diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 01b258e23c..b80d10d34c 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -69,8 +69,8 @@ workflows: '.github/workflows/menu.yml': - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' - '.github/workflows/nightly.yml': - - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nightly.yml': [] + '.github/workflows/pbr.yml': [] '.github/workflows/pcraft-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' diff --git a/.github/workflows/ai-core.yml b/.github/workflows/ai-core.yml index 6f5b34e892..2be123b233 100644 --- a/.github/workflows/ai-core.yml +++ b/.github/workflows/ai-core.yml @@ -3,7 +3,7 @@ name: AI model on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/ai-core/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ai-core.yml'] pull_request: paths: ['crates/ai-core/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ai-core.yml'] diff --git a/.github/workflows/atomic.yml b/.github/workflows/atomic.yml index b8bcc8b8ea..6afdafc290 100644 --- a/.github/workflows/atomic.yml +++ b/.github/workflows/atomic.yml @@ -3,7 +3,7 @@ name: Atomic file writes on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/atomic/**', 'crates/settings/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/atomic.yml'] pull_request: paths: ['crates/atomic/**', 'crates/settings/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/atomic.yml'] diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index 6063c4e4dc..5fd971c629 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -2,7 +2,7 @@ name: Shared audio on: push: - branches: [main, next] + branches: [main] paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] pull_request: paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] diff --git a/.github/workflows/cms.yml b/.github/workflows/cms.yml index b13dd82d14..c1737392da 100644 --- a/.github/workflows/cms.yml +++ b/.github/workflows/cms.yml @@ -3,7 +3,7 @@ name: Colour management on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml'] pull_request: paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml'] diff --git a/.github/workflows/crw.yml b/.github/workflows/crw.yml index 3e9b430d67..10e5b7ccf7 100644 --- a/.github/workflows/crw.yml +++ b/.github/workflows/crw.yml @@ -2,7 +2,7 @@ name: Shared CRW on: push: - branches: [main, next] + branches: [main] paths: ["crates/crw/**", "scripts/fetch-crw-samples.py", "Cargo.toml", "Cargo.lock", ".github/workflows/crw.yml"] pull_request: paths: ["crates/crw/**", "scripts/fetch-crw-samples.py", "Cargo.toml", "Cargo.lock", ".github/workflows/crw.yml"] @@ -52,7 +52,7 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - # Pull requests restore the entry main or next saved and never write their own: the same + # Pull requests restore the entry main saved and never write their own: the same # files saved once per pull request took a share of the 10 GB cache budget. - name: Restore the CC0 sample files id: samples diff --git a/.github/workflows/dialogs.yml b/.github/workflows/dialogs.yml index f9ab8fe56e..23def9feb0 100644 --- a/.github/workflows/dialogs.yml +++ b/.github/workflows/dialogs.yml @@ -3,7 +3,7 @@ name: Dialogs on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/dialogs/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/dialogs.yml'] pull_request: paths: ['crates/dialogs/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/dialogs.yml'] diff --git a/.github/workflows/doc.yml b/.github/workflows/doc.yml index 00b8336db1..6275433817 100644 --- a/.github/workflows/doc.yml +++ b/.github/workflows/doc.yml @@ -3,7 +3,7 @@ name: Craft documents on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/doc/**', 'crates/pcraft-format/**', 'crates/vectorcraft-format/**', 'crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/doc.yml'] pull_request: paths: ['crates/doc/**', 'crates/pcraft-format/**', 'crates/vectorcraft-format/**', 'crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/doc.yml'] diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index fc51a0da51..cb54dbf119 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -6,7 +6,7 @@ name: Docs on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml'] pull_request: paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml'] diff --git a/.github/workflows/ecproj-format.yml b/.github/workflows/ecproj-format.yml index bec96fed5c..048c897b3c 100644 --- a/.github/workflows/ecproj-format.yml +++ b/.github/workflows/ecproj-format.yml @@ -3,7 +3,7 @@ name: EffectCraft project format on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ecproj-format.yml'] pull_request: paths: ['crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ecproj-format.yml'] diff --git a/.github/workflows/font-store.yml b/.github/workflows/font-store.yml index fd599d207c..e655697b3d 100644 --- a/.github/workflows/font-store.yml +++ b/.github/workflows/font-store.yml @@ -3,7 +3,7 @@ name: Font store on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/font-store/**', 'crates/font-catalog/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/font-store.yml'] pull_request: paths: ['crates/font-store/**', 'crates/font-catalog/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/font-store.yml'] diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index 37796f6816..2ee6fc6281 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -2,7 +2,7 @@ name: Shared format crates on: push: - branches: [main, next] + branches: [main] paths: - "crates/xml/**" - "crates/mime/**" @@ -15,8 +15,10 @@ on: - "crates/silhouette-studio/**" - "crates/tiff/**" - "crates/heif/**" + - "crates/pst/**" - "crates/cms/**" - "crates/cdr/**" + - "crates/texture/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/formats.yml" @@ -33,8 +35,10 @@ on: - "crates/silhouette-studio/**" - "crates/tiff/**" - "crates/heif/**" + - "crates/pst/**" - "crates/cms/**" - "crates/cdr/**" + - "crates/texture/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/formats.yml" @@ -67,9 +71,11 @@ jobs: - { crate: craft-svg-paths, features: "" } - { crate: craft-silhouette-studio, features: "" } - { crate: craft-tiff, features: "" } - - { crate: craft-heif, features: "testdata" } + - { crate: craft-heif, features: "testdata test-support" } + - { crate: craft-pst, features: "test-writer test-support" } - { crate: craft-cms, features: "" } - { crate: craft-cdr, features: "synth" } + - { crate: craft-texture, features: "dds parallel" } # fmt, clippy with default and with all features, and the tests run in the Workspace gate on # every OS; this lints each feature alone and checks the web build. name: ${{ matrix.crate }} feature sets, WASM diff --git a/.github/workflows/full-validation.yml b/.github/workflows/full-validation.yml index 85ad96f2fe..652e2b1f13 100644 --- a/.github/workflows/full-validation.yml +++ b/.github/workflows/full-validation.yml @@ -32,7 +32,9 @@ jobs: craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1 - env: CRAFT_PRINT_REQUIRE_QUEUE=0 + env: | + CRAFT_PRINT_REQUIRE_QUEUE=0 + CRAFT_HOSTILE_DIVISOR=1 setup-command: bash scripts/ci-test-inputs.sh command: | python scripts/test-full-validation.py diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml index 7ee967c65b..de64ad3ee4 100644 --- a/.github/workflows/house-rules.yml +++ b/.github/workflows/house-rules.yml @@ -2,7 +2,7 @@ name: House rules on: push: - branches: [main, next] + branches: [main] paths: - AGENTS.md - CLAUDE.md diff --git a/.github/workflows/jpeg.yml b/.github/workflows/jpeg.yml index ebb27bafde..495af8b232 100644 --- a/.github/workflows/jpeg.yml +++ b/.github/workflows/jpeg.yml @@ -2,7 +2,7 @@ name: Shared JPEG on: push: - branches: [main, next] + branches: [main] paths: ["crates/jpeg/**", "Cargo.toml", "Cargo.lock", ".github/workflows/jpeg.yml"] pull_request: paths: ["crates/jpeg/**", "Cargo.toml", "Cargo.lock", ".github/workflows/jpeg.yml"] diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index bfce473788..47a5576499 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -2,7 +2,7 @@ name: Keymap on: push: - branches: [main, next] + branches: [main] paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] pull_request: paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index 090ad84da9..f4c4e6689b 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -2,7 +2,7 @@ name: Shared media on: push: - branches: [main, next] + branches: [main] paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] pull_request: paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] diff --git a/.github/workflows/menu.yml b/.github/workflows/menu.yml index 80b6678cd3..b12c8bcc6a 100644 --- a/.github/workflows/menu.yml +++ b/.github/workflows/menu.yml @@ -2,7 +2,7 @@ name: Menu on: push: - branches: [main, next] + branches: [main] paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"] pull_request: paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"] diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 5cc8032668..e5108dfa5a 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,7 +1,7 @@ name: Nightly full tests # The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep -# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The +# with CRAFT_HOSTILE_DIVISOR=1 (every member, no sample), and every proptest at its own case count (no PROPTEST_CASES). The # rest of the workspace's tests run with them, on Linux, with the gate's setup. on: schedule: @@ -26,37 +26,12 @@ jobs: packages: mesa-vulkan-drivers libvulkan1 craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan - env: CRAFT_PRINT_REQUIRE_QUEUE=0 + env: | + CRAFT_PRINT_REQUIRE_QUEUE=0 + CRAFT_HOSTILE_DIVISOR=1 setup-command: bash scripts/ci-test-inputs.sh cache-paths: .test-inputs/photocraft/corpus cache-key: photocraft-corpus cache-key-files: scripts/ci-test-inputs.sh # The gate's build (the same targets and profile overrides), with every test at its full count. command: bash scripts/ci-workspace-tests.sh full - - # The scheduled run is main's; this starts the full tests above on next too, where the gate - # runs the same fractions. It also starts one Workspace run on next a day that nothing cancels - # (pull requests run the Linux legs only, and pushes to next cancel each other's runs): next's - # macOS and Windows legs then run in full at least once a day, and its Linux leg builds from - # source and saves next's own workspace-crates cache entry, which pull requests into next - # restore. Main gets the same from workspace.yml's own scheduled runs. The only job here with - # `actions: write`; it checks out and runs nothing from the repository. - workspace-next: - name: Workspace on next - if: github.event_name == 'schedule' - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - actions: write - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - name: Start the Workspace workflow and these full tests on next - env: - GH_TOKEN: ${{ github.token }} - REPO: ${{ github.repository }} - run: | - gh workflow run workspace.yml --repo "$REPO" --ref next - gh workflow run nightly.yml --repo "$REPO" --ref next diff --git a/.github/workflows/pbr.yml b/.github/workflows/pbr.yml new file mode 100644 index 0000000000..51c3a62daa --- /dev/null +++ b/.github/workflows/pbr.yml @@ -0,0 +1,29 @@ +name: PBR feature tests + +on: + workflow_dispatch: + push: + branches: [main, next] + paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml'] + pull_request: + paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml'] + +permissions: + contents: read + +jobs: + features: + name: PBR ${{ matrix.mode }} tests + strategy: + fail-fast: false + matrix: + include: + - { mode: serial, arguments: '' } + - { mode: parallel, arguments: '--features parallel' } + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest"]' + craft-fonts-ref: '' + require-craft-fonts: false + timeout-minutes: 30 + command: cargo test -p craft-pbr --locked ${{ matrix.arguments }} diff --git a/.github/workflows/pcraft-format.yml b/.github/workflows/pcraft-format.yml index cefa5360c4..0e4feabc92 100644 --- a/.github/workflows/pcraft-format.yml +++ b/.github/workflows/pcraft-format.yml @@ -3,7 +3,7 @@ name: PhotoCraft format on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/pcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pcraft-format.yml'] pull_request: paths: ['crates/pcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pcraft-format.yml'] diff --git a/.github/workflows/pdf.yml b/.github/workflows/pdf.yml index 1550512ac5..0269fdc7ea 100644 --- a/.github/workflows/pdf.yml +++ b/.github/workflows/pdf.yml @@ -2,7 +2,7 @@ name: Shared PDF on: push: - branches: [main, next] + branches: [main] paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**", "vendor/vello_common/**", "vendor/vello_cpu/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"] pull_request: paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**", "vendor/vello_common/**", "vendor/vello_cpu/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"] diff --git a/.github/workflows/proof.yml b/.github/workflows/proof.yml index 0f5b869a4a..ea5edb8a56 100644 --- a/.github/workflows/proof.yml +++ b/.github/workflows/proof.yml @@ -2,7 +2,7 @@ name: Proofing on: push: - branches: [main, next] + branches: [main] paths: ["crates/proof/**", "Cargo.toml", "Cargo.lock", ".github/workflows/proof.yml"] pull_request: paths: ["crates/proof/**", "Cargo.toml", "Cargo.lock", ".github/workflows/proof.yml"] diff --git a/.github/workflows/theme.yml b/.github/workflows/theme.yml index 213a74b147..f0bb32a466 100644 --- a/.github/workflows/theme.yml +++ b/.github/workflows/theme.yml @@ -3,7 +3,7 @@ name: Suite themes on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml'] pull_request: paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml'] diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index 0ea3b8c1bb..e5e3e71d15 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -3,7 +3,7 @@ name: App updates on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/update/**', 'Cargo.toml', 'Cargo.lock', 'rustfmt.toml', 'clippy.toml', '.github/workflows/update.yml'] pull_request: paths: ['crates/update/**', 'Cargo.toml', 'Cargo.lock', 'rustfmt.toml', 'clippy.toml', '.github/workflows/update.yml'] diff --git a/.github/workflows/vectorcraft-format.yml b/.github/workflows/vectorcraft-format.yml index 0ca15636df..cd66615a50 100644 --- a/.github/workflows/vectorcraft-format.yml +++ b/.github/workflows/vectorcraft-format.yml @@ -3,7 +3,7 @@ name: VectorCraft format on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/vectorcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/vectorcraft-format.yml'] pull_request: paths: ['crates/vectorcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/vectorcraft-format.yml'] diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index 03b59cc427..20afe0d700 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -2,7 +2,7 @@ name: Shared video on: push: - branches: [main, next] + branches: [main] paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] pull_request: paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] diff --git a/.github/workflows/web-api.yml b/.github/workflows/web-api.yml index 0ad01e28fd..f0f8e22da7 100644 --- a/.github/workflows/web-api.yml +++ b/.github/workflows/web-api.yml @@ -3,7 +3,7 @@ name: Web API (page command API) on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/web-api/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/web-api.yml'] pull_request: paths: ['crates/web-api/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/web-api.yml'] diff --git a/.github/workflows/web-host.yml b/.github/workflows/web-host.yml index 055303bc26..dc0254850a 100644 --- a/.github/workflows/web-host.yml +++ b/.github/workflows/web-host.yml @@ -2,7 +2,7 @@ name: Shared web host on: push: - branches: [main, next] + branches: [main] paths: ["crates/web-host/**", "Cargo.toml", "Cargo.lock", ".github/workflows/web-host.yml"] pull_request: paths: ["crates/web-host/**", "Cargo.toml", "Cargo.lock", ".github/workflows/web-host.yml"] diff --git a/.github/workflows/window.yml b/.github/workflows/window.yml index a534393fdc..5f05883d14 100644 --- a/.github/workflows/window.yml +++ b/.github/workflows/window.yml @@ -3,7 +3,7 @@ name: Window decorations on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml'] pull_request: paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml'] diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 5c802e799e..b1a0ee2ffd 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -2,7 +2,7 @@ name: Workspace on: push: - branches: [main, next] + branches: [main] tags: ["v*"] pull_request: workflow_dispatch: @@ -16,13 +16,12 @@ permissions: contents: read concurrency: - # A pull request, main and next each have one group, so a newer push cancels the run it - # supersedes; the newest push's run still tests everything before it. Every other run (a release - # tag, a manual run, the scheduled run, nightly.yml's run on next) gets a group of its own and is - # neither cancelled nor replaced while queued: a release run always finishes, the scheduled run - # saves the caches, and next gets one complete macOS and Windows run a day. - group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next') && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next' }} + # A pull request and main each have one group, so a newer push cancels the run it supersedes; the + # newest push's run still tests everything before it. Every other run (a release tag, a manual + # run, the scheduled run) gets a group of its own and is neither cancelled nor replaced while + # queued: a release run always finishes, and the scheduled run saves the caches. + group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }} jobs: # Whether this run needs the macOS and Windows legs, and which tests every leg runs @@ -71,7 +70,7 @@ jobs: # The macOS and Windows legs cache dependencies only, so `deps-profile` hashes only the # settings that reach a dependency: `[profile.dev]` and `[profile.dev.package."*"]`. Every # other override names a workspace crate (scripts/test-workspace-tests.py), so changing one - # keeps those entries, and next's runs restore main's. + # keeps those entries. - uses: actions/checkout@v7.0.1 if: github.event_name != 'pull_request' with: @@ -104,13 +103,10 @@ jobs: # The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each # main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo # rebuilds only the crates a change reaches. `cache-prune` keeps the newest entry. The midnight - # scheduled run builds from source (`cold-build`) and starts the entry afresh. next has an entry - # of its own, since main's is built from different code and lockfile and a pull request into next - # rebuilt nearly everything from it (15.5 minutes): nightly.yml's daily manual run on next builds - # from source and saves it (`cache-save-on-dispatch`), and pull requests into next restore it - # before main's. The macOS and Windows legs keep a dependency-only entry: their workspace crates - # would not fit the 10 GB cache budget beside Linux's. The lint legs keep no cache - # (`lint-cache: false`) for the same reason; a cold lint leg is still shorter than its gate leg. + # scheduled run builds from source (`cold-build`) and starts the entry afresh. The macOS and + # Windows legs keep a dependency-only entry: their workspace crates would not fit the 10 GB cache + # budget beside Linux's. The lint legs keep no cache (`lint-cache: false`) for the same reason; a + # cold lint leg is still shorter than its gate leg. native: name: Workspace needs: platforms @@ -118,9 +114,8 @@ jobs: with: os: '["ubuntu-latest"]' cache-workspace-crates: true - cache-save-on-dispatch: true cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }} - cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }} + cold-build: ${{ github.event.schedule == '17 0 * * *' }} lint-cache: false # The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a # workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them. @@ -182,7 +177,7 @@ jobs: # The macOS and Windows legs, with the Linux leg's inputs. They take 1.5-2 hours against the Linux # leg's 15-40 minutes, so a pull request does not wait for them: they run after the merge, on - # every push to main and next, on main's scheduled runs and on nightly.yml's daily run on next. + # every push to main and on main's scheduled runs. # A pull request that needs them before it merges gets the full-ci label. native-platforms: name: Workspace @@ -192,7 +187,7 @@ jobs: with: os: '["windows-latest","macos-latest"]' lint-cache: false - # Named by the dependency settings alone (`deps-profile`), so next restores main's entries. + # Named by the dependency settings alone (`deps-profile`). cache-version: v2-${{ needs.platforms.outputs.deps-profile }} timeout-minutes: *timeout tools: *tools @@ -212,15 +207,14 @@ jobs: lint-command: *lint command: *command - # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), as - # does the daily manual run on next, and every run restores only the newest. This deletes the - # older ones of the run's branch as soon as the Linux leg is done, instead of leaving them to the - # 10 GB budget's eviction, which would evict other entries too. The only job with - # `actions: write`; it checks out and runs nothing from the repository. + # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), and + # every run restores only the newest. This deletes the older ones as soon as the Linux leg is + # done, instead of leaving them to the 10 GB budget's eviction, which would evict other entries + # too. The only job with `actions: write`; it checks out and runs nothing from the repository. cache-prune: name: cache prune needs: native - if: ${{ !cancelled() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/next') }} + if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -234,11 +228,10 @@ jobs: env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} - REF: ${{ github.ref }} run: | set -euo pipefail # `-rust---crates-----...`, newest first. - gh cache list --repo "$REPO" --ref "$REF" --limit 100 --sort created_at --order desc --json id,key \ + gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \ --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" declare -A kept while read -r id key; do diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 34e0bcd6f3..55ff91d455 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -94,6 +94,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso | `crates/raster-codecs/src/xpm/x11_colors.rs` | X.Org Foundation and X11 contributors (X11 `rgb.txt` colour names and values, normalised into a lookup table) | , via [PhotoCraft `crates/codecs`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/codecs/src/codecs/xpm) | MIT (X.Org app/rgb) | | `crates/psd/tests/fixtures/atn/*.atn` (seven synthetic action sets, encoded field by field; `crates/psd/tests/fixtures/atn/README.md`) | PhotoCraft contributors | [PhotoCraft `crates/psd/tests/fixtures/atn`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/psd/tests/fixtures/atn) | MIT OR Apache-2.0 | | `crates/lottie/tests/fixtures/` | EffectCraft contributors (original work: four hand-written Lottie JSON documents, written from the public Lottie format description; not exported from any Adobe product or third-party file) | [EffectCraft `crates/lottie/tests/fixtures`](https://github.com/storytold/effectcraft/tree/e18f48fb/crates/lottie/tests/fixtures) | MIT OR Apache-2.0 | +| `crates/i18n-build/tests/fixture/` | craft-libs contributors (original work: nine hand-written catalogs of a few common interface words, in craft-i18n's catalog format; not copied from craft-i18n or any app) | this repository | MIT OR Apache-2.0 | | `crates/pkcs7/tests/data/` | PdfCraft contributors (original work: throw-away test keys and certificates made with OpenSSL 3 for these tests, as seven PKCS #12 files with the password `test` and two PEM certificates; they protect nothing; commands in `crates/pkcs7/tests/data/README.md`) | [PdfCraft `crates/sign/tests/data`](https://github.com/storytold/pdfcraft/tree/1d7a9f9f/crates/sign/tests/data) | MIT OR Apache-2.0 | | `crates/affinity/tests/support/corpus.tsv`, `crates/affinity/tests/support/affinity3-signatures.txt` (manifest and measured signatures only; the 113 files, 90 of them documents, are not bundled, `scripts/fetch-affinity-corpus.sh` downloads them outside the checkout) | The authors of each document: samuel-etver (vector-art), satoshoe-dev (affinity-samples), Seth A. Robinson (Patchy fixtures), Nick Beeuwsaert (AFDesignLoad), Jeremy Cantu (Branding), eviltwo (AssetStoreTemplate), Square (leakcanary) | each file's pinned upstream URL and SHA-256 in the manifest; every name from [VectorCraft `xtask/src/affinity_corpus.rs`](https://github.com/storytold/vectorcraft/blob/bada8e17103db9917de44e40a1cead5a7fc71c3c/xtask/src/affinity_corpus.rs) and [PhotoCraft `xtask/affinity-corpus.sha256`](https://github.com/storytold/photocraft/blob/629751503165118d5fec5f70e64fe2d6592f7b53/xtask/affinity-corpus.sha256) | CC0-1.0, MIT or Apache-2.0 (per file, in the manifest) | | `crates/raw/docs/coverage/adobe-cameras.tsv` | Facts (maker, model, extension, profile, minimum Camera Raw version) parsed by LightCraft contributors from Adobe's published list | [Adobe Camera Raw supported cameras](https://helpx.adobe.com/camera-raw/desktop/dng-and-file-formats/camera-raw-plug-supported-cameras.html), Wayback capture 20261003133011; moved from [LightCraft `docs/raw`](https://github.com/storytold/lightcraft/tree/5ff567a4a2e067bef1b6bce152c11e7f727ccbaf/docs/raw) | Facts, not copyrightable expression; the file is MIT OR Apache-2.0 | @@ -124,6 +125,8 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper `crates/audio-dsp` combines FilmCraft `crates/audio-dsp` at `3f137a7ed420cac79b32145f5243b7f98b31f71c` and SoundCraft `crates/dsp` at `648ed9db9a0e98cc55643babffac381521a556c8` (both MIT OR Apache-2.0). `crates/audio-dsp/NOTICE` keeps the copyright notices of both projects. +`crates/audio-dsp/src/effects/voice.rs` adapts the two crossfaded read taps of SoundCraft `crates/dsp/src/plugins/pitch.rs` and the YIN pitch tracker of `crates/dsp/src/pitch_detect.rs` at `915481be1b49d7e0502e07b059d0c0198c61911a` (MIT OR Apache-2.0). The taps are centered on a fixed 10 ms latency and spaced by whole periods of the tracked pitch, and the tracker runs on a decimated copy of the input in buffers sized at creation. + ## GIMP palette reader `crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. @@ -171,6 +174,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. `crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. +## GPU device selection + +`crates/gpu-device`'s adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both. + ## Dalvik DEX inspection `crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained. diff --git a/Cargo.lock b/Cargo.lock index 4b32db1727..858d8604d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1125,32 +1125,36 @@ dependencies = [ [[package]] name = "candle-core" -version = "0.9.2" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c15b675b80d994b2eadb20a4bbe434eabeb454eac3ee5e2b4cf6f147ee9be091" +checksum = "d11c8be87cfbaef9ebb62fb3f850d1fc8e00cc1d11d393fdbe55a4d5c2cdb325" dependencies = [ "byteorder", "float8", "gemm", "half", + "libc", "libm", "memmap2", "num-traits", "num_cpus", + "parking_lot", "rand 0.9.5", "rand_distr", "rayon", "safetensors", "thiserror 2.0.21", + "tokenizers", "yoke", - "zip 7.4.0", + "zerocopy", + "zip", ] [[package]] name = "candle-nn" -version = "0.9.2" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3045fa9e7aef8567d209a27d56b692f60b96f4d0569f4c3011f8ca6715c65e03" +checksum = "437fabe77547c2447c7bdf3cc946e19db29a2832440176b419f77c80b0a9a05e" dependencies = [ "candle-core", "half", @@ -1164,14 +1168,14 @@ dependencies = [ [[package]] name = "candle-transformers" -version = "0.9.2" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b538ec4aa807c416a2ddd3621044888f188827862e2a6fcacba4738e89795d01" +checksum = "2b1e1abeac23d7df4f94e8a3852b3dbb661d332e37c3bef479507bac867187b2" dependencies = [ "byteorder", "candle-core", "candle-nn", - "fancy-regex 0.17.0", + "fancy-regex 0.19.2", "num-traits", "rand 0.9.5", "rayon", @@ -1786,6 +1790,7 @@ dependencies = [ "craft-drawingml", "craft-dwg", "craft-dxf", + "craft-ease", "craft-ecproj-format", "craft-elf", "craft-eps", @@ -1814,6 +1819,7 @@ dependencies = [ "craft-geom", "craft-gif", "craft-gpu", + "craft-gpu-device", "craft-gpu-null", "craft-gpu-providers", "craft-gpu-wgpu", @@ -1826,6 +1832,7 @@ dependencies = [ "craft-html", "craft-http-url", "craft-i18n", + "craft-i18n-build", "craft-ical", "craft-idml", "craft-image-codecs", @@ -1869,6 +1876,7 @@ dependencies = [ "craft-ora", "craft-pages", "craft-palette", + "craft-pbr", "craft-pcap", "craft-pcraft-bundle", "craft-pcraft-format", @@ -1898,6 +1906,7 @@ dependencies = [ "craft-review", "craft-rtf", "craft-sbs", + "craft-scopes", "craft-score", "craft-scraft-format", "craft-settings", @@ -2273,14 +2282,15 @@ version = "0.1.0" dependencies = [ "craft-ai-agents", "craft-atomic", + "craft-control-protocol", "craft-flags", "craft-platform", "dirs", - "getrandom 0.3.4", "log", "proptest", "serde", "serde_json", + "socket2", "tempfile", ] @@ -2288,6 +2298,7 @@ dependencies = [ name = "craft-control-protocol" version = "0.1.0" dependencies = [ + "getrandom 0.3.4", "serde_json", "subtle", ] @@ -2342,7 +2353,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -2482,7 +2493,7 @@ dependencies = [ "craft-zip", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -2493,6 +2504,7 @@ dependencies = [ "chrono", "craft-cfb", "craft-drawingml", + "craft-flow", "craft-math", "craft-offcrypto", "craft-opc", @@ -2507,7 +2519,7 @@ dependencies = [ "thiserror 2.0.21", "unicode-bidi", "zeroize", - "zip 9.1.3", + "zip", ] [[package]] @@ -2567,6 +2579,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-ease" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "craft-ecproj-format" version = "0.1.0" @@ -2602,7 +2622,7 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -2641,6 +2661,7 @@ dependencies = [ "exr", "flate2", "half", + "serde", "serde_json", "thiserror 2.0.21", ] @@ -2666,7 +2687,7 @@ dependencies = [ "ruzstd", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -2677,7 +2698,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -2902,6 +2923,18 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-gpu-device" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "log", + "pollster 0.4.0", + "serde", + "serde_json", + "wgpu", +] + [[package]] name = "craft-gpu-null" version = "0.1.0" @@ -3024,6 +3057,21 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-i18n-build" +version = "0.1.0" +dependencies = [ + "craft-i18n", + "craft-i18n-build-consumer", +] + +[[package]] +name = "craft-i18n-build-consumer" +version = "0.1.0" +dependencies = [ + "craft-i18n-build", +] + [[package]] name = "craft-ical" version = "0.1.0" @@ -3039,7 +3087,7 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -3047,6 +3095,7 @@ name = "craft-image-codecs" version = "0.1.0" dependencies = [ "avif-serialize", + "craft-cms", "craft-dds", "craft-heif", "craft-jpeg", @@ -3062,7 +3111,7 @@ dependencies = [ "hayro-jpeg2000", "image", "image-webp", - "jpeg-encoder 0.6.1", + "jpeg-encoder 0.7.1", "jxl-oxide", "png 0.18.1", "proptest", @@ -3206,7 +3255,7 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -3338,6 +3387,7 @@ dependencies = [ "craft-frame", "craft-media", "craft-time", + "craft-video", "craft-y4m", "serde", "serde_json", @@ -3437,6 +3487,8 @@ dependencies = [ "base64 0.23.1", "chrono", "craft-flow", + "craft-html", + "craft-markdown", "craft-math", "craft-metafile", "craft-wordmodel", @@ -3452,7 +3504,7 @@ dependencies = [ "sha2 0.11.1", "thiserror 2.0.21", "zeroize", - "zip 9.1.3", + "zip", ] [[package]] @@ -3460,6 +3512,7 @@ name = "craft-ods" version = "0.1.0" dependencies = [ "craft-odf", + "craft-ods", "craft-sheet", "craft-xml", "thiserror 2.0.21", @@ -3489,7 +3542,7 @@ dependencies = [ "craft-zip", "log", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -3515,7 +3568,7 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -3538,6 +3591,17 @@ dependencies = [ name = "craft-palette" version = "0.1.0" +[[package]] +name = "craft-pbr" +version = "0.1.0" +dependencies = [ + "craft-texture", + "glam 0.30.10", + "naga", + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-pcap" version = "0.1.0" @@ -3641,7 +3705,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -3991,6 +4055,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-scopes" +version = "0.1.0" +dependencies = [ + "craft-color", + "serde", + "serde_json", +] + [[package]] name = "craft-score" version = "0.1.0" @@ -4075,7 +4148,7 @@ dependencies = [ "kurbo", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -4243,6 +4316,12 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "libc", + "rustix 1.1.6", + "sha2 0.10.9", + "skrifa 0.47.0", +] [[package]] name = "craft-text" @@ -4621,11 +4700,13 @@ dependencies = [ name = "craft-update" version = "0.1.0" dependencies = [ + "base64 0.22.1", "chrono", "craft-host", "craft-theme", "craft-ui", "dunce", + "ed25519-dalek 2.2.0", "egui", "flate2", "image", @@ -4638,11 +4719,12 @@ dependencies = [ "sha2 0.10.9", "tar", "tempfile", + "toml", "ureq", "verifysign", "winreg", "winsafe", - "zip 9.1.3", + "zip", ] [[package]] @@ -4875,8 +4957,10 @@ name = "craft-xtask" version = "0.1.0" dependencies = [ "craft-atomic", + "libc", "serde_json", "tempfile", + "toml_edit", ] [[package]] @@ -4899,7 +4983,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.3", + "zip", ] [[package]] @@ -5130,6 +5214,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "daachorse" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5614204febbc33cc07a2806aa6440b904ac012b68eecc37f4493ea4a76455a3d" + [[package]] name = "darling" version = "0.20.11" @@ -5203,7 +5293,7 @@ checksum = "e917a58e17b27d2f15626c490754ccced7f46592dc5b5f39a3013b89cba5f068" dependencies = [ "astc-decode", "bitflags 2.13.2", - "glam", + "glam 0.25.0", "resize", "zerocopy", ] @@ -5596,7 +5686,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "emath", @@ -5652,7 +5742,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5687,7 +5777,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "accesskit", "ahash", @@ -5706,7 +5796,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5725,7 +5815,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5745,7 +5835,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "egui", @@ -5758,7 +5848,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "eframe", "egui", @@ -5835,7 +5925,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", ] @@ -5908,7 +5998,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5934,7 +6024,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[package]] name = "equator" @@ -6209,9 +6299,9 @@ dependencies = [ [[package]] name = "float8" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719a903cc23e4a89e87962c2a80fdb45cdaad0983a89bd150bb57b4c8571a7d5" +checksum = "c2d1f04709a8ac06e8e8042875a3c466cc4832d3c1a18dbcb9dba3c6e83046bc" dependencies = [ "half", "num-traits", @@ -6750,6 +6840,12 @@ version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" +[[package]] +name = "glam" +version = "0.30.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9" + [[package]] name = "glifo" version = "0.1.1" @@ -11434,13 +11530,15 @@ checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" [[package]] name = "safetensors" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "675656c1eabb620b921efea4f9199f97fc86e36dd6ffd1fbbe48d0f59a4987f5" +checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846" dependencies = [ "hashbrown 0.16.1", + "libc", "serde", "serde_json", + "tempfile", ] [[package]] @@ -12834,16 +12932,17 @@ dependencies = [ [[package]] name = "tokenizers" -version = "0.22.2" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b238e22d44a15349529690fb07bd645cf58149a1b1e44d6cb5bd1641ff1a6223" +checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc" dependencies = [ "ahash", - "aho-corasick", "compact_str", + "daachorse", "dary_heap", "derive_builder", "esaxx-rs", + "fancy-regex 0.17.0", "getrandom 0.3.4", "itertools 0.14.0", "log", @@ -13089,12 +13188,6 @@ dependencies = [ "rustc-hash 2.1.3", ] -[[package]] -name = "typed-path" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" - [[package]] name = "typed-path" version = "0.13.0" @@ -15149,18 +15242,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "zip" -version = "7.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980" -dependencies = [ - "crc32fast", - "indexmap", - "memchr", - "typed-path 0.12.4", -] - [[package]] name = "zip" version = "9.1.3" @@ -15173,7 +15254,7 @@ dependencies = [ "indexmap", "memchr", "nix", - "typed-path 0.13.0", + "typed-path", "windows-sys 0.61.2", ] @@ -15266,19 +15347,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" diff --git a/Cargo.toml b/Cargo.toml index f842c026e6..ea77bf6c48 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,7 @@ acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-plist = { path = "crates/plist" } +craft-gpu-device = { path = "crates/gpu-device" } craft-wasm = { path = "crates/wasm" } craft-platform = { path = "crates/platform" } craft-png = { path = "crates/png" } @@ -82,6 +83,7 @@ craft-cloud = { path = "crates/cloud" } craft-cloud-local = { path = "crates/cloud-local" } craft-cloud-ui = { path = "crates/cloud-ui" } craft-color = { path = "crates/color" } +craft-scopes = { path = "crates/scopes" } craft-color-ui = { path = "crates/color-ui" } craft-color-transform = { path = "crates/color-transform" } craft-frame = { path = "crates/frame" } @@ -103,6 +105,7 @@ craft-deckcraft-format = { path = "crates/deckcraft-format" } craft-designcraft-format = { path = "crates/designcraft-format" } craft-dxf = { path = "crates/dxf" } craft-drawingml = { path = "crates/drawingml" } +craft-ease = { path = "crates/ease" } craft-eps = { path = "crates/eps" } craft-elf = { path = "crates/elf" } craft-file-formats = { path = "crates/file-formats" } @@ -146,6 +149,7 @@ craft-gpu-null = { path = "crates/gpu-null" } craft-gpu-providers = { path = "crates/gpu-providers" } craft-gpu-wgpu = { path = "crates/gpu-wgpu" } craft-i18n = { path = "crates/i18n" } +craft-i18n-build = { path = "crates/i18n-build" } craft-ipc = { path = "crates/ipc" } craft-idml = { path = "crates/idml" } craft-indd = { path = "crates/indd" } @@ -228,6 +232,7 @@ craft-testkit = { path = "crates/testkit" } craft-text = { path = "crates/text" } craft-tcraft = { path = "crates/tcraft" } craft-texture = { path = "crates/texture" } +craft-pbr = { path = "crates/pbr" } craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } craft-tiff = { path = "crates/tiff" } @@ -318,20 +323,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } 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 c63edc0812..4a2d1084e4 100644 --- a/NOTICE +++ b/NOTICE @@ -229,6 +229,26 @@ The colour management module in crates/cms is extracted from: Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain (CC0-1.0); see ATTRIBUTION.md. +The image-based lighting in crates/pbr (craft-pbr) is adapted from: +- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc, + copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs. + https://github.com/storytold/texturecraft + Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors. +- MaterialCraft, crates/render/src/ibl.rs, revision 4ff5af9af7371613ee37b186e03caf49ee6dbd88, + whose differing parts are copied to crates/pbr/tests/it/reference/materialcraft.rs. + https://github.com/storytold/materialcraft + Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors. +The BRDF, environment BRDF and default environment in crates/pbr are adapted from: +- EffectCraft, crates/render/src/three_d/adv/shade.rs and adv/scene.rs, revision + 41da144555a1c8ddbbe94876a00259832322d00c, whose shading functions and default environment + are copied to crates/pbr/tests/it/reference/effectcraft.rs. + https://github.com/storytold/effectcraft + Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. +The WGSL text in crates/pbr/src/shade.wgsl is adapted from: +- EffectCraft, crates/gpu/src/shaders/advanced3d.wgsl, revision + f4d45dfef3a280d96aff1d4eb5f1950160adefc2 (above). +All four sources are licensed MIT OR Apache-2.0. crates/pbr/README.md lists the changes from them. + Optional PDF writer Krilla 0.8.2 (https://github.com/LaurenzV/krilla), MIT OR Apache-2.0. @@ -269,9 +289,10 @@ linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs, -src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its manifest names Joe Neeman as author, and -its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/linesweeper/README.craft.md and -vendor/linesweeper/SOURCE.json for provenance, the local patches and the files left out. +src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its +manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See +vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local +patches and the files left out. Platform lifecycle source provenance diff --git a/README.md b/README.md index 7884f375af..af82eafac8 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from FilmCraft. +- [`craft-cdr`](crates/cdr/README.md): bounded reader and writer of `.cdr` drawings: versions 1 to + 27 and `.cmx` files read into one drawing model (pages, layers, groups, shapes, fills and + outlines), and version 15 `.cdr` files written. - [`craft-cfb`](crates/cfb/README.md): clean-room Compound File Binary ([MS-CFB], OLE structured storage) reader and writer: the container of legacy Office files, Outlook messages, encrypted OOXML packages and AAF. Bounded on hostile input; what the streams hold stays with each format. @@ -126,6 +129,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit EMU units and `a:xfrm`, colours with theme slots and colour transforms, preset shape outlines (`a:prstGeom`), custom geometry with guide formulas (`a:custGeom`) and preset text warps (`a:prstTxWarp`). From DeckCraft. Takes `craft-xml` trees; packages stay with each format. +- [`craft-ease`](crates/ease/README.md): easing curves, keyed tracks, constant-speed motion paths + and damped springs for animation: named eases, CSS `cubic-bezier()`, speed and influence, + editable custom and sampled curves, hold keys and a spring stepped by its exact solution. + From AniCraft and EffectCraft. No dependencies without the optional `serde` feature. - [`craft-elf`](crates/elf/src/lib.rs): ELF program headers and dynamic section entries from untrusted bytes, from Craft Anything: 32- or 64-bit in either byte order, bounded counts and overflow-checked offsets, virtual-address-to-file mapping through `PT_LOAD`, and segment, permission and dynamic tag names. - [`craft-eps`](crates/eps/README.md): Encapsulated PostScript files as a container: the binary preview header (read and write), the DSC header comments and bounding boxes (also `(atend)`), @@ -204,6 +211,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit every frame's position, delay, disposal and transparent colour, the loop count and the first frame's colour table, without decompressing pixels. Tells an animation from a still and whether a file can hold the picture it declares before a decoder runs. +- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto, + low power, a named adapter that survives a reordered list and a driver update, or software; + corrections for drivers that crash; the next adapter and then a software one when a device fails + to open; a capability report; device-loss and error recording without panics; and what to reopen + after a loss. Settings pages and the window stay in each app. - [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook (`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept unread and written back into a list. The workbook model and what follows a read stay in GridCraft. @@ -219,6 +231,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit lookup with fallback (`pt-br` → `pt` → English), plurals, language names, the system locale and a pseudo locale. The catalogs stay a fully optional build input; apps keep `tl!` and their language setting. +- [`craft-i18n-build`](crates/i18n-build/README.md): embeds the optional craft-i18n catalogs + from an app's `build.rs` (`CRAFT_I18N_DIR`, `CRAFT_I18N_REQUIRED`) as the table `craft-i18n` + reads, with each regional locale's parent and the app's own catalogs merged in. No + dependencies. - [`craft-raw`](crates/raw/README.md): camera raw files, the file-format layer, from LightCraft with what PhotoCraft's and FilmCraft's readers added: container parsing and decompression to a neutral raw image (samples, CFA, black and white levels, active area, crop, orientation, colour tags, @@ -291,7 +307,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-markdown`](crates/markdown/README.md): Markdown read and written (a CommonMark subset with GitHub tables and strikethrough), to and from the craft-flow model. - [`craft-math`](crates/math/README.md): equations as one tree (the Office Math object model) with its syntaxes, read and written: OMML, presentation MathML, LaTeX math and the UnicodeMath linear format. - [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV - (`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`) and + (`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`), Bink (`bink`) and MPEG-TS/PS (`mpegts`) demuxers, from FilmCraft, a Sierra VMD (`vmd`) demuxer, and an ISO BMFF box reader. Containers only; codecs are in `craft-audio`, and video codecs will go in a separate crate. - [`craft-lottie`](crates/lottie/README.md): Lottie (Bodymovin) JSON: the document model of @@ -366,8 +382,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit with a password. Salvages damaged files. Bounded and panic-free on hostile input. What an item means stays in each app. -- [`craft-quit`](crates/quit/src/lib.rs): native macOS quit, egui close handling and an optional - app menu. Unsaved-document decisions and save prompts stay in each app. +- [`craft-quit`](crates/quit/README.md): native macOS quit, a window close held for unsaved + documents, the Quit menu item id and the unsaved-changes question one document at a time + (`CloseGuard`). The prompt and the saving stay in each app. - [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages (`\uN`, `\'hh`, single-byte and East Asian multibyte pages), escaping and dates, and a reader and writer for a small neutral model (paragraphs, character formatting, outline levels, tables). @@ -403,8 +420,12 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test whose body runs past a limit, or whose condition does not hold in time; a variable the caller names replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged - copies of a valid input, and fails the test with the case that panicked or did not finish. Not - published. + copies of a valid input, and fails the test with the case that panicked or did not finish. Its `rng` + module holds two seeded generators for repeatable test input. Its `skip` module prints a `SKIPPED:` + line when a test lacks a program, a corpus or the craft-fonts faces, or fails the test when the + variable the caller names is `1`. Any other value of that variable except empty fails the test as a + configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder against a + pinned SHA-256 list. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and diff --git a/crates/ai/Cargo.toml b/crates/ai/Cargo.toml index cca808c9c9..95fc39442f 100644 --- a/crates/ai/Cargo.toml +++ b/crates/ai/Cargo.toml @@ -19,10 +19,10 @@ dirs = "7" sysinfo = "0.39" ureq = { version = "3", features = ["json"] } sha2 = "0.11" -candle-core = { version = "0.9", optional = true } -candle-nn = { version = "0.9", optional = true } -candle-transformers = { version = "0.9", optional = true } -tokenizers = { version = "0.22", optional = true, default-features = false, features = ["onig"] } +candle-core = { version = "0.11.1", optional = true } +candle-nn = { version = "0.11.1", optional = true } +candle-transformers = { version = "0.11.1", optional = true } +tokenizers = { version = "0.23", optional = true, default-features = false, features = ["onig"] } [features] # Local GGUF inference on candle. Heavy dependency tree; apps opt in. diff --git a/crates/atomic/README.md b/crates/atomic/README.md index e43d1c58f7..6ef4429a89 100644 --- a/crates/atomic/README.md +++ b/crates/atomic/README.md @@ -6,7 +6,7 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee ## Core Guarantees: Atomicity vs. Durability -1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; sweeping orphaned staging files is delegated to consuming application recovery routines. The destination file itself is never corrupted. +1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; the application removes orphaned staging files by calling `sweep_temp_files` for the folder (see "Removing Orphaned Staging Files" below). The destination file itself is never corrupted. 2. **Durability & Ordering Boundaries**: - **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback). - **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced. @@ -63,6 +63,27 @@ let path = Path::new("export.png"); write_new(path, b"png bytes...").expect("exclusive write"); ``` +### Removing Orphaned Staging Files + +```rust +use std::path::Path; +use std::time::Duration; +use craft_atomic::sweep_temp_files; + +// Removes staging files in scenes/ that were last modified an hour or more ago. +// Returns how many were removed. +let removed = sweep_temp_files(Path::new("scenes"), Duration::from_secs(3600)).unwrap_or(0); +``` + +`sweep_temp_files` removes only regular files whose names have the staging form, never follows +a symbolic link, and does not search subfolders. A save updates its staging file's modification +time only while it writes bytes, not while it flushes or renames, and removing the staging file +makes that save fail. Choose a minimum age longer than the longest time any save into the folder, +by any process including the calling one, may go without writing, counting the final flush and +rename. On Windows, a write may not update the modification time until the staging file's handle +closes, so choose a minimum age longer than the longest whole save, from the staging file's +creation through the rename. Entries that cannot be removed are left in place. + ### Document Permissions and Private Data The free functions and `WriteOptions::default()` use `NewFilePermissions::PlatformDefault`. diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 5aa3c75cd4..104f859368 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -14,9 +14,9 @@ //! file retains its previous bytes, or it is replaced completely with the new contents. If an error occurs //! during staging or rename, the target remains unmodified and the staging file is removed in user space. //! An abnormal process termination (e.g. `SIGKILL`, crash, power loss) bypasses user-space cleanup and -//! leaves the temporary staging file on disk. Sweeping orphaned staging files is the responsibility of the -//! consuming application; the library does not perform background sweeping. The destination file itself is -//! never corrupted. +//! leaves the temporary staging file on disk. The library does not sweep in the background; the consuming +//! application calls [`sweep_temp_files`] for a folder, for example at startup, to remove orphaned staging +//! files. The destination file itself is never corrupted. //! - **Durability & Ordering Boundaries**: //! Data persistence across power failures involves two sync points: //! 1. **Content Flush (`sync_file`)**: The staging file's payload is forced to non-volatile storage @@ -818,6 +818,57 @@ pub fn temp_name(file: &str) -> String { format!(".{stem}.{pid}-{n}.craft_tmp") } +/// Removes staging files that interrupted writes left in `dir`, and returns how many it removed. +/// +/// A file is removed when its name has the form [`temp_name`] gives, it is a regular file (a +/// symbolic link is not followed), and it was last modified at least `min_age` ago. The process +/// id in the name is not used to decide, since the system reuses process ids. A save updates its +/// staging file's modification time only while it writes bytes, not while it flushes or renames, +/// and removing the staging file makes that save fail. Pass a `min_age` longer than the longest +/// time any save into `dir`, by any process including the calling one, may go without writing, +/// counting the final flush and rename. On Windows, a write may not update the modification time +/// until the staging file's handle closes, so pass a `min_age` longer than the longest whole save, +/// from the staging file's creation through the rename. Entries that cannot be read or removed are +/// left in place. Subfolders are not searched. +/// On `wasm32` this returns an `Unsupported` error. +pub fn sweep_temp_files(dir: &Path, min_age: std::time::Duration) -> io::Result { + #[cfg(target_arch = "wasm32")] + { + let _ = (dir, min_age); + Err(io::Error::new(io::ErrorKind::Unsupported, "staging files cannot be swept on this platform")) + } + #[cfg(not(target_arch = "wasm32"))] + { + let now = std::time::SystemTime::now(); + let entries = std::fs::read_dir(dir).map_err(|e| io::Error::new(e.kind(), format!("cannot read {}: {e}", dir.display())))?; + let mut removed = 0; + for entry in entries.flatten() { + if !entry.file_name().to_str().is_some_and(is_temp_name) { + continue; + } + let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue }; + let old = meta.modified().ok().and_then(|m| now.duration_since(m).ok()).is_some_and(|age| age >= min_age); + if meta.is_file() && old && std::fs::remove_file(entry.path()).is_ok() { + removed += 1; + } + } + Ok(removed) + } +} + +/// Whether `name` has the form [`temp_name`] gives (`.{stem}.{pid}-{n}.craft_tmp`), with a stem +/// of at most [`TEMP_STEM_BYTES`] bytes. +#[cfg(not(target_arch = "wasm32"))] +fn is_temp_name(name: &str) -> bool { + // Decimal digits with no leading zero, as `format!` writes an integer; a lone `0` is allowed. + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0')); + let Some((stem, tail)) = name.strip_prefix('.').and_then(|rest| rest.strip_suffix(".craft_tmp")).and_then(|rest| rest.rsplit_once('.')) else { + return false; + }; + let Some((pid, n)) = tail.split_once('-') else { return false }; + stem.len() <= TEMP_STEM_BYTES && digits(pid) && digits(n) && pid.parse::().is_ok() && n.parse::().is_ok() +} + /// The end of an error message: whether an original file was left as it was. fn unchanged(existed: bool) -> &'static str { if existed { "; the original file was not changed" } else { "" } diff --git a/crates/atomic/src/tests.rs b/crates/atomic/src/tests.rs index 78cc37ae16..132fd5a0a6 100644 --- a/crates/atomic/src/tests.rs +++ b/crates/atomic/src/tests.rs @@ -582,3 +582,79 @@ fn wasm_atomic_write_returns_unsupported() { let err = atomic_write(Path::new("dummy.craft"), b"data").unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::Unsupported); } + +#[cfg(target_arch = "wasm32")] +#[test] +fn wasm_sweep_temp_files_returns_unsupported() { + let err = sweep_temp_files(Path::new("scenes"), std::time::Duration::ZERO).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::Unsupported); +} + +/// Writes the file `name` in `dir` and dates its modification time `age` in the past. +#[cfg(not(target_arch = "wasm32"))] +fn leftover(dir: &Path, name: &str, age: std::time::Duration) -> io::Result { + let p = dir.join(name); + std::fs::write(&p, b"interrupted save")?; + File::options().write(true).open(&p)?.set_modified(std::time::SystemTime::now() - age)?; + Ok(p) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn sweep_removes_only_old_staging_files() -> io::Result<()> { + let d = TempDir::new("sweep_old"); + let other = std::process::id().wrapping_add(1); + let hour = std::time::Duration::from_secs(3600); + let orphan = leftover(&d.0, &format!(".scene.json.{other}-0.craft_tmp"), 2 * hour)?; + // A process id the system reused for this process does not protect an old orphan. + let same_pid = leftover(&d.0, &temp_name("scene.json"), 2 * hour)?; + let recent = leftover(&d.0, &format!(".scene.json.{other}-1.craft_tmp"), std::time::Duration::ZERO)?; + let document = leftover(&d.0, "scene.json", 2 * hour)?; + + assert_eq!(sweep_temp_files(&d.0, hour)?, 2); + assert!(!orphan.exists() && !same_pid.exists()); + assert!(recent.exists() && document.exists()); + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn sweep_keeps_files_it_did_not_name_and_folders() -> io::Result<()> { + let d = TempDir::new("sweep_lookalike"); + let other = std::process::id().wrapping_add(1); + let old = std::time::Duration::from_secs(7200); + let orphan = leftover(&d.0, &format!(".a.b.{other}-7.craft_tmp"), old)?; + let kept = [ + leftover(&d.0, "notes.craft_tmp", old)?, + leftover(&d.0, &format!("scene.json.{other}-7.craft_tmp"), old)?, + leftover(&d.0, ".scene.json.12-x.craft_tmp", old)?, + leftover(&d.0, ".scene.json.-3.craft_tmp", old)?, + leftover(&d.0, ".12-3.craft_tmp", old)?, + leftover(&d.0, &format!(".scene.json.{other}-7.craft_tmp.bak"), old)?, + leftover(&d.0, ".scene.json.99999999999-7.craft_tmp", old)?, + // temp_name writes the process id and the counter without leading zeros. + leftover(&d.0, ".scene.json.012-0.craft_tmp", old)?, + leftover(&d.0, ".scene.json.12-03.craft_tmp", old)?, + // temp_name keeps at most TEMP_STEM_BYTES bytes of the destination's name. + leftover(&d.0, &format!(".{}.{other}-7.craft_tmp", "s".repeat(TEMP_STEM_BYTES + 1)), old)?, + ]; + // The longest stem temp_name writes, in ASCII and in two-byte characters. + let longest = leftover(&d.0, &temp_name(&"s".repeat(200)), old)?; + let longest_wide = leftover(&d.0, &temp_name(&"é".repeat(100)), old)?; + let folder = d.0.join(format!(".scene.json.{other}-8.craft_tmp")); + std::fs::create_dir(&folder)?; + + assert_eq!(sweep_temp_files(&d.0, std::time::Duration::ZERO)?, 3); + assert!(!orphan.exists() && !longest.exists() && !longest_wide.exists()); + assert!(kept.iter().all(|p| p.exists()), "a file without the staging name was removed"); + assert!(folder.is_dir()); + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn sweep_of_a_missing_folder_is_an_error() { + let d = TempDir::new("sweep_missing"); + let err = sweep_temp_files(&d.0.join("absent"), std::time::Duration::ZERO).err().map(|e| e.kind()); + assert_eq!(err, Some(io::ErrorKind::NotFound)); +} diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index fce5926b91..5aa1811309 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -12,7 +12,14 @@ and contains no `unsafe` code. (compressor, expander and gate, limiter, maximizer, multiband and tube-modeled compressors), delays and reverbs (including convolution and surround), modulation, restoration (denoise, dehum, click remover, de-esser, de-reverb, speech enhancement), channel tools, distortion, - dither, a signal generator and a loudness meter. + dither, a signal generator, a loudness meter, a pitch shifter for a live voice with 10 ms of + latency, a formant shifter for a live voice with 10.7 ms of latency, and noise suppression for + a live voice with 5.3 ms of latency that follows the noise floor without first learning it. + These latencies are at 48 kHz (the STFT sizes depend on the sample rate; `latency()` reports + them in samples). The pitch shifter's Keep Formants switch adds the formant shifter's latency, + and `latency()` reports it while the switch is on. A ring modulator for robotic and metallic + voices (ring, frequency modulation, and positive or negative comb resonators, with the + frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency. - `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated loudness, loudness range (EBU Tech 3342), sample peak and true peak. - `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order @@ -27,6 +34,14 @@ and contains no `unsafe` code. - `biquad` and `design`: biquad filters with their magnitude response, and IIR filter design from Butterworth, Bessel, Chebyshev and elliptic prototypes. +`noise_suppression` estimates the noise floor from minimum spectral power over 1.5 s. The first +noise estimate after a reset starts from the median bin's power. Each bin's value is clamped +between 30 dB below its own estimate and its own estimate. Windows that overlap a run of at +least one hop of zeros (64 samples at 48 kHz) do not enter the noise estimate. The gain floor +moves from 0 dB toward the attenuation set by `reduction` during the first search window +of sound. Continuous voiced or tonal audio present from startup can enter the noise estimate +and be attenuated afterward. + ## Conventions Audio is planar `f32`: one slice per channel, all the same length. `AudioEffect::process`, @@ -76,6 +91,10 @@ The crate combines two crates from the ArtCraft apps, with changes: `648ed9db9a0e98cc55643babffac381521a556c8`: the tail length, offline mode, events, saved state and editor parts of the trait, the maximizer, dither, panning, the signal generator and the offline resampler. +- [storytold/soundcraft](https://github.com/storytold/soundcraft) `crates/dsp` at + `915481be1b49d7e0502e07b059d0c0198c61911a`: the two crossfaded read taps of the voice pitch + shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`), and the + ring modulator (`src/plugins/modulation.rs`). `NOTICE` keeps the copyright notices of both projects. diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 679b7c5f9a..e8acfdb18e 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -1,6 +1,7 @@ //! Audio effects and their registry. pub(crate) mod channel; +pub(crate) mod character; pub(crate) mod declick; pub(crate) mod dither; pub(crate) mod dynamics; @@ -15,10 +16,13 @@ pub(crate) mod restoration; pub(crate) mod reverbs; pub(crate) mod special; mod stft; +pub(crate) mod suppress; pub(crate) mod time; pub(crate) mod util; +pub(crate) mod voice; pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing}; +pub use character::RingMod; pub(crate) use declick::ClickRemover; pub use dither::Dither; pub use dynamics::{Compressor, Gate, Limiter, Maximizer}; @@ -34,7 +38,9 @@ pub(crate) use restoration::{DeHum, DeNoise}; pub(crate) use reverbs::{ConvolutionReverb, SurroundReverb}; pub use special::LoudnessMeterFx; pub(crate) use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, Mastering, Mute, StereoExpander, VocalEnhancer}; +pub use suppress::NoiseSuppression; pub(crate) use time::{Delay, Reverb}; +pub use voice::{VoiceFormant, VoicePitch}; use crate::{AudioEffect, ParamSpec, sane_channels, sane_sample_rate}; @@ -123,7 +129,10 @@ static REGISTRY: &[EffectInfo] = &[ }, entry!("dehum", "DeHum", Restoration, DeHum), entry!("denoise", "DeNoise", Restoration, DeNoise), + entry!("noise_suppression", "Noise Suppression", Restoration, NoiseSuppression), entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter), + entry!("voice_pitch", "Voice Pitch", Pitch, VoicePitch), + entry!("voice_formant", "Voice Formant", Pitch, VoiceFormant), entry!("deesser", "DeEsser", Restoration, DeEsser), entry!("dereverb", "DeReverb", Restoration, DeReverb), entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance), @@ -141,6 +150,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("chorus_flanger", "Chorus/Flanger", Modulation, ChorusFlanger), entry!("flanger", "Flanger", Modulation, Flanger), entry!("phaser", "Phaser", Modulation, Phaser), + entry!("ring_mod", "Ring Modulator", Modulation, RingMod), entry!("analog_delay", "Analog Delay", Time, AnalogDelay), entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay), entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb), diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index 0b6f05a802..fc83ffbeec 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -132,9 +132,11 @@ fn every_effect_is_deterministic_and_latency_is_constant() { f }; let lat0 = (e.create)(SR, 2).latency(); + // Keep Formants adds voice_pitch's formant stage; no other parameter changes a latency. + let want = if e.id == "voice_pitch" { lat0 + voice::VoiceFormant::new(SR, 2).latency() } else { lat0 }; let mut a = mk(); let mut b = mk(); - assert_eq!(a.latency(), lat0, "{}: latency depends on parameters", e.id); + assert_eq!(a.latency(), want, "{}: latency depends on parameters", e.id); let ya = run(a.as_mut(), &l, &r); let yb = run(b.as_mut(), &l, &r); assert!(ya.0 == yb.0 && ya.1 == yb.1, "{}: not deterministic", e.id); @@ -147,7 +149,14 @@ fn latency_is_where_the_impulse_lands() { // settings (FFT filter / convolution / existing STFT effects). The click remover repairs a // lone impulse in silence as a click, so its latency is checked on noise by // `neutral_settings_are_delayed_identity`. - for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)])] { + for (id, p) in [ + ("fft_filter", vec![]), + ("convolution_reverb", vec![("mix", 0.0)]), + ("voice_pitch", vec![]), + ("voice_pitch", vec![("formant_follow", 1.0)]), + ("voice_formant", vec![]), + ("noise_suppression", vec![("reduction", 0.0)]), + ] { let mut e = fx(id, &p); let lat = e.latency(); assert!(lat > 0, "{id}"); @@ -906,6 +915,8 @@ fn delays_and_reverbs_report_their_tails() { ("chorus_flanger", &[("mode", 1.0), ("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]), ("chorus_flanger", &[("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]), ("flanger", &[("final_delay", 20.0), ("feedback", 100.0), ("mix", 100.0)][..]), + ("ring_mod", &[("effect", 2.0), ("frequency", 100.0), ("resonance", 90.0)][..]), + ("ring_mod", &[("effect", 3.0), ("frequency", 60.0), ("resonance", 95.0), ("mod_source", 1.0), ("mod_depth", 100.0)][..]), ] { let mut e = fx(id, params); let tail = e.tail_samples(); @@ -976,6 +987,10 @@ fn direct_constructors_cap_the_channel_count() { channel::Amplify, filters::FullParametricEq, pitch::PitchShifter, + voice::VoicePitch, + voice::VoiceFormant, + suppress::NoiseSuppression, + character::RingMod, ); } diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs new file mode 100644 index 0000000000..5a67d4a354 --- /dev/null +++ b/crates/audio-dsp/src/effects/character.rs @@ -0,0 +1,489 @@ +//! Character effects for a live voice. None of them adds latency. +//! +//! The ring modulator (`ring_mod`) has four effects: +//! +//! - Ring multiplies the input by a sine carrier at the frequency, which moves each partial of a +//! voice to the sum and the difference of its frequency and the carrier's. +//! - Frequency Mod reads the input through a delay that the carrier swings between 2 samples and +//! 2 samples plus 2 ms. +//! - Resonator + and Resonator - feed the output back after one period of the frequency, with a +//! positive or a negative sign, so the input rings at the frequency and its multiples (Resonator +//! +) or at its odd half multiples (Resonator -). The output is scaled by `1 - resonance`, so the +//! peak gain at resonance is unity. +//! +//! An LFO, an envelope follower (5 ms attack, 100 ms release) or a sample-and-hold source moves the +//! frequency by up to two octaves either way at 100 % depth. The envelope follower moves it up +//! only. + +use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail}; +use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing}; +use std::f64::consts::TAU; + +fn blend(dry: f64, wet: f64, mix: f64) -> f64 { + (1.0 - mix) * dry + mix * wet +} + +/// Smoothing time of the frequency, resonance, depth and mix, in ms. +const SM: f32 = 20.0; +const RING_EFFECTS: &[&str] = &["Ring", "Frequency Mod", "Resonator +", "Resonator -"]; +const RING_SOURCES: &[&str] = &["LFO", "Envelope", "Sample & Hold"]; +/// Lowest frequency the control reaches. +const MIN_HZ: f32 = 20.0; +/// Octaves the frequency moves at full modulation depth. +const MOD_OCTAVES: f32 = 2.0; +/// Peak delay swing of Frequency Mod, in ms. +const FM_SWING_MS: f32 = 1.0; +/// Shortest delay of Frequency Mod, in samples (room for the interpolated read). +const FM_BASE: f32 = 2.0; +/// Sample-and-hold seed (the same sequence after every reset). +const SEED: u64 = 0x5EED_1234; +/// Highest frequency the modulation reaches, as a fraction of the sample rate. +const MAX_FRACTION: f32 = 0.45; + +/// Ring modulation, frequency modulation and positive or negative comb resonators, with the +/// frequency moved by an LFO, an envelope follower or a sample-and-hold source. +pub struct RingMod { + pv: ParamValues, + sr: f32, + lines: Vec, + carrier: Lfo, + lfo: Lfo, + rng: Prng, + env: Envelope, + env_attack: f32, + env_release: f32, + held: f32, + hold_left: usize, + /// Effect the lines hold state for. + effect: usize, + freq: Smoothed, + res: Smoothed, + depth: Smoothed, + mix: Smoothed, +} + +impl RingMod { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::choice("effect", "Effect", RING_EFFECTS, 0), + ParamSpec::log("frequency", "Frequency", MIN_HZ, 5000.0, 440.0, Unit::Hertz), + ParamSpec::new("resonance", "Resonance", 0.0, 95.0, 50.0, Unit::Percent), + ParamSpec::choice("mod_source", "Mod Source", RING_SOURCES, 0), + ParamSpec::log("mod_rate", "Mod Rate", 0.05, 20.0, 1.0, Unit::Hertz), + ParamSpec::new("mod_depth", "Mod Depth", 0.0, 100.0, 0.0, Unit::Percent), + ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + // One period of the lowest frequency the modulation reaches, or the widest Frequency Mod + // delay, whichever is longer. + let longest_ms = (1000.0 / (MIN_HZ * (-MOD_OCTAVES).exp2())).max(2.0 * FM_SWING_MS) + 1.0; + let len = delay_line_len(longest_ms, sample_rate, ch); + let sm = |v| Smoothed::with_ms(v, sample_rate, SM); + let mut s = RingMod { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + lines: vec![DelayLine::new(len); ch], + carrier: Lfo::default(), + lfo: Lfo::default(), + rng: Prng::new(SEED), + env: Envelope::default(), + env_attack: coef(5.0, sample_rate), + env_release: coef(100.0, sample_rate), + held: 0.0, + hold_left: 0, + effect: 0, + freq: sm(440.0), + res: sm(0.0), + depth: sm(0.0), + mix: sm(1.0), + }; + s.apply_params(true); + s.effect = s.pv.idx("effect"); + s + } + + fn apply_params(&mut self, snap: bool) { + self.freq.set(self.pv.v("frequency")); + self.res.set(self.pv.v("resonance") / 100.0); + self.depth.set(self.pv.v("mod_depth") / 100.0); + self.mix.set(self.pv.v("mix") / 100.0); + if snap { + for s in [&mut self.freq, &mut self.res, &mut self.depth, &mut self.mix] { + s.snap(); + } + } + } + + /// One period of the lowest frequency the modulation reaches, in ms, from the settings and from + /// the values still ramping toward them. The envelope follower moves the frequency up only, so + /// with it the lowest is the frequency. The frequency is held within the same range as in + /// [`AudioEffect::process`]. + fn longest_period_ms(&self) -> f32 { + let down = if self.pv.idx("mod_source") == 1 { 0.0 } else { self.depth.value().max(self.depth.target()) }; + let lowest = self.freq.value().min(self.freq.target()) * (-MOD_OCTAVES * down).exp2(); + 1000.0 / lowest.clamp(1.0, self.sr * MAX_FRACTION) + } +} + +impl AudioEffect for RingMod { + param_plumbing!("ring_mod"); + /// Ring has no tail. Frequency Mod holds up to its widest delay. The resonators ring until + /// the feedback has fallen by 60 dB at the longest period the modulation reaches, at the higher + /// of the resonance setting and the value still ramping toward it. + fn tail_samples(&self) -> usize { + match self.pv.idx("effect") { + 1 => (FM_BASE + 2.0 * FM_SWING_MS * 0.001 * self.sr).ceil() as usize + 1, + 2 | 3 => echo_tail(self.longest_period_ms(), self.res.value().max(self.res.target()), self.sr), + _ => 0, + } + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(DelayLine::reset); + self.carrier.reset(); + self.lfo.reset(); + self.rng = Prng::new(SEED); + self.env.env = 0.0; + self.held = 0.0; + self.hold_left = 0; + self.effect = self.pv.idx("effect"); + for s in [&mut self.freq, &mut self.res, &mut self.depth, &mut self.mix] { + s.snap(); + } + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + if n == 0 { + return; + } + let nch = channels.len().min(self.lines.len()); + let effect = self.pv.idx("effect"); + if effect != self.effect { + // The lines hold the previous effect's state. + self.lines.iter_mut().for_each(DelayLine::reset); + self.effect = effect; + } + let source = self.pv.idx("mod_source"); + let rate = self.pv.v("mod_rate"); + let hold = ((self.sr / rate.max(0.05)) as usize).max(1); + // A faster rate cuts the value being held short, instead of holding it for the old length. + self.hold_left = self.hold_left.min(hold); + let highest = self.sr * MAX_FRACTION; + let swing = FM_SWING_MS * 0.001 * self.sr; + let sign = if effect == 3 { -1.0 } else { 1.0 }; + for i in 0..n { + let level = channels[..nch].iter().map(|c| c[i]).filter(|x| x.is_finite()).fold(0.0f32, |m, x| m.max(x.abs())); + let env = self.env.tick(self.env_attack, self.env_release, level); + let m = match source { + 1 => env.min(1.0), + 2 => { + if self.hold_left == 0 { + self.held = self.rng.uniform(); + self.hold_left = hold; + } + self.hold_left -= 1; + self.held + } + _ => (TAU * self.lfo.phase(0.0)).sin() as f32, + }; + self.lfo.advance(rate, self.sr); + let f = (self.freq.tick() * (MOD_OCTAVES * self.depth.tick() * m).exp2()).clamp(1.0, highest); + let fb = self.res.tick(); + let mix = self.mix.tick(); + let carrier = (TAU * self.carrier.phase(0.0)).sin() as f32; + self.carrier.advance(f, self.sr); + // The read happens before this sample's push, so one period back is `period - 1`. + let back = self.sr / f - 1.0; + for (ch, line) in self.lines.iter_mut().enumerate() { + // A non-finite sample is taken as silence. A channel the block leaves out is fed + // silence, so it holds none of its earlier audio when it comes back. + let dry = match channels.get(ch).filter(|_| ch < nch) { + Some(c) if c[i].is_finite() => c[i], + _ => 0.0, + }; + let wet = match effect { + 1 => { + line.push(dry); + line.read(FM_BASE + swing * (1.0 + carrier)) + } + 2 | 3 => { + let y = flush32(dry + sign * fb * line.read(back)); + line.push(y); + y * (1.0 - fb) + } + _ => dry * carrier, + }; + if ch < nch { + let (dry, wet) = (dry as f64, wet as f64); + channels[ch][i] = blend(dry, wet, f64::from(mix)) as f32; + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn ring(params: &[(&str, f32)], channels: usize) -> RingMod { + let mut r = RingMod::new(SR, channels); + for (id, v) in params { + assert!(r.set_param(id, *v), "{id}"); + } + r.reset(); + r + } + + /// Ring moves a tone to the sum and the difference of its frequency and the carrier's, each + /// at half the tone's amplitude, and leaves nothing at the tone's own frequency. + #[test] + fn ring_moves_a_tone_to_the_sum_and_difference_frequencies() { + let mut r = ring(&[("frequency", 300.0)], 1); + let mut x = sine(1000.0, 0.5, SR as f64, SR as usize, 0.0); + r.process(&mut [&mut x]); + for (f, want) in [(700.0, 0.25), (1300.0, 0.25), (1000.0, 0.0), (300.0, 0.0)] { + let a = tone_amplitude(&x, f, SR as f64); + assert!((a - want).abs() < 0.005, "{f} Hz: {a}, want {want}"); + } + } + + /// Resonator + repeats an impulse once per period of its frequency, each repeat lower by the + /// resonance, and Resonator - flips the sign of each repeat. + #[test] + fn resonators_repeat_an_impulse_once_per_period() { + for (effect, sign) in [(2.0, 1.0f32), (3.0, -1.0)] { + let mut r = ring(&[("effect", effect), ("frequency", 500.0), ("resonance", 80.0)], 1); + let mut x = vec![0.0f32; 1000]; + x[10] = 1.0; + r.process(&mut [&mut x]); + // 96 samples per period at 500 Hz. + for k in 0..8 { + let i = 10 + 96 * k; + let want = 0.2 * (sign * 0.8).powi(k as i32); + assert!((x[i] - want).abs() < 1e-5, "effect {effect}, repeat {k} at {i}: {}, want {want}", x[i]); + } + let others = x.iter().enumerate().filter(|(i, _)| *i < 10 || (*i - 10) % 96 != 0).fold(0.0f32, |m, (_, v)| m.max(v.abs())); + assert!(others < 1e-5, "effect {effect}: {others} between the repeats"); + } + } + + #[test] + fn an_empty_block_keeps_the_resonator_ring() { + let p = [("effect", 2.0), ("frequency", 500.0), ("resonance", 80.0)]; + let (mut r, mut still) = (ring(&p, 1), ring(&p, 1)); + for f in [&mut r, &mut still] { + let mut x = vec![0.0f32; 50]; + x[10] = 1.0; + f.process(&mut [&mut x]); + } + assert!(r.set_param("effect", 0.0)); + let mut empty: [f32; 0] = []; + r.process(&mut [&mut empty[..]]); + r.process(&mut []); + assert!(r.set_param("effect", 2.0)); + let (mut a, mut b) = (vec![0.0f32; 500], vec![0.0f32; 500]); + r.process(&mut [&mut a]); + still.process(&mut [&mut b]); + assert!(rms(&b) > 1e-3, "the ring has already died out"); + assert_eq!(a, b); + } + + /// Frequency Mod delays the input by 2 samples to 2 samples plus 2 ms, swinging across the + /// whole range at the carrier's rate. + #[test] + fn frequency_mod_swings_the_delay_by_two_ms() { + let mut r = ring(&[("effect", 1.0), ("frequency", 440.0)], 1); + let slope = 1e-4f32; + let mut x: Vec = (0..4800).map(|i| i as f32 * slope).collect(); + r.process(&mut [&mut x]); + let delays: Vec = x.iter().enumerate().skip(200).map(|(i, y)| (i as f32 * slope - y) / slope).collect(); + let (lo, hi) = delays.iter().fold((f32::MAX, f32::MIN), |(lo, hi), d| (lo.min(*d), hi.max(*d))); + assert!((1.99..2.1).contains(&lo), "shortest delay {lo}"); + assert!((97.9..=98.01).contains(&hi), "longest delay {hi}"); + } + + /// With the envelope as the source, a steady input at full level moves the frequency up by + /// the depth: two octaves at 100 %. + #[test] + fn envelope_moves_the_frequency_up_with_the_level() { + let mut r = ring(&[("frequency", 100.0), ("mod_source", 1.0), ("mod_depth", 100.0)], 1); + let n = SR as usize; + let mut x = vec![1.0f32; n]; + r.process(&mut [&mut x]); + let tail = &x[n / 2..]; + assert!(tone_amplitude(tail, 400.0, SR as f64) > 0.99, "400 Hz: {}", tone_amplitude(tail, 400.0, SR as f64)); + assert!(tone_amplitude(tail, 100.0, SR as f64) < 0.01, "100 Hz: {}", tone_amplitude(tail, 100.0, SR as f64)); + } + + /// A resonator's tail covers the longest period the modulation reaches: four times as long at + /// full depth with the LFO or sample and hold, which move the frequency down two octaves, and + /// unchanged with the envelope, which moves it up only. + #[test] + fn resonator_tail_follows_the_lowest_frequency_the_modulation_reaches() { + let tail = |source: f32, depth: f32| { + ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 90.0), ("mod_source", source), ("mod_depth", depth)], 1).tail_samples() as f32 + }; + let still = tail(0.0, 0.0); + for source in [0.0, 2.0] { + let ratio = tail(source, 100.0) / still; + assert!((ratio - 4.0).abs() < 0.01, "source {source}: {ratio}"); + } + assert_eq!(tail(1.0, 100.0), still); + } + + /// While the resonance ramps down to a new setting, the tail still covers the higher value, + /// and it shrinks to the new setting's tail once the ramp has ended. + #[test] + fn resonator_tail_covers_a_resonance_still_ramping_down() { + let mut r = ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 95.0)], 1); + let high = r.tail_samples(); + assert!(r.set_param("resonance", 0.0)); + assert_eq!(r.tail_samples(), high); + let mut x = vec![0.0f32; 4800]; + r.process(&mut [&mut x]); + let low = ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 0.0)], 1).tail_samples(); + assert_eq!(r.tail_samples(), low); + assert!(low * 10 < high, "{low} vs {high}"); + } + + /// At a low sample rate the resonators ring at the highest frequency processing reaches, not + /// at the setting above it, and the tail covers that ring. A setting below that frequency + /// keeps the tail of its own period. + #[test] + fn resonator_tail_covers_a_frequency_held_at_the_rate_limit() { + let sr = 1000.0f32; + let mut r = RingMod::new(sr, 1); + for (id, v) in [("effect", 2.0), ("frequency", 5000.0), ("resonance", 95.0)] { + assert!(r.set_param(id, v), "{id}"); + } + r.reset(); + let tail = r.tail_samples(); + let mut x = vec![0.0f32; tail + 200]; + x[0] = 1.0; + r.process(&mut [&mut x]); + let after = x[tail + 1..].iter().fold(0.0f32, |m, v| m.max(v.abs())); + assert!(after <= 1e-3 * x[0].abs(), "tail {tail}: {after} after it, against {} at the impulse", x[0]); + let mut below = RingMod::new(sr, 1); + for (id, v) in [("effect", 2.0), ("frequency", 400.0), ("resonance", 95.0)] { + assert!(below.set_param(id, v), "{id}"); + } + below.reset(); + assert_eq!(below.tail_samples(), echo_tail(1000.0 / 400.0, 0.95, sr)); + } + + /// Frequency Mod reads between two of the largest samples of opposite sign without + /// overflowing. + #[test] + fn frequency_mod_reads_between_huge_samples_of_opposite_sign() { + let mut r = ring(&[("effect", 1.0), ("frequency", 500.0)], 1); + let mut x = vec![0.0f32; 200]; + x[6] = -f32::MAX; + x[7] = f32::MAX; + r.process(&mut [&mut x]); + assert!(x.iter().all(|v| v.is_finite()), "{:?}", x.iter().position(|v| !v.is_finite())); + } + + #[test] + fn frequency_mod_full_mix_keeps_a_small_delayed_sample() { + let mut r = ring(&[("effect", 1.0), ("frequency", 500.0), ("mix", 100.0)], 1); + let mut x = vec![0.5f32; 600]; + x[500] = f32::MAX; + r.process(&mut [&mut x]); + assert_eq!(x[500], 0.5, "the delayed sample was lost at full mix"); + } + + /// Mixing a dry and a wet sample of opposite sign at the largest level stays finite: a mix of + /// 0 gives the input, and every mix gives the result at a level of 1 scaled up. + #[test] + fn mixing_huge_samples_of_opposite_sign_stays_finite() { + for mix in [0.0f32, 50.0, 100.0] { + let run = |level: f32| { + let mut r = ring(&[("frequency", 5000.0), ("mix", mix)], 1); + let mut x = vec![level; 480]; + r.process(&mut [&mut x]); + x + }; + let (huge, unit) = (run(f32::MAX), run(1.0)); + assert!(huge.iter().all(|v| v.is_finite()), "mix {mix}"); + for (i, (h, u)) in huge.iter().zip(&unit).enumerate() { + let want = *u as f64 * f32::MAX as f64; + assert!((*h as f64 - want).abs() <= 1e-5 * f32::MAX as f64, "mix {mix}, sample {i}: {h} against {want}"); + } + if mix == 0.0 { + assert!(huge.iter().all(|v| *v == f32::MAX)); + } + } + } + + /// Raising the sample-and-hold rate takes effect within one new hold, instead of after the + /// value already held at the slow rate runs out. + #[test] + fn sample_and_hold_follows_a_faster_rate_at_once() { + let mut r = ring(&[("mod_source", 2.0), ("mod_rate", 0.05), ("mod_depth", 100.0)], 1); + let mut x = vec![0.0f32; 480]; + r.process(&mut [&mut x]); + let first = r.held; + assert!(r.set_param("mod_rate", 20.0)); + // A hold lasts 2,400 samples at 20 Hz and 960,000 at 0.05 Hz. + let mut x = vec![0.0f32; 4800]; + r.process(&mut [&mut x]); + assert_ne!(r.held, first, "the slow hold kept its value"); + } + + /// At a mix of 0 every effect passes the input through unchanged. + #[test] + fn mix_zero_passes_the_input_through() { + for effect in 0..4 { + let mut r = ring(&[("effect", effect as f32), ("mix", 0.0), ("mod_depth", 50.0)], 2); + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let (mut l, mut rr) = (x.clone(), x.clone()); + r.process(&mut [&mut l, &mut rr]); + assert!(l == x && rr == x, "effect {effect}"); + } + } + + /// A block that leaves a channel out feeds it silence, so a resonator's ring on that channel + /// keeps decaying instead of waiting for the channel to come back. + #[test] + fn channels_a_block_leaves_out_are_fed_silence() { + let p = [("effect", 2.0), ("frequency", 100.0), ("resonance", 90.0)]; + let (mut left_out, mut silent) = (ring(&p, 2), ring(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + for r in [&mut left_out, &mut silent] { + let (mut l, mut rr) = (x.clone(), x.clone()); + r.process(&mut [&mut l, &mut rr]); + } + for _ in 0..10 { + let mut l = vec![0.0f32; 480]; + left_out.process(&mut [&mut l]); + let (mut l, mut rr) = (vec![0.0f32; 480], vec![0.0f32; 480]); + silent.process(&mut [&mut l, &mut rr]); + } + let (mut la, mut ra) = (vec![0.0f32; 4800], vec![0.0f32; 4800]); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (vec![0.0f32; 4800], vec![0.0f32; 4800]); + silent.process(&mut [&mut lb, &mut rb]); + assert!(rms(&rb) > 1e-3, "the ring has already died out: {}", rms(&rb)); + let worst = ra.iter().zip(&rb).fold(0.0f32, |m, (a, b)| m.max((a - b).abs())); + assert!(worst < 1e-6, "the left-out channel differs by {worst}"); + assert_eq!(la, lb); + } + + /// A non-finite input sample comes out as silence and leaves no NaN in the resonator. + #[test] + fn a_non_finite_sample_leaves_the_state_finite() { + for effect in 0..4 { + let mut r = ring(&[("effect", effect as f32), ("resonance", 95.0)], 1); + let mut x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + x[100] = f32::NAN; + x[200] = f32::INFINITY; + r.process(&mut [&mut x]); + assert!(x.iter().all(|v| v.is_finite()), "effect {effect}"); + } + } +} diff --git a/crates/audio-dsp/src/effects/stft.rs b/crates/audio-dsp/src/effects/stft.rs index c4b9ed7070..14d1003dbb 100644 --- a/crates/audio-dsp/src/effects/stft.rs +++ b/crates/audio-dsp/src/effects/stft.rs @@ -402,7 +402,7 @@ mod tests { #[test] fn paired_effects_match_mono_on_transients() { use crate::AudioEffect; - use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter}; + use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter}; const SR: f32 = 48_000.0; let len = 48_000; let material = |f: f64, amp: f32, phase: f64, click_every: usize, click_at: usize, noise: f32, seed: u64| -> Vec { @@ -427,6 +427,7 @@ mod tests { "DeReverb" => Box::new(DeReverb::new(SR, ch)), "FftFilter" => Box::new(FftFilter::new(SR, ch)), "DeNoise" => Box::new(DeNoise::new(SR, ch)), + "NoiseSuppression" => Box::new(NoiseSuppression::new(SR, ch)), _ => Box::new(PitchShifter::new(SR, ch)), }; if name == "PitchShifter" { @@ -445,7 +446,7 @@ mod tests { y }; let mut failures = Vec::new(); - for name in ["PitchShifter", "DeNoise", "DeReverb", "FftFilter"] { + for name in ["PitchShifter", "DeNoise", "NoiseSuppression", "DeReverb", "FftFilter"] { for (label, src) in [("identical", &identical), ("different", &different)] { let joint = run(name, src); for (ch, chan) in src.iter().enumerate() { @@ -502,17 +503,18 @@ mod tests { #[test] fn non_finite_sample_stays_in_its_channel() { use crate::AudioEffect; - use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter}; + use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter}; const SR: f32 = 48_000.0; let len = 24_000; let mut rng = Rng::new(5); let clean_a: Vec = crate::testutil::sine(440.0, 0.4, SR as f64, len, 0.0).iter().map(|v| v + 0.05 * rng.uniform()).collect(); let clean_b: Vec = crate::testutil::sine(1250.0, 0.4, SR as f64, len, 0.3).iter().map(|v| v + 0.05 * rng.uniform()).collect(); type Make = fn() -> Box; - let make: [(&str, Make, usize); 4] = [ + let make: [(&str, Make, usize); 5] = [ ("DeReverb", || Box::new(DeReverb::new(SR, 2)), 1), ("FftFilter", || Box::new(FftFilter::new(SR, 2)), 1), ("DeNoise", || Box::new(DeNoise::new(SR, 2)), 1), + ("NoiseSuppression", || Box::new(NoiseSuppression::new(SR, 2)), 1), ("PitchShifter", || Box::new(PitchShifter::new(SR, 2)), 1), ]; let mono = |name: &str, src: &[f32]| -> Vec { @@ -520,6 +522,7 @@ mod tests { "DeReverb" => Box::new(DeReverb::new(SR, 1)), "FftFilter" => Box::new(FftFilter::new(SR, 1)), "DeNoise" => Box::new(DeNoise::new(SR, 1)), + "NoiseSuppression" => Box::new(NoiseSuppression::new(SR, 1)), _ => Box::new(PitchShifter::new(SR, 1)), }; if name == "PitchShifter" { diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs new file mode 100644 index 0000000000..acebd93e37 --- /dev/null +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -0,0 +1,984 @@ +//! Noise suppression for a live voice (`noise_suppression`), with 256 samples (5.3 ms) of latency +//! at 48 kHz. +//! +//! The effect runs a short STFT: 256 points at up to 50 kHz (twice that for each doubling of the +//! rate above it), a hop of a quarter of the size, and square-root Hann windows. Each bin's noise +//! power is the smallest value of its smoothed power over the last 1.5 s (minimum statistics, +//! R. Martin, 2001), so the estimate follows a noise floor that changes and needs no "learn noise" +//! step. Each bin's gain is a Wiener gain on the decision-directed a priori SNR (Ephraim and Malah, +//! 1984), held at or above the floor that `reduction` sets, and averaged with its neighbors. At a +//! reduction of 0 every gain is 1 and the effect is a plain delay. +//! +//! A frame enters the noise estimate only after the next four frames have arrived. A frame of +//! digital silence (a mute or a gate) drops the frames still waiting, and the four frames after +//! it do not enter either, so no frame that shares a sample with the silence lowers the estimate +//! and lets the noise pass when the sound resumes, wherever between two hops the silence ends. +//! A mute too short to fill a frame keeps every frame that holds a sample of it out too, down to +//! a run of zeros one hop long (64 samples at 48 kHz); a shorter run of zeros counts as sound. +//! Nor does a frame more than 15 dB below the estimate, until such frames have lasted a whole +//! search window without digital silence between them (the floor has really fallen). +//! The noise power the gains are computed from falls at once and rises by at most 10 dB a +//! second, so a vowel or a note held for longer than the search window keeps its level for a few +//! seconds more, and a noise floor that rises by 12 dB is suppressed again within 3 s. +//! After a reset the gain floor moves from 0 dB toward the attenuation set by `reduction` over +//! the first search window of sound. The first noise estimate after a reset starts from the +//! median bin's power. Each bin's value is clamped between 30 dB below its own estimate and its +//! own estimate. The noise power then rises by at most 10 dB a second. A vowel held from the +//! first sample keeps its level for a few seconds, like one held after a stretch of noise, while +//! steady noise of an even spectrum is suppressed as soon as the floor allows; noise whose +//! spectrum is uneven takes up to 3 s more in the bins well above the median. Continuous voiced +//! or tonal audio present from startup can eventually enter the noise estimate and be attenuated. + +use super::stft::{Pairing, Plan, Spectral, StftChannel, stream}; +use crate::{AudioEffect, MAX_CHANNELS, ParamSpec, ParamValues, Unit, block_len, db_to_gain, flush32, param_plumbing}; + +/// Length of the minimum-statistics search, and the number of sub-windows it rotates through. +const SEARCH_S: f32 = 1.5; +const SUBWINDOWS: usize = 8; +/// Time constant of the smoothing of each bin's power. +const POWER_MS: f32 = 10.0; +/// Time constant of the decision-directed a priori SNR. +const PRIORI_MS: f32 = 80.0; +/// Ratio of the mean noise power to the minimum of its smoothed power with these windows (see +/// `the_noise_estimate_follows_white_noise`). +const BIAS: f32 = 3.25; +/// Smallest noise power a bin is divided by, so digital silence keeps its gain at the floor. +const MIN_NOISE: f32 = 1.0e-30; +/// A frame whose power is below the estimated noise power by this ratio (15 dB) is quiet. +const QUIET: f32 = 1.0 / 32.0; +/// Frames that share a sample with any one frame: the hop is a quarter of the STFT size. +const OVERLAP: usize = 4; +/// Lowest the first noise power of a bin starts against the bin's own estimate (30 dB). +const SEED_SPAN: f32 = 1.0e-3; +/// Fastest rise of the noise power a bin's gain is computed from, in dB per second. +const RISE_DB_S: f32 = 10.0; + +/// STFT size: 256 at up to 50 kHz (5.3 ms at 48 kHz), doubled for each doubling of the rate above +/// it, up to 8192. +fn suppress_size(sample_rate: f32) -> usize { + let (mut n, mut top) = (256, 50_000.0); + while sample_rate > top && n < 8192 { + n *= 2; + top *= 2.0; + } + n +} + +/// Smoothing and floor shared by every frame, from the parameters and the frame rate. +#[derive(Clone, Copy, Debug)] +struct Coefs { + /// Lowest gain a bin gets. + floor: f32, + /// Weight of the previous smoothed power. + smooth: f32, + /// Weight of the previous frame's clean power in the a priori SNR. + priori: f32, + /// Frames in one minimum-statistics sub-window. + sub_frames: usize, + /// Frames in the whole search window. + window: usize, + /// Largest ratio of one frame's noise power to the previous frame's (`RISE_DB_S`). + rise: f32, +} + +/// One channel's noise estimate and gains. Every buffer is sized at creation. +#[derive(Clone, Debug)] +struct Bins { + /// Smoothed power of each bin. + power: Vec, + /// Smallest smoothed power in the current sub-window. + min: Vec, + /// Smallest smoothed power of each of the last `SUBWINDOWS` sub-windows. + ring: Vec, + slot: usize, + frames: usize, + /// Power the previous frame kept (gain² × power). + clean: Vec, + gains: Vec, + /// Smallest smoothed power of the search window for each bin, for the frame being processed. + est: Vec, + /// Noise power of each bin that the gains are computed from: `est` times the bias, rising by + /// at most `RISE_DB_S`. + noise: Vec, + /// Power of each bin of the frames waiting to enter the estimate, `OVERLAP` frames of + /// `bins` values, the oldest at `head`. + queue: Vec, + /// Total power of each waiting frame, and whether it may enter the estimate. + queue_total: [f32; OVERLAP], + queue_ok: [bool; OVERLAP], + /// Whether a mute began between a waiting frame and the one before it. + queue_cut: [bool; OVERLAP], + /// Whether a mute began since the last frame was queued. + cut_pending: bool, + head: usize, + queued: usize, + /// Whether a frame has entered the estimate since the last reset. + started: bool, + /// Frames that entered the estimate since the last reset, up to a search window. + heard: usize, + /// Frames with sound since the last frame of digital silence, up to `OVERLAP + 1`. It starts + /// at 1: the zeros the STFT starts with end on a hop boundary, so `OVERLAP` frames clear them. + since_zero: usize, + /// Quiet frames in a row since the last frame of digital silence, up to a search window. + quiet_run: usize, + /// Whether `noise` has been set from a first estimate since the last reset. + seeded: bool, + /// Room to find the median bin of the first estimate. + scratch: Vec, + /// Zero samples in a row up to the last sample, up to a hop. + zero_run: usize, + /// Samples since the last sample of a mute (a run of at least a hop of zeros), or `usize::MAX` + /// when there has been none since the last reset. + since_mute: usize, + /// Samples since the last frame. + since_frame: usize, +} + +impl Bins { + fn new(bins: usize) -> Self { + Bins { + power: vec![0.0; bins], + min: vec![f32::INFINITY; bins], + ring: vec![f32::INFINITY; bins * SUBWINDOWS], + slot: 0, + frames: 0, + clean: vec![0.0; bins], + gains: vec![1.0; bins], + est: vec![f32::INFINITY; bins], + noise: vec![f32::INFINITY; bins], + queue: vec![0.0; bins * OVERLAP], + queue_total: [0.0; OVERLAP], + queue_ok: [false; OVERLAP], + queue_cut: [false; OVERLAP], + cut_pending: false, + head: 0, + queued: 0, + started: false, + heard: 0, + since_zero: 1, + quiet_run: 0, + seeded: false, + scratch: vec![0.0; bins], + zero_run: 0, + since_mute: usize::MAX, + since_frame: 0, + } + } + + fn reset(&mut self) { + self.power.fill(0.0); + self.min.fill(f32::INFINITY); + self.ring.fill(f32::INFINITY); + self.clean.fill(0.0); + self.gains.fill(1.0); + self.est.fill(f32::INFINITY); + self.noise.fill(f32::INFINITY); + self.slot = 0; + self.frames = 0; + self.head = 0; + self.queued = 0; + self.cut_pending = false; + self.started = false; + self.heard = 0; + self.since_zero = 1; + self.quiet_run = 0; + self.seeded = false; + self.zero_run = 0; + self.since_mute = usize::MAX; + self.since_frame = 0; + } + + /// Takes one input sample before the STFT does, to find mutes too short to give a frame of + /// digital silence. Once `hop` zeros run in a row, the frame still waiting that holds the first + /// of them leaves the queue, and so does every later frame that holds a sample of the run. + fn sample(&mut self, x: f32, hop: usize) { + self.since_frame += 1; + self.zero_run = if x == 0.0 { (self.zero_run + 1).min(hop) } else { 0 }; + if self.zero_run < hop { + self.since_mute = self.since_mute.saturating_add(1); + return; + } + if self.since_mute != 0 { + // The run has just reached a hop. It started `hop - 1` samples ago, so of the frames + // waiting only the newest can hold it: when it ended less than a hop ago. + if self.queued > 0 && self.since_frame < hop { + self.queue_ok[(self.head + self.queued - 1) % OVERLAP] = false; + } + self.cut_pending = true; + } + self.since_mute = 0; + } + + /// Noise power of bin `k` for the frame last processed: the smallest smoothed power of the + /// search window times the bias, rising by at most `RISE_DB_S`. + fn noise(&self, k: usize) -> f32 { + self.noise[k].max(MIN_NOISE) + } + + /// Moves the oldest waiting frame into the noise estimate, unless it shares a sample with + /// digital silence, or it is quiet and quiet frames have not yet lasted a search window. + fn commit(&mut self, c: &Coefs) { + let bins = self.power.len(); + let at = self.head; + self.head = (at + 1) % OVERLAP; + self.queued -= 1; + if self.queue_cut[at] { + self.quiet_run = 0; + } + if !self.queue_ok[at] { + return; + } + let noise_total = self.est.iter().map(|e| e * BIAS).sum::(); + let quiet = noise_total.is_finite() && self.queue_total[at] < noise_total * QUIET; + self.quiet_run = if quiet { (self.quiet_run + 1).min(c.window) } else { 0 }; + if quiet && self.quiet_run < c.window { + return; + } + let a = if self.started { c.smooth } else { 0.0 }; + for k in 0..bins { + let p = self.queue[at * bins + k]; + self.power[k] = flush32(a * self.power[k] + (1.0 - a) * p); + self.min[k] = self.min[k].min(self.power[k]); + self.est[k] = self.est[k].min(self.power[k]); + } + self.frames += 1; + if self.frames == c.sub_frames { + for k in 0..bins { + self.ring[self.slot * bins + k] = self.min[k]; + self.min[k] = f32::INFINITY; + } + self.slot = (self.slot + 1) % SUBWINDOWS; + self.frames = 0; + } + self.started = true; + self.heard = (self.heard + 1).min(c.window); + } + + /// Takes one frame's half spectrum, updates the noise estimate and the gains, and writes the + /// gains averaged with their neighbors to `out`. A frame with a non-finite bin leaves the + /// state as it is and repeats the last gains. + fn frame(&mut self, re: &[f32], im: &[f32], c: &Coefs, out: &mut [f32]) { + let bins = self.power.len(); + self.since_frame = 0; + let finite = re.iter().zip(im).fold(true, |ok, (a, b)| ok & (a * a + b * b).is_finite()); + if finite { + for k in 0..bins { + self.est[k] = (0..SUBWINDOWS).fold(self.min[k], |m, u| m.min(self.ring[u * bins + k])); + } + let total = (0..bins).map(|k| re[k] * re[k] + im[k] * im[k]).sum::(); + if total == 0.0 { + // Digital silence: the frames still waiting share a sample with it, and so do the + // next `OVERLAP - 1` frames, or the next `OVERLAP` when the silence ends between + // two hops. A quiet run ends here too. + self.queued = 0; + self.cut_pending = false; + self.since_zero = 0; + self.quiet_run = 0; + } else { + self.since_zero = (self.since_zero + 1).min(OVERLAP + 1); + if self.queued == OVERLAP { + self.commit(c); + } + let at = (self.head + self.queued) % OVERLAP; + for k in 0..bins { + self.queue[at * bins + k] = re[k] * re[k] + im[k] * im[k]; + } + self.queue_total[at] = total; + self.queue_cut[at] = std::mem::take(&mut self.cut_pending); + // A frame holds the last STFT size of samples, `2 * (bins - 1)`. + self.queue_ok[at] = self.since_zero > OVERLAP && self.since_mute >= 2 * (bins - 1); + self.queued += 1; + } + if self.started && !self.seeded { + // The first estimate: a bin well above the median bin, such as a harmonic of a + // vowel held from the start, starts from the median and rises from there. + self.seeded = true; + self.scratch.copy_from_slice(&self.est); + let median = *self.scratch.select_nth_unstable_by(bins / 2, f32::total_cmp).1 * BIAS; + for k in 0..bins { + let own = self.est[k] * BIAS; + self.noise[k] = own.min(median.max(own * SEED_SPAN)); + } + } + // The floor moves from 1 to `c.floor` (in dB) over the first search window of sound. + let floor = c.floor.powf(self.heard as f32 / c.window as f32); + for k in 0..bins { + let p = re[k] * re[k] + im[k] * im[k]; + // The noise power falls at once and rises by at most `c.rise` a frame, so a sound + // held longer than the search window is not taken for the noise at once. + self.noise[k] = (self.est[k] * BIAS).min(self.noise[k].max(MIN_NOISE) * c.rise); + let noise = self.noise(k); + let excess = (p / noise - 1.0).max(0.0); + let xi = c.priori * self.clean[k] / noise + (1.0 - c.priori) * excess; + // `1 - 1 / (1 + xi)` is `xi / (1 + xi)`, and stays 1 for an infinite `xi`. + let g = (1.0 - 1.0 / (1.0 + xi)).max(floor); + self.gains[k] = g; + self.clean[k] = flush32(g * g * p); + } + } + for k in 0..bins { + let lo = self.gains[k.saturating_sub(1)]; + let hi = self.gains[(k + 1).min(bins - 1)]; + out[k] = 0.25 * lo + 0.5 * self.gains[k] + 0.25 * hi; + } + } +} + +/// Noise suppression for a live voice: lowers steady background noise (fans, hiss, room tone) by +/// up to `reduction` dB, with no step that learns the noise first. Its latency is the STFT size, +/// 256 samples (5.3 ms) at 48 kHz. Continuous voiced or tonal audio present from startup can +/// enter the noise estimate and be attenuated after the initial search window. +pub struct NoiseSuppression { + pv: ParamValues, + n: usize, + hop: usize, + spec: Spectral, + stft: Vec, + bins: Vec, + /// Gains of the frame being processed, averaged with their neighbors. + smoothed: Vec, + coefs: Coefs, + sample_rate: f32, + /// Samples since the last frame, the same in every channel. + pos: usize, +} + +impl NoiseSuppression { + pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("reduction", "Reduction", 0.0, 40.0, 24.0, Unit::Decibels)]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let n = suppress_size(sample_rate); + let bins = n / 2 + 1; + let ch = crate::sane_channels(channels); + let mut s = NoiseSuppression { + pv: ParamValues::new(Self::PARAMS), + n, + hop: n / OVERLAP, + spec: Spectral::new(n, true), + stft: vec![StftChannel::new(n); ch], + bins: vec![Bins::new(bins); ch], + smoothed: vec![1.0; bins], + coefs: Coefs { floor: 1.0, smooth: 0.0, priori: 0.0, sub_frames: 1, window: SUBWINDOWS, rise: 1.0 }, + sample_rate, + pos: 0, + }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, _snap: bool) { + let frame_s = self.hop as f32 / self.sample_rate; + let sub_frames = ((SEARCH_S / frame_s / SUBWINDOWS as f32).round() as usize).max(1); + self.coefs = Coefs { + floor: db_to_gain(-self.pv.v("reduction")), + smooth: (-frame_s * 1000.0 / POWER_MS).exp(), + priori: (-frame_s * 1000.0 / PRIORI_MS).exp(), + sub_frames, + window: sub_frames * SUBWINDOWS, + // A power ratio: twice the dB of an amplitude ratio. + rise: db_to_gain(2.0 * RISE_DB_S * frame_s), + }; + } +} + +impl AudioEffect for NoiseSuppression { + param_plumbing!("noise_suppression"); + fn latency(&self) -> usize { + self.n + } + fn tail_samples(&self) -> usize { + self.n + } + fn reset(&mut self) { + self.stft.iter_mut().for_each(StftChannel::reset); + self.bins.iter_mut().for_each(Bins::reset); + self.pos = 0; + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + let nch = channels.len().min(self.stft.len()); + // A non-finite sample is taken as silence, so it never reaches the output. + for c in channels.iter_mut().take(nch) { + c[..len].iter_mut().for_each(|v| *v = flush32(*v)); + } + let (n, hop, coefs) = (self.n, self.hop, self.coefs); + let scale = 1.0 / (n as f32 * 2.0); + let plan = Plan { hop, scale, pairing: Pairing::SynthesisOnly }; + // The block runs in pieces that end at the next frame, so each channel's noise estimate + // takes every sample of a frame before the STFT frames it. + let mut start = 0; + while start < len { + let end = len.min(start + hop - self.pos); + for (b, c) in self.bins.iter_mut().zip(channels.iter()).take(nch) { + c[start..end].iter().for_each(|&x| b.sample(x, hop)); + } + let mut piece: [&mut [f32]; MAX_CHANNELS] = std::array::from_fn(|_| <&mut [f32]>::default()); + for (p, c) in piece.iter_mut().zip(channels.iter_mut()).take(nch) { + *p = &mut c[start..end]; + } + let (bins, smoothed) = (&mut self.bins, &mut self.smoothed); + stream(&mut self.stft, &mut self.spec, &mut piece[..nch], end - start, plan, &mut |ch, _, re, im| { + bins[ch].frame(re, im, &coefs, smoothed); + for ((r, i), g) in re.iter_mut().zip(im.iter_mut()).zip(smoothed.iter()) { + *r *= g; + *i *= g; + } + }); + self.pos = (self.pos + end - start) % hop; + start = end; + } + // A channel the block leaves out is fed silence, so it holds none of its earlier audio + // when it comes back. + let half = n / 2 + 1; + let (spec, smoothed) = (&mut self.spec, &mut self.smoothed); + for (st, b) in self.stft.iter_mut().zip(self.bins.iter_mut()).skip(nch) { + for _ in 0..len { + b.sample(0.0, hop); + st.tick(0.0, hop, &mut |input, out| { + spec.analyze(input); + b.frame(&spec.re[..half], &spec.im[..half], &coefs, smoothed); + for k in 0..half { + spec.re[k] *= smoothed[k]; + spec.im[k] *= smoothed[k]; + } + spec.synthesize_add(out, scale); + }); + } + } + // A huge finite input can overflow the inverse FFT. + for c in channels.iter_mut().take(nch) { + c[..len].iter_mut().for_each(|v| *v = flush32(*v)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn suppressor(reduction: f32) -> NoiseSuppression { + let mut s = NoiseSuppression::new(SR, 1); + assert!(s.set_param("reduction", reduction)); + s.reset(); + s + } + + fn white(seed: u64, n: usize, amp: f32) -> Vec { + let mut r = Rng::new(seed); + (0..n).map(|_| r.uniform() * amp).collect() + } + + /// Voiced syllables (seven harmonics of a gliding pitch from 110 to 230 Hz under a sine + /// envelope) with pauses between them, at a peak level of about 0.5. + fn voiced(sr: f64, secs: f64, seed: u64) -> Vec { + let n = (sr * secs) as usize; + let mut rng = Rng::new(seed); + let mut out = vec![0.0f32; n]; + let mut i = 0usize; + while i < n { + let len = ((0.12 + 0.2 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; + let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); + let glide = 1.0 + 0.3 * rng.uniform() as f64; + let amp = 0.1 + 0.1 * (rng.uniform() * 0.5 + 0.5); + for k in 0..len.min(n - i) { + let t = k as f64 / sr; + let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; + let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); + let v: f32 = (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum(); + out[i + k] = v * env * amp; + } + i += len + ((rng.uniform() * 0.5 + 0.5) * 0.25 * sr as f32) as usize; + } + out + } + + /// Runs the suppressor's gains, computed from `speech + noise`, on the speech and the noise + /// apart, so the SNR before and after can be measured. Returns the processed mix, speech and + /// noise. + fn shadow(speech: &[f32], noise: &[f32], reduction: f32) -> (Vec, Vec, Vec) { + let s = suppressor(reduction); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let mut spec = Spectral::new(n, true); + let half = n / 2 + 1; + let scale = 1.0 / (n as f32 * 2.0); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lanes = [StftChannel::new(n), StftChannel::new(n), StftChannel::new(n)]; + let mut out = [vec![0.0f32; speech.len()], vec![0.0f32; speech.len()], vec![0.0f32; speech.len()]]; + for i in 0..speech.len() { + let x = [speech[i] + noise[i], speech[i], noise[i]]; + bins.sample(x[0], hop); + for (lane, (st, o)) in lanes.iter_mut().zip(out.iter_mut()).enumerate() { + o[i] = st.tick(x[lane], hop, &mut |input, frame_out| { + spec.analyze(input); + if lane == 0 { + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + } + for k in 0..half { + spec.re[k] *= gains[k]; + spec.im[k] *= gains[k]; + } + spec.synthesize_add(frame_out, scale); + }); + } + } + let [mix, speech, noise] = out; + (mix, speech, noise) + } + + fn energy(x: &[f32]) -> f64 { + x.iter().map(|&v| v as f64 * v as f64).sum() + } + + /// SNR before and after the suppressor at a reduction of 24 dB, and the change of the voice's + /// own level, in dB, measured from 3 s on (the noise estimate has settled by then). + fn snr_gain(speech: &[f32], noise_amp: f32) -> (f64, f64, f64) { + let len = speech.len(); + let noise = white(17, len, noise_amp); + let (mix, ys, yv) = shadow(speech, &noise, 24.0); + let mut real: Vec = speech.iter().zip(&noise).map(|(a, b)| a + b).collect(); + suppressor(24.0).process(&mut [&mut real]); + assert!(real.iter().zip(&mix).all(|(a, b)| (a - b).abs() < 1e-5), "the shadow run differs from the effect"); + let lat = 256; + let (from, to) = (SR as usize * 3, len - lat); + let after = from + lat..to + lat; + let snr_in = db((energy(&speech[from..to]) / energy(&noise[from..to])).sqrt()); + let snr_out = db((energy(&ys[after.clone()]) / energy(&yv[after.clone()])).sqrt()); + let kept = db((energy(&ys[after]) / energy(&speech[from..to])).sqrt()); + (snr_in, snr_out - snr_in, kept) + } + + /// Voiced syllables in white noise come out with an SNR at least 15 dB higher at an input SNR + /// of 7 dB (13 dB higher at 17 dB), and the voice's level changes by less than 3 dB. + #[test] + fn the_voice_gains_15_db_of_snr_and_keeps_its_level() { + let speech = voiced(SR as f64, 12.0, 4); + for (noise_amp, want) in [(0.06f32, 15.0), (0.02, 13.0)] { + let (snr_in, gain, kept) = snr_gain(&speech, noise_amp); + assert!(gain >= want, "input SNR {snr_in:.1} dB: SNR gain {gain:.1} dB"); + assert!(kept.abs() < 3.0, "input SNR {snr_in:.1} dB: voice level changed by {kept:.2} dB"); + } + } + + /// Speech with consonants (bursts of broadband noise at the level of the vowels) keeps its + /// level within 3 dB and still gains SNR. Bins where a consonant covers the noise keep both. + #[test] + fn speech_with_consonants_keeps_its_level() { + let speech = speechy(SR as f64, 12.0, 4); + for noise_amp in [0.06f32, 0.02] { + let (snr_in, gain, kept) = snr_gain(&speech, noise_amp); + assert!(gain >= 4.0, "input SNR {snr_in:.1} dB: SNR gain {gain:.1} dB"); + assert!(kept.abs() < 3.0, "input SNR {snr_in:.1} dB: speech level changed by {kept:.2} dB"); + } + } + + /// Steady noise falls by close to the reduction setting, at 44.1, 48, 96 and 192 kHz, and the + /// latency is 256 samples up to 50 kHz and doubles with each doubling of the rate above it. + #[test] + fn steady_noise_falls_by_the_reduction() { + for (sr, lat) in [(44_100.0f32, 256), (48_000.0, 256), (96_000.0, 512), (192_000.0, 1024)] { + for reduction in [6.0f32, 12.0, 24.0, 40.0] { + let mut s = NoiseSuppression::new(sr, 1); + assert!(s.set_param("reduction", reduction)); + assert_eq!(s.latency(), lat); + let n = sr as usize * 4; + let x = white(5, n, 0.05); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let tail = n - sr as usize..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + // At 40 dB the Wiener gains of noise-only bins sit above the floor. + let limit = if reduction == 40.0 { 28.0 } else { reduction as f64 - 2.0 }; + assert!(got >= limit && got <= reduction as f64 + 1.0, "{sr} Hz, reduction {reduction}: noise fell by {got:.1} dB"); + } + } + } + + /// At a reduction of 0 the output is the input delayed by the latency. + #[test] + fn zero_reduction_is_a_delay() { + let mut s = suppressor(0.0); + let lat = s.latency(); + let x = speechy(SR as f64, 2.0, 8); + let mut y = x.clone(); + s.process(&mut [&mut y]); + for i in lat..x.len() { + assert!((y[i] - x[i - lat]).abs() < 1e-5, "{i}: {} vs {}", y[i], x[i - lat]); + } + } + + /// The noise estimate follows a noise floor that rises by 12 dB within 3 s, and one that falls + /// by 12 dB at once. + #[test] + fn the_estimate_follows_a_changing_noise_floor() { + let level = |amps: [f32; 2], at: f32| -> f64 { + let mut s = suppressor(24.0); + let n = SR as usize * 8; + let mut rng = Rng::new(31); + let x: Vec = (0..n).map(|i| rng.uniform() * if i < n / 2 { amps[0] } else { amps[1] }).collect(); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let from = n / 2 + (at * SR) as usize; + let range = from..from + SR as usize / 4; + -db(rms(&y[range.clone()]) / rms(&x[range])) + }; + let up = level([0.02, 0.08], 3.0); + assert!(up >= 20.0, "rise: noise fell by {up:.1} dB 3 s later"); + let down = level([0.08, 0.02], 0.25); + assert!(down >= 20.0, "fall: noise fell by {down:.1} dB 0.25 s later"); + } + + /// Noise that starts after digital silence is suppressed again within the search window. + #[test] + fn noise_after_silence_is_suppressed_again() { + let mut s = suppressor(24.0); + let n = SR as usize * 6; + let mut x = white(41, n, 0.05); + x[..SR as usize * 2].fill(0.0); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let tail = n - SR as usize / 2..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// Noise that resumes after a pause of digital silence, or of noise 40 dB lower, is suppressed + /// from the start: the pause does not enter the noise estimate. + #[test] + fn noise_after_a_pause_is_suppressed_at_once() { + for pause_amp in [0.0f32, 0.0005] { + let mut s = suppressor(24.0); + let lat = s.latency(); + let n = SR as usize * 5; + let (pause, resume) = (SR as usize * 3, SR as usize * 4); + let mut x = white(43, n, 0.05); + x[pause..resume].iter_mut().for_each(|v| *v *= pause_amp / 0.05); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let range = resume + lat + SR as usize / 50..resume + lat + SR as usize / 2; + let got = -db(rms(&y[range.clone()]) / rms(&x[range.start - lat..range.end - lat])); + assert!(got >= 20.0, "pause level {pause_amp}: noise fell by {got:.1} dB after the pause"); + } + } + + /// No frame that shares a sample with digital silence enters the noise estimate: not the + /// frames that run into a mute, nor those that run out of it, whether or not the mute starts + /// or ends on a frame boundary. At most two frames per mute that hold no silence are dropped + /// with them. + #[test] + fn frames_that_touch_a_mute_stay_out_of_the_estimate() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + for offset in [0usize, 17, 40, 63] { + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let len = SR as usize; + let mut x = white(29, len, 0.05); + let mutes = [(SR as usize * 3 / 10 + offset, SR as usize * 4 / 10 + offset), (SR as usize * 7 / 10 + offset, SR as usize * 8 / 10)]; + for &(a, b) in &mutes { + x[a..b].fill(0.0); + } + assert!(x.iter().enumerate().all(|(i, v)| *v != 0.0 || mutes.iter().any(|&(a, b)| (a..b).contains(&i)))); + let mut frames = 0usize; + // A frame enters the estimate when the frame `OVERLAP` after it arrives, which is when + // `heard` grows. + let mut entered = Vec::new(); + for &v in &x { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + let heard = bins.heard; + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + frames += 1; + if bins.heard > heard { + entered.push(frames - OVERLAP); + } + }); + } + // Frame `j` (from 1) holds samples `j * hop - n .. j * hop`; samples before 0 are + // the zeros the STFT starts with. + let holds_no_silence = |j: usize| j * hop >= n && x[j * hop - n..j * hop].iter().all(|v| *v != 0.0); + let clean = (1..=frames).filter(|&j| holds_no_silence(j)).count(); + assert!(frames < coefs.window, "the test needs `heard` below its cap"); + assert_eq!(entered.len(), bins.heard); + for &j in &entered { + assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); + } + assert!(bins.heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", bins.heard); + } + } + + /// A mute too short to fill a frame, from one hop long up, keeps the frames that hold a sample + /// of it out of the estimate too, wherever it starts and ends between two hops. + #[test] + fn frames_that_touch_a_short_mute_stay_out_of_the_estimate() { + for offset in [0usize, 17, 40, 63] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut x = white(31, SR as usize / 2, 0.05); + // The last mute is one STFT size long and holds no whole frame unless it starts on a hop. + let mutes = [ + (192 + offset, 256 + offset), + (6000 + offset, 6100 + offset), + (12_000 + offset, 12_200 + offset), + (17_984 + offset, 17_984 + offset + n), + ]; + for &(a, b) in &mutes { + x[a..b].fill(0.0); + } + assert!(x.iter().enumerate().all(|(i, v)| *v != 0.0 || mutes.iter().any(|&(a, b)| (a..b).contains(&i)))); + // One hop per block, so each block ends with a frame. A frame enters the estimate when + // the frame `OVERLAP` after it arrives, which is when `heard` grows. + let mut entered = Vec::new(); + for (k, chunk) in x.chunks(hop).enumerate() { + let heard = s.bins[0].heard; + let mut y = chunk.to_vec(); + s.process(&mut [&mut y]); + if s.bins[0].heard > heard { + entered.push(k + 1 - OVERLAP); + } + } + let frames = x.len() / hop; + let holds_no_silence = |j: usize| j * hop >= n && x[j * hop - n..j * hop].iter().all(|v| *v != 0.0); + let clean = (1..=frames).filter(|&j| holds_no_silence(j)).count(); + assert!(frames < s.coefs.window, "the test needs `heard` below its cap"); + assert_eq!(entered.len(), s.bins[0].heard); + for &j in &entered { + assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); + } + assert!(s.bins[0].heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", s.bins[0].heard); + } + } + + /// Quiet stretches that a mute separates do not add up to a search window: the estimate stays + /// at the noise before them, and falls only after a whole search window of quiet in a row. + #[test] + fn a_mute_ends_a_quiet_run() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let window = coefs.window * hop; + let amp = 0.05f32; + let (loud, quiet, mute) = (SR as usize * 2, window * 6 / 10, SR as usize / 5); + let mut x = white(47, loud + 2 * quiet + mute + window + quiet, amp); + x[loud..].iter_mut().for_each(|v| *v *= 0.01); + x[loud + quiet..loud + quiet + mute].fill(0.0); + let want = amp * amp / 3.0 * n as f32 / 2.0; + let mut feed = |part: &[f32]| -> f64 { + for &v in part { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + }); + } + (1..half - 1).map(|k| db((bins.est[k] as f64 * BIAS as f64 / want as f64).sqrt())).sum::() / (half - 2) as f64 + }; + let split = loud + 2 * quiet + mute; + let kept = feed(&x[..split]); + assert!(kept > -6.0, "after two quiet stretches split by a mute the estimate fell by {:.1} dB", -kept); + let fell = feed(&x[split..]); + assert!(fell < -20.0, "after a search window of quiet the estimate fell by only {:.1} dB", -fell); + } + + #[test] + fn a_short_mute_ends_the_queued_quiet_run() { + for offset in [0, 17] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut loud = white(47, SR as usize * 2, 0.05); + s.process(&mut [&mut loud]); + let mut quiet = white(51, 20 * hop + offset, 0.0005); + s.process(&mut [&mut quiet]); + assert!(s.bins[0].quiet_run > 0); + let mute_end = loud.len() + quiet.len() + hop; + let first_clean_frame = (mute_end + n).div_ceil(hop); + let commit_end = (first_clean_frame + OVERLAP) * hop; + let mut after = white(53, commit_end - loud.len() - quiet.len(), 0.0005); + after[..hop].fill(0.0); + let before_mute = s.bins[0].quiet_run; + s.process(&mut [&mut after[..hop]]); + assert_eq!(s.bins[0].quiet_run, before_mute + 1, "offset {offset}: queued pre-mute frames lost their quiet run"); + s.process(&mut [&mut after[hop..]]); + assert_eq!(s.bins[0].quiet_run, 1, "offset {offset}: pre-mute quiet frames contributed to the new run"); + } + } + + /// A voice that starts with the stream keeps its level within 3 dB over its first 0.25 s and + /// its first 1.5 s, while the suppressor has no noise estimate yet. One of the voices starts on + /// its first sample with a vowel held for 0.25 s. + #[test] + fn a_voice_at_the_start_keeps_its_level() { + let mut abrupt = voiced(SR as f64, 2.0, 7); + let vowel = SR as usize / 4; + let len = abrupt.len(); + abrupt.copy_within(..len - vowel, vowel); + for (i, v) in abrupt[..vowel].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + for speech in [abrupt, voiced(SR as f64, 2.0, 6), speechy(SR as f64, 2.0, 6)] { + let noise = white(19, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + for to in [SR as usize / 4, SR as usize * 3 / 2] { + let kept = db((energy(&ys[lat..to + lat]) / energy(&speech[..to])).sqrt()); + assert!(kept.abs() < 3.0, "voice level changed by {kept:.2} dB in the first {to} samples"); + } + } + } + + /// A steady vowel held for 3 s in noise, longer than the search window, keeps its level within + /// 3 dB over its last second. + #[test] + fn a_held_vowel_keeps_its_level() { + let (lead, held) = (SR as usize * 2, SR as usize * 3); + let mut speech = vec![0.0f32; lead + held + SR as usize / 2]; + for (i, v) in speech[lead..lead + held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + let fade = (i as f32 / 480.0).min(1.0); + *v = fade * (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum::(); + } + let noise = white(37, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + let last = lead + held - SR as usize..lead + held; + let kept = db((energy(&ys[last.start + lat..last.end + lat]) / energy(&speech[last])).sqrt()); + assert!(kept.abs() < 3.0, "the held vowel's level changed by {kept:.2} dB in its last second"); + } + + /// A steady vowel held from the first sample, with no noise before it, keeps its level within + /// 3 dB over its first 2 s, after the floor has reached the reduction. + #[test] + fn a_vowel_held_from_the_start_keeps_its_level() { + let held = SR as usize * 3; + let mut speech = vec![0.0f32; held + SR as usize / 2]; + for (i, v) in speech[..held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + let noise = white(53, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + for range in [0..SR as usize * 2, SR as usize * 3 / 2..SR as usize * 2] { + let kept = db((energy(&ys[range.start + lat..range.end + lat]) / energy(&speech[range.clone()])).sqrt()); + assert!(kept.abs() < 3.0, "the vowel's level changed by {kept:.2} dB over {range:?}"); + } + } + + #[test] + fn a_hop_periodic_startup_vowel_keeps_its_level_at_16_khz() { + let sr = 16_000.0; + let held = sr as usize * 3; + let mut speech = vec![0.0f32; held + sr as usize / 2]; + for (i, v) in speech[..held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 250.0 * i as f64 / sr as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + let mut s = NoiseSuppression::new(sr, 1); + assert!(s.set_param("reduction", 24.0)); + s.reset(); + assert_eq!(s.hop, sr as usize / 250); + let lat = s.latency(); + let mut y = speech.clone(); + s.process(&mut [&mut y]); + for range in [0..sr as usize * 2, sr as usize * 3 / 2..sr as usize * 2] { + let kept = db((energy(&y[range.start + lat..range.end + lat]) / energy(&speech[range.clone()])).sqrt()); + assert!(kept.abs() < 3.0, "the 250 Hz startup vowel at 16 kHz changed by {kept:.2} dB over {range:?}"); + } + } + + /// Steady noise whose spectrum falls with frequency (white noise through a one-pole low-pass + /// at 500 Hz) is suppressed by at least 20 dB from 4 s on. + #[test] + fn steady_low_passed_noise_falls_by_the_reduction() { + let mut s = suppressor(24.0); + let n = SR as usize * 5; + let a = (-std::f32::consts::TAU * 500.0 / SR).exp(); + let mut state = 0.0f32; + let x: Vec = white(59, n, 0.2) + .into_iter() + .map(|v| { + state = a * state + (1.0 - a) * v; + state + }) + .collect(); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let lat = s.latency(); + let from = SR as usize * 4; + let got = -db(rms(&y[from + lat..n]) / rms(&x[from..n - lat])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// NaN, infinite and the largest finite samples give finite output, and the noise is still + /// suppressed afterwards. + #[test] + fn non_finite_and_huge_samples_give_finite_output() { + let mut s = suppressor(24.0); + let n = SR as usize * 4; + let x = white(13, n, 0.05); + let mut y = x.clone(); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + y[3000 + i * 1500] = bad; + y[3001 + i * 1500] = bad; + } + s.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite())); + let tail = n - SR as usize / 2..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// A block that leaves channels out feeds them silence, so when they come back without a + /// reset none of their earlier audio sounds. + #[test] + fn channels_left_out_of_a_block_come_back_silent() { + let noise = white(23, 4_000, 0.5); + let mut s = NoiseSuppression::new(SR, 3); + let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone()); + s.process(&mut [&mut a, &mut b, &mut c]); + // The first channel is silent too, so the paired inverse FFT carries none of its audio + // into the second channel. + let mut a = vec![0.0f32; 4_000]; + s.process(&mut [&mut a]); + let (mut a, mut b, mut c) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + s.process(&mut [&mut a, &mut b, &mut c]); + assert!(b.iter().chain(&c).all(|v| *v == 0.0), "earlier audio came back"); + } + + /// On steady white noise, the noise estimate, averaged over the bins, lands within 1 dB of the + /// noise's mean power once the search window has filled. + #[test] + fn the_noise_estimate_follows_white_noise() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let amp = 0.1f32; + let x = white(3, SR as usize * 4, amp); + for &v in &x { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + }); + } + // uniform noise of amplitude `amp` has a variance of amp²/3; each bin of the + // square-root-Hann windowed FFT gets n/2 of that + let want = amp * amp / 3.0 * n as f32 / 2.0; + let mean = (1..half - 1).map(|k| db((bins.noise(k) as f64 / want as f64).sqrt())).sum::() / (half - 2) as f64; + assert!(mean.abs() < 1.0, "the noise estimate is {mean:.2} dB from the mean power"); + } +} diff --git a/crates/audio-dsp/src/effects/util.rs b/crates/audio-dsp/src/effects/util.rs index eb19d70d72..e16654994e 100644 --- a/crates/audio-dsp/src/effects/util.rs +++ b/crates/audio-dsp/src/effects/util.rs @@ -81,7 +81,14 @@ impl DelayLine { let i0 = self.w + len - 1 - di as usize; let i0 = if i0 >= len { i0 - len } else { i0 }; let i1 = if i0 == 0 { len - 1 } else { i0 - 1 }; - self.buf[i0] + (self.buf[i1] - self.buf[i0]) * frac + let (a, b) = (self.buf[i0], self.buf[i1]); + let y = a + (b - a) * frac; + if y.is_finite() { + y + } else { + // Two large samples of opposite sign overflow `b - a` in f32. + (a as f64 + (b as f64 - a as f64) * frac as f64) as f32 + } } /// Integer read (`d` samples ago, 0 = newest). #[inline] diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs new file mode 100644 index 0000000000..9b8afd96e2 --- /dev/null +++ b/crates/audio-dsp/src/effects/voice.rs @@ -0,0 +1,1288 @@ +//! Effects for a live voice: a pitch shifter with 10 ms of latency and a formant shifter with +//! 10.7 ms of latency (at 48 kHz). +//! +//! The pitch shifter (`voice_pitch`) has two read taps that sweep through a short delay line and +//! crossfade (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms. +//! +//! The taps sit half a sweep apart and are centered on the latency, so the delay of each one +//! stays within `latency ± spacing`. A pitch tracker (YIN, on a copy of the input low-passed and +//! decimated to about 12 kHz, over the last 42.7 ms of history) sets the spacing to a whole number +//! of periods whenever one tap passes the center, so the two taps read the same point of a +//! period and a voiced sound crossfades without beating. A period longer than the room inside the +//! latency (below about 100 Hz), and unvoiced input, use the widest spacing that fits; below +//! 100 Hz each crossfade then steps the phase of the voice, which can move its pitch by a few +//! hertz (5 Hz for 85 Hz shifted up 5 semitones). At a shift +//! of 0 the effect crossfades over 20 ms to the input delayed by the latency, so a neutral setting +//! is a plain delay. +//! +//! The formant shifter (`voice_formant`) moves the spectral envelope of the voice up or down while +//! its harmonics stay where they are. It runs a short STFT (512 points at up to 50 kHz, hop 128). +//! For each frame it fits a linear predictor (one coefficient per kHz plus 2, at most 96) to the +//! last two frame lengths of input (1,024 samples at 48 kHz), which end with the frame and add no +//! latency, and takes the +//! envelope from the predictor. It then multiplies every bin by the envelope read at +//! `bin / ratio` over the envelope at the bin, with at most 24 dB of boost. Its latency is the +//! STFT size. `voice_pitch` uses the same stage for Keep Formants: the stage moves the shifted +//! voice's envelope back by the inverse of the pitch ratio, so the pitch changes and the formants +//! stay, and the latency grows by the STFT size. + +use super::stft::{Spectral, StftChannel, fft_size}; +use crate::biquad::{Biquad, Coeffs, FilterType}; +use crate::fft::Fft; +use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, flush32, param_plumbing}; +use std::f64::consts::PI; + +/// Latency, and the most a tap may read either side of it. +const LATENCY_MS: f32 = 10.0; +/// Lowest and highest fundamental the tracker reports. +const MIN_HZ: f32 = 70.0; +const MAX_HZ: f32 = 1000.0; +/// Rate the tracker analyzes at, before rounding to a whole decimation factor. +const TRACK_RATE: f32 = 12_000.0; +/// YIN's threshold on the cumulative mean normalized difference. +const THRESHOLD: f32 = 0.15; +/// Length of the crossfade to and from the plain delay at a shift of 0. +const BYPASS_MS: f32 = 20.0; +/// Samples kept between a tap and the newest sample, for the cubic interpolation. +const MARGIN: f64 = 2.0; +/// Largest step of the sweep phase per sample; one step never crosses two tap boundaries. +const MAX_STEP: f64 = 0.45; +/// Analysis input is clipped to this level, so a huge sample cannot overflow the tracker. +const TRACK_CLIP: f64 = 1.0e4; +/// Fewest and most predictor coefficients of the formant envelope (one per kHz plus 2 between). +const MIN_ORDER: usize = 8; +const MAX_ORDER: usize = 96; +/// Width of the Gaussian lag window, which widens each envelope peak to about this many hertz. +const LAG_HZ: f64 = 40.0; +/// White noise added to the autocorrelation (60 dB down), so a pure tone still gives a stable +/// predictor. +const WHITE: f64 = 1.0e-6; +/// Largest boost the envelope warp gives one bin: ln 16, about 24 dB. +const MAX_BOOST: f64 = 2.772_588_722_239_781; + +/// STFT size of the formant stage: 512 at up to 50 kHz (10.7 ms at 48 kHz), 1024 up to 100 kHz, +/// 2048 above. +fn formant_size(sample_rate: f32) -> usize { + fft_size(sample_rate) / 4 +} + +/// Fundamental period of the recent input, from YIN (de Cheveigné and Kawahara, 2002) run on a +/// low-passed, decimated copy. Every buffer is sized at creation. +/// +/// It keeps two copies: the mean of the channels, and one channel alone. A frame whose mean holds +/// less than a quarter of that channel's energy (channels of opposite polarity cancel in the +/// mean) is analyzed on that channel. The channel is the first one until another channel holds +/// over four times its energy through one hop; the tracker then moves to the loudest channel, and +/// analyzes that channel's copy only once a whole frame of it has come in. +#[derive(Clone, Debug)] +struct Tracker { + /// Input samples per analysis sample. + factor: usize, + count: usize, + coeffs: [Coeffs; 2], + feeds: [Feed; 2], + at: usize, + hop: usize, + since: usize, + frame: Vec, + diff: Vec, + min_tau: usize, + max_tau: usize, + /// Period in input samples, or `None` when the last frame was unvoiced. + period: Option, + /// Channel the second copy holds. + channel: usize, + /// Energy of each channel's clipped input since the last analysis. + energy: Vec, + /// Analysis samples of `channel` in the second copy, up to the frame length. + filled: usize, +} + +impl Tracker { + fn new(sample_rate: f32, channels: usize) -> Self { + let factor = (sample_rate / TRACK_RATE).round().max(1.0) as usize; + let rate = sample_rate / factor as f32; + let max_hz = MAX_HZ.min(rate / 4.0); + let min_tau = ((rate / max_hz).floor() as usize).max(2); + let max_tau = (rate / MIN_HZ).ceil() as usize + 1; + let len = (2 * max_tau + 2).next_power_of_two(); + // Fourth-order Butterworth low-pass at a quarter of the analysis rate. + let (sr, fc) = (sample_rate as f64, rate as f64 / 4.0); + let coeffs = [0.541_196_1, 1.306_563].map(|q| Coeffs::design(FilterType::LowPass, sr, fc, q, 0.0)); + Tracker { + factor, + count: 0, + coeffs, + feeds: [Feed::new(len), Feed::new(len)], + at: 0, + hop: len / 4, + since: 0, + frame: vec![0.0; len], + diff: vec![0.0; max_tau + 2], + min_tau, + max_tau, + period: None, + channel: 0, + energy: vec![0.0; channels.max(1)], + // The zeros the copy starts with are the first channel's silence. + filled: len, + } + } + + fn reset(&mut self) { + self.count = 0; + self.feeds.iter_mut().for_each(Feed::reset); + self.at = 0; + self.since = 0; + self.period = None; + self.channel = 0; + self.energy.fill(0.0); + self.filled = self.frame.len(); + } + + /// Adds one input sample of channel `c` to that channel's energy. + fn measure(&mut self, c: usize, x: f32) { + if let Some(e) = self.energy.get_mut(c) { + let x = (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP); + *e += x * x; + } + } + + /// Takes one input sample, as the mean of the channels and the sample of the channel in + /// `self.channel`; runs an analysis every `hop` analysis samples. + fn push(&mut self, mean: f32, single: f32) { + let clipped = [mean, single].map(|x| (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP)); + for (feed, x) in self.feeds.iter_mut().zip(clipped) { + feed.filter(&self.coeffs, x); + } + self.count += 1; + if self.count < self.factor { + return; + } + self.count = 0; + let mask = self.frame.len() - 1; + for feed in &mut self.feeds { + feed.ring[self.at] = feed.last as f32; + } + self.at = (self.at + 1) & mask; + self.filled = (self.filled + 1).min(self.frame.len()); + self.since += 1; + if self.since >= self.hop { + self.since = 0; + self.analyze(); + self.choose_channel(); + } + } + + /// Moves the second copy to the loudest channel when that channel held over four times the + /// energy of the one in use since the last analysis. The first of equally loud channels wins. + fn choose_channel(&mut self) { + let loudest = (0..self.energy.len()).fold(0, |b, c| if self.energy[c] > self.energy[b] { c } else { b }); + if self.energy[self.channel] < 0.25 * self.energy[loudest] { + self.channel = loudest; + self.feeds[1].reset(); + self.filled = 0; + } + self.energy.fill(0.0); + } + + fn analyze(&mut self) { + let [mean, single] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::()); + if mean < 0.25 * single && self.filled < self.frame.len() { + // The channel's copy holds less than a frame since the move: keep the last period. + return; + } + let feed = if mean < 0.25 * single { &self.feeds[1] } else { &self.feeds[0] }; + let mask = self.frame.len() - 1; + for (i, v) in self.frame.iter_mut().enumerate() { + *v = feed.ring[(self.at + i) & mask]; + } + self.period = yin(&self.frame, &mut self.diff, self.min_tau, self.max_tau).map(|t| t * self.factor as f64); + } + + /// Tap spacing for the current period: the most whole periods that fit in `max`, or `max` + /// itself for unvoiced input and for a period longer than `max`. + fn spacing(&self, max: f64) -> f64 { + match self.period { + Some(t) if t <= max => (max / t).floor() * t, + _ => max, + } + } +} + +/// One low-passed, decimated copy of the input that the tracker can analyze. +#[derive(Clone, Debug)] +struct Feed { + lowpass: [Biquad; 2], + /// The newest low-passed sample, kept at every input sample. + last: f64, + ring: Vec, +} + +impl Feed { + fn new(len: usize) -> Self { + Feed { lowpass: [Biquad::new(), Biquad::new()], last: 0.0, ring: vec![0.0; len] } + } + + fn reset(&mut self) { + self.lowpass.iter_mut().for_each(Biquad::reset); + self.last = 0.0; + self.ring.iter_mut().for_each(|v| *v = 0.0); + } + + fn filter(&mut self, coeffs: &[Coeffs; 2], x: f64) { + let y = self.lowpass[0].tick(&coeffs[0], x); + self.last = self.lowpass[1].tick(&coeffs[1], y); + } +} + +/// YIN on `frame`: the lag in samples, with parabolic interpolation, or `None` when no lag in +/// `min_tau..max_tau` falls below the threshold. `diff` holds at least `max_tau + 1` values. +fn yin(frame: &[f32], diff: &mut [f32], min_tau: usize, max_tau: usize) -> Option { + let w = frame.len().checked_sub(max_tau)?; + if max_tau <= min_tau + 2 || diff.len() <= max_tau || w == 0 { + return None; + } + difference(frame, &mut diff[..=max_tau], w); + normalize(&mut diff[..=max_tau]); + pick(&diff[..=max_tau], min_tau) +} + +/// Squared difference of the frame with itself at every lag. +fn difference(frame: &[f32], diff: &mut [f32], w: usize) { + diff[0] = 0.0; + for (tau, d) in diff.iter_mut().enumerate().skip(1) { + *d = frame[..w].iter().zip(&frame[tau..tau + w]).map(|(a, b)| (a - b) * (a - b)).sum(); + } +} + +/// Cumulative mean normalized difference, in place. +fn normalize(diff: &mut [f32]) { + diff[0] = 1.0; + let mut running = 0.0f32; + for (tau, d) in diff.iter_mut().enumerate().skip(1) { + running += *d; + *d = if running > 0.0 { *d * tau as f32 / running } else { 1.0 }; + } +} + +/// The first dip below the threshold, walked to its local minimum and interpolated. +fn pick(cmnd: &[f32], min_tau: usize) -> Option { + let last = cmnd.len() - 1; + let mut tau = (min_tau..last).find(|&t| cmnd[t] < THRESHOLD)?; + while tau + 1 < last && cmnd[tau + 1] < cmnd[tau] { + tau += 1; + } + let (a, b, c) = (cmnd[tau - 1] as f64, cmnd[tau] as f64, cmnd[tau + 1] as f64); + let denom = a - 2.0 * b + c; + let shift = if denom.abs() > 1e-12 { (0.5 * (a - c) / denom).clamp(-1.0, 1.0) } else { 0.0 }; + Some(tau as f64 + shift) +} + +/// Four-point cubic Hermite read of `line` at a fractional `delay` behind `pos`. `delay` is at +/// least 2 and leaves two samples in the line behind it. +#[inline] +fn read(line: &[f32], mask: usize, pos: usize, delay: f64) -> f64 { + let i = delay as usize; + let f = delay - i as f64; + let at = |k: usize| line[(pos + line.len() - k) & mask] as f64; + let (ym1, y0, y1, y2) = (at(i - 1), at(i), at(i + 1), at(i + 2)); + let c1 = 0.5 * (y1 - ym1); + let c2 = ym1 - 2.5 * y0 + 2.0 * y1 - 0.5 * y2; + let c3 = 0.5 * (y2 - ym1) + 1.5 * (y0 - y1); + ((c3 * f + c2) * f + c1) * f + y0 +} + +/// Read positions and gains of both taps for one sample. +#[derive(Clone, Copy, Debug)] +struct Taps { + wet: f64, + delay_a: f64, + gain_a: f64, + delay_b: f64, +} + +/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). Keep Formants +/// (`formant_follow`) adds the formant stage's latency, 10.7 ms at 48 kHz, and `latency` reports +/// it while the switch is on. +pub struct VoicePitch { + pv: ParamValues, + latency: usize, + /// Formant stage of Keep Formants, and the share of its output against the shifted voice. + follow: Stage, + follow_mix: f64, + follow_on: bool, + /// Widest tap spacing that keeps both taps inside the line, in samples. + max_spacing: f64, + lines: Vec>, + mask: usize, + pos: usize, + tracker: Tracker, + ratio: f64, + /// Sweep phase in `[0, 1)`: tap A is at the latency when it is 0.5, tap B when it is 0. + phase: f64, + spacing: f64, + /// Share of the shifted signal against the plain delay. + wet: f64, + wet_step: f64, +} + +impl VoicePitch { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::new("semitones", "Pitch", -24.0, 24.0, 0.0, Unit::Semitones), + ParamSpec::new("cents", "Fine Tune (cents)", -100.0, 100.0, 0.0, Unit::None), + ParamSpec::new("formant_follow", "Keep Formants", 0.0, 1.0, 0.0, Unit::Toggle), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + let latency = ((sample_rate * LATENCY_MS / 1000.0).round() as usize).max(4); + let len = (2 * latency + 8).next_power_of_two(); + let mut s = VoicePitch { + pv: ParamValues::new(Self::PARAMS), + latency, + follow: Stage::new(sample_rate, ch), + follow_mix: 0.0, + follow_on: false, + max_spacing: latency as f64 - MARGIN, + lines: vec![vec![0.0; len]; ch], + mask: len - 1, + pos: 0, + tracker: Tracker::new(sample_rate, ch), + ratio: 1.0, + phase: 0.5, + spacing: latency as f64 - MARGIN, + wet: 0.0, + wet_step: 1.0 / (sample_rate * BYPASS_MS / 1000.0).max(1.0) as f64, + }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, snap: bool) { + let shift = self.pv.v("semitones") as f64 + self.pv.v("cents") as f64 / 100.0; + self.ratio = 2f64.powf(shift / 12.0); + self.follow_on = self.pv.v("formant_follow") >= 0.5; + if snap { + self.wet = self.target_wet(); + self.follow_mix = self.follow_target(); + } + } + + fn follow_target(&self) -> f64 { + if self.follow_on { 1.0 } else { 0.0 } + } + + fn target_wet(&self) -> f64 { + if self.ratio == 1.0 { 0.0 } else { 1.0 } + } + + /// Moves the crossfade and the sweep by one sample and returns where the taps read. + fn advance(&mut self) -> Taps { + let target = self.target_wet(); + self.wet = if self.wet < target { (self.wet + self.wet_step).min(target) } else { (self.wet - self.wet_step).max(target) }; + if self.wet == 0.0 { + // Fully on the plain delay: the next shift starts with tap A at the latency. + self.phase = 0.5; + self.spacing = self.max_spacing; + } else { + self.sweep(); + } + let pb = if self.phase >= 0.5 { self.phase - 0.5 } else { self.phase + 0.5 }; + let (l, s) = (self.latency as f64, self.spacing); + Taps { wet: self.wet, delay_a: l + (self.phase - 0.5) * 2.0 * s, gain_a: (PI * self.phase).sin().powi(2), delay_b: l + (pb - 0.5) * 2.0 * s } + } + + /// Advances the sweep phase. A tap whose delay changes by `1 - ratio` per sample reads the + /// input `ratio` times as fast. + fn sweep(&mut self) { + let step = ((1.0 - self.ratio) / (2.0 * self.spacing)).clamp(-MAX_STEP, MAX_STEP); + let raw = self.phase + step; + let wrapped = !(0.0..1.0).contains(&raw); + let p = raw - raw.floor(); + if wrapped || (p >= 0.5) != (self.phase >= 0.5) { + self.regrain(p, wrapped); + } else { + self.phase = p; + } + } + + /// One tap has just passed the latency and the other is silent at the end of its sweep: + /// take the tracker's spacing, and scale the centered tap's small offset so its delay does + /// not jump. + fn regrain(&mut self, p: f64, wrapped: bool) { + let new = self.tracker.spacing(self.max_spacing); + let k = self.spacing / new; + self.spacing = new; + let phase = if wrapped { + // Tap B is centered; its offset from the center is `p` (just past 0) or `p - 1`. + let u = (if p < 0.5 { p } else { p - 1.0 }) * k; + let u = u.clamp(-MAX_STEP, MAX_STEP); + if u < 0.0 { u + 1.0 } else { u } + } else { + 0.5 + ((p - 0.5) * k).clamp(-MAX_STEP, MAX_STEP) + }; + self.phase = if phase < 1.0 { phase } else { 0.0 }; + } +} + +impl AudioEffect for VoicePitch { + param_plumbing!("voice_pitch"); + fn latency(&self) -> usize { + self.latency + if self.follow_on { self.follow.n } else { 0 } + } + fn tail_samples(&self) -> usize { + // A tap reads up to `latency + max_spacing` samples back and the cubic read two samples + // more, which is twice the latency in all. Keep Formants spreads a frame over up to the + // formant stage's size more. A render drains `latency() + tail_samples()` samples. + self.latency + if self.follow_on { self.follow.n } else { 0 } + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|v| *v = 0.0)); + self.pos = 0; + self.tracker.reset(); + self.phase = 0.5; + self.spacing = self.max_spacing; + self.wet = self.target_wet(); + self.follow.reset(); + self.follow_mix = self.follow_target(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + let ch = self.lines.len(); + let dry_at = self.mask + 1 - self.latency; + let follow_target = self.follow_target(); + // The formant stage moves the envelope by the inverse of the pitch ratio. + let back = (1.0 / self.ratio) as f32; + for i in 0..len { + let mut sum = 0.0f32; + for (c, line) in self.lines.iter_mut().enumerate() { + // A non-finite sample is stored as silence, so it never reaches the output. A + // channel the block leaves out is stored as silence too, so its line holds none + // of its earlier audio when it comes back. + let x = channels.get(c).map_or(0.0, |io| flush32(io[i])); + line[self.pos] = x; + sum += x; + self.tracker.measure(c, x); + } + let single = self.lines[self.tracker.channel][self.pos]; + self.tracker.push(sum / ch as f32, single); + let t = self.advance(); + let mix = if self.follow_mix < follow_target { + (self.follow_mix + self.wet_step).min(follow_target) + } else { + (self.follow_mix - self.wet_step).max(follow_target) + }; + self.follow_mix = mix; + // While Keep Formants is off and faded out, the stage's frames copy the shifted voice, + // so switching it on crossfades from a delayed copy instead of from silence. + let warp = if mix > 0.0 { back } else { 1.0 }; + // A channel the block leaves out still reads its line into the formant stage, so the + // audio its line holds reaches the stage on time; only its output is dropped. + for (c, line) in self.lines.iter().enumerate() { + let dry = line[(self.pos + dry_at) & self.mask] as f64; + let y = if t.wet == 0.0 { + dry + } else { + let shifted = + t.gain_a * read(line, self.mask, self.pos, t.delay_a) + (1.0 - t.gain_a) * read(line, self.mask, self.pos, t.delay_b); + t.wet * shifted + (1.0 - t.wet) * dry + }; + let y = y.clamp(-f32::MAX as f64, f32::MAX as f64); + let z = self.follow.tick(c, y as f32, warp); + // The stage's output is `n` samples later than `y`, so a switch fades one out + // before the other comes in instead of mixing them. + let out = if mix < 0.5 { (1.0 - 2.0 * mix) * y } else { (2.0 * mix - 1.0) * z as f64 }; + if let Some(io) = channels.get_mut(c) { + io[i] = out.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + } + } + self.pos = (self.pos + 1) & self.mask; + } + } +} + +/// Spectral envelope of the recent input from linear prediction, and the warp that moves it. +/// Every buffer is sized at creation. +#[derive(Clone, Debug)] +struct Envelope { + fft: Fft, + /// Hann window over the analyzed history. + window: Vec, + /// Gaussian lag window, one value per autocorrelation lag (`order + 1`). + lags: Vec, + frame: Vec, + r: Vec, + /// Predictor coefficients, `a[0] = 1`. + a: Vec, + prev: Vec, + re: Vec, + im: Vec, + /// Natural log of the envelope's magnitude, bins 0..=n/2 of the STFT. + log: Vec, +} + +impl Envelope { + /// An envelope for STFT frames of `n` points, read from the last `2 n` samples. + fn new(n: usize, sample_rate: f32) -> Self { + let order = ((sample_rate / 1000.0).round() as usize + 2).clamp(MIN_ORDER, MAX_ORDER); + let w = 2 * n; + let window = (0..w).map(|i| 0.5 - 0.5 * (2.0 * PI * (i as f64 + 0.5) / w as f64).cos()).collect(); + let lags = (0..=order) + .map(|i| { + let x = 2.0 * PI * LAG_HZ * i as f64 / sample_rate as f64; + (-0.5 * x * x).exp() + }) + .collect(); + Envelope { + fft: Fft::new(n), + window, + lags, + frame: vec![0.0; w], + r: vec![0.0; order + 1], + a: vec![0.0; order + 1], + prev: vec![0.0; order + 1], + re: vec![0.0; n], + im: vec![0.0; n], + log: vec![0.0; n / 2 + 1], + } + } + + /// Reads the envelope of the newest `2 n` samples of `history`. Returns `false` for silence, + /// which has no envelope. + fn measure(&mut self, history: &History) -> bool { + let mask = history.ring.len() - 1; + for (i, (v, w)) in self.frame.iter_mut().zip(&self.window).enumerate() { + *v = history.ring[(history.pos + i) & mask] as f64 * w; + } + let len = self.frame.len(); + self.r[0] = dot(&self.frame, &self.frame) * self.lags[0]; + if !(self.r[0] > 0.0 && self.r[0].is_finite()) { + return false; + } + for (lag, (r, w)) in self.r.iter_mut().zip(&self.lags).enumerate().skip(1) { + *r = dot(&self.frame[..len - lag], &self.frame[lag..]) * w; + } + self.r[0] *= 1.0 + WHITE; + levinson(&self.r, &mut self.a, &mut self.prev); + // The envelope is 1 / |A| on the bins of the STFT. + self.re.fill(0.0); + self.im.fill(0.0); + for (v, a) in self.re.iter_mut().zip(&self.a) { + *v = *a as f32; + } + self.fft.forward(&mut self.re, &mut self.im); + for (l, (re, im)) in self.log.iter_mut().zip(self.re.iter().zip(&self.im)) { + *l = (-0.5 * (*re as f64 * *re as f64 + *im as f64 * *im as f64 + 1e-30).ln()) as f32; + } + true + } + + /// Multiplies the half spectrum `re`/`im` (bins 0..=n/2) by the envelope read at `bin / + /// ratio` over the envelope at the bin, so the envelope moves up by `ratio` and the + /// harmonics stay. A frame with a non-finite bin is replaced with silence. + fn warp(&self, re: &mut [f32], im: &mut [f32], ratio: f32) { + let half = self.log.len(); + let (re, im) = (&mut re[..half], &mut im[..half]); + if !re.iter().chain(im.iter()).fold(true, |ok, v| ok & v.is_finite()) { + re.fill(0.0); + im.fill(0.0); + return; + } + let last = (half - 1) as f32; + for k in 0..half { + let src = (k as f32 / ratio).min(last); + let i = src as usize; + let e = match self.log.get(i + 1) { + Some(next) => self.log[i] + (src - i as f32) * (next - self.log[i]), + None => self.log[i], + }; + let g = ((e - self.log[k]) as f64).min(MAX_BOOST).exp() as f32; + re[k] *= g; + im[k] *= g; + } + } +} + +/// Dot product of two slices of the same length, in four running sums so it vectorizes. +fn dot(a: &[f64], b: &[f64]) -> f64 { + let mut sums = [0.0f64; 4]; + let ((ca, ra), (cb, rb)) = (a.as_chunks::<4>(), b.as_chunks::<4>()); + for (x, y) in ca.iter().zip(cb) { + for ((s, x), y) in sums.iter_mut().zip(x).zip(y) { + *s += x * y; + } + } + let rest: f64 = ra.iter().zip(rb).map(|(x, y)| x * y).sum(); + (sums[0] + sums[1]) + (sums[2] + sums[3]) + rest +} + +/// Levinson-Durbin recursion: the predictor `a` (`a[0] = 1`) of the autocorrelation `r`. It +/// stops at the first reflection coefficient that would make the predictor unstable. +fn levinson(r: &[f64], a: &mut [f64], prev: &mut [f64]) { + a.fill(0.0); + a[0] = 1.0; + let mut err = r[0]; + for i in 1..a.len() { + let acc = r[i] + (1..i).map(|j| a[j] * r[i - j]).sum::(); + let k = -acc / err; + // NaN (from a zero error) also stops the recursion. + if k.is_nan() || k.abs() >= 1.0 { + return; + } + prev[..i].copy_from_slice(&a[..i]); + for j in 1..i { + a[j] = prev[j] + k * prev[i - j]; + } + a[i] = k; + err *= 1.0 - k * k; + } +} + +/// The newest samples of one channel, for the envelope. +#[derive(Clone, Debug)] +struct History { + ring: Vec, + /// Where the next sample goes, which is also the oldest sample. + pos: usize, +} + +impl History { + fn push(&mut self, x: f32) { + self.ring[self.pos] = x; + self.pos = (self.pos + 1) & (self.ring.len() - 1); + } + + fn reset(&mut self) { + self.ring.fill(0.0); + self.pos = 0; + } +} + +/// STFT stage that moves each channel's envelope, fed one sample at a time: the formant +/// shifter, and the formant stage of `voice_pitch`'s Keep Formants. +#[derive(Clone, Debug)] +struct Stage { + n: usize, + hop: usize, + scale: f32, + spec: Spectral, + stft: Vec, + history: Vec, + env: Envelope, +} + +impl Stage { + fn new(sample_rate: f32, channels: usize) -> Self { + let n = formant_size(sample_rate); + Stage { + n, + hop: n / 4, + // √Hann on both sides is Hann, which sums to 2 at a hop of n/4; the inverse FFT is + // unscaled. + scale: 1.0 / (2 * n) as f32, + spec: Spectral::new(n, true), + stft: vec![StftChannel::new(n); channels], + history: vec![History { ring: vec![0.0; 2 * n], pos: 0 }; channels], + env: Envelope::new(n, sample_rate), + } + } + + fn reset(&mut self) { + self.stft.iter_mut().for_each(StftChannel::reset); + self.history.iter_mut().for_each(History::reset); + } + + /// Pushes one sample of a channel and returns the stage's output for it, `n` samples later. + /// A frame moves the envelope by `ratio`, which can spread a sound over the frame, so the + /// output can go on for up to `n` samples more (the tail). At a ratio of 1, and for silence, a frame only + /// windows and adds its input, which needs no FFT. + fn tick(&mut self, channel: usize, x: f32, ratio: f32) -> f32 { + let Stage { n, hop, scale, spec, stft, history, env } = self; + let half = *n / 2 + 1; + history[channel].push(x); + let history = &history[channel]; + let z = stft[channel].tick(x, *hop, &mut |input, out| { + if ratio != 1.0 && env.measure(history) { + spec.analyze(input); + env.warp(&mut spec.re[..half], &mut spec.im[..half], ratio); + spec.synthesize_add(out, *scale); + } else { + for ((o, x), w) in out.iter_mut().zip(input).zip(&spec.window) { + *o += x * w * w * 0.5; + } + } + }); + // A huge finite input can overflow the inverse FFT. + flush32(z) + } +} + +/// Formant shifter for a live voice: moves the spectral envelope by -12 to +12 semitones (a ratio +/// of 0.5 to 2) and keeps the harmonics. Its latency is the STFT size, 512 samples (10.7 ms) at +/// 48 kHz. +pub struct VoiceFormant { + pv: ParamValues, + stage: Stage, + ratio: f32, +} + +impl VoiceFormant { + pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("semitones", "Formant Shift", -12.0, 12.0, 0.0, Unit::Semitones)]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let mut s = VoiceFormant { pv: ParamValues::new(Self::PARAMS), stage: Stage::new(sample_rate, crate::sane_channels(channels)), ratio: 1.0 }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, _snap: bool) { + self.ratio = 2f32.powf(self.pv.v("semitones") / 12.0); + } +} + +impl AudioEffect for VoiceFormant { + param_plumbing!("voice_formant"); + fn latency(&self) -> usize { + self.stage.n + } + fn tail_samples(&self) -> usize { + self.stage.n + } + fn reset(&mut self) { + self.stage.reset(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + for i in 0..len { + for c in 0..self.stage.stft.len() { + // A non-finite sample is taken as silence, so it never reaches the output. A + // channel the block leaves out is fed silence, so it holds none of its earlier + // audio when it comes back. + match channels.get_mut(c) { + Some(io) => io[i] = self.stage.tick(c, flush32(io[i]), self.ratio), + None => { + self.stage.tick(c, 0.0, self.ratio); + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn shifter(semitones: f32, cents: f32) -> VoicePitch { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("semitones", semitones) && p.set_param("cents", cents)); + p.reset(); + p + } + + fn run(p: &mut VoicePitch, x: &[f32]) -> Vec { + let (mut l, mut r) = (x.to_vec(), x.to_vec()); + p.process(&mut [&mut l, &mut r]); + assert_eq!(l, r, "both channels get the same shift"); + l + } + + /// One second of output after the first half second. + fn settled(y: &[f32]) -> &[f32] { + &y[SR as usize / 2..SR as usize * 3 / 2] + } + + /// Frequency of the strongest component between `lo` and `hi` Hz, to 0.01 Hz. + fn peak_hz(x: &[f32], lo: f64, hi: f64) -> f64 { + let best = |from: f64, to: f64, step: f64| { + let n = ((to - from) / step) as usize; + (0..=n) + .map(|i| from + i as f64 * step) + .max_by(|a, b| tone_amplitude(x, *a, SR as f64).total_cmp(&tone_amplitude(x, *b, SR as f64))) + .unwrap_or(from) + }; + let coarse = best(lo, hi, 0.25); + best(coarse - 0.25, coarse + 0.25, 0.01) + } + + fn cents(f: f64, want: f64) -> f64 { + 1200.0 * (f / want).log2() + } + + /// A voiced tone shifted by an octave either way, or by a fifth with a fine offset, lands on + /// the shifted frequency within 2 cents. + #[test] + fn a_shifted_tone_reads_the_shifted_frequency() { + for (f_in, semis, fine) in [(220.0, 12.0, 0.0), (220.0, -12.0, 0.0), (180.0, 7.0, 30.0), (110.0, -24.0, 0.0)] { + let mut p = shifter(semis, fine); + let y = run(&mut p, &sine(f_in, 0.5, SR as f64, SR as usize * 2, 0.0)); + let want = f_in * 2f64.powf((semis as f64 + fine as f64 / 100.0) / 12.0); + let got = peak_hz(settled(&y), want * 0.9, want * 1.1); + assert!(cents(got, want).abs() < 2.0, "{f_in} Hz {semis:+} st {fine:+} ct: {got} Hz, want {want}"); + } + } + + /// On a voiced tone the taps are spaced by whole periods, so the crossfades do not beat: + /// almost all the output is the shifted tone. + #[test] + fn a_voiced_tone_crossfades_without_beating() { + for (f_in, semis) in [(220.0, 7.0), (150.0, -5.0), (300.0, 12.0)] { + let mut p = shifter(semis, 0.0); + let y = run(&mut p, &sine(f_in, 0.5, SR as f64, SR as usize * 2, 0.0)); + let rest = beside_tone_db(&y, f_in * 2f64.powf(semis as f64 / 12.0)); + assert!(rest < -40.0, "{f_in} Hz {semis:+} st: {rest:.1} dB beside the tone"); + } + } + + /// With a silent first channel, a voice on the other two channels in opposite polarity is + /// still tracked from one of them and crossfades without beating. + #[test] + fn opposite_polarity_beside_a_silent_first_channel_is_still_tracked() { + let mut p = VoicePitch::new(SR, 3); + assert!(p.set_param("semitones", 7.0)); + p.reset(); + let n = SR as usize * 2; + let mut silent = vec![0.0f32; n]; + let mut l = sine(220.0, 0.5, SR as f64, n, 0.0); + let mut r: Vec = l.iter().map(|v| -v).collect(); + p.process(&mut [&mut silent, &mut l, &mut r]); + assert!(silent.iter().all(|v| *v == 0.0)); + assert!(l.iter().zip(&r).all(|(a, b)| *a == -*b)); + let rest = beside_tone_db(&l, 220.0 * 2f64.powf(7.0 / 12.0)); + assert!(rest < -40.0, "{rest:.1} dB beside the tone"); + } + + /// A voice whose two channels have opposite polarity, which cancel in their mean, is still + /// tracked and crossfades without beating. + #[test] + fn opposite_polarity_channels_are_still_tracked() { + let mut p = shifter(7.0, 0.0); + let mut l = sine(220.0, 0.5, SR as f64, SR as usize * 2, 0.0); + let mut r: Vec = l.iter().map(|v| -v).collect(); + p.process(&mut [&mut l, &mut r]); + assert!(l.iter().zip(&r).all(|(a, b)| *a == -*b)); + let rest = beside_tone_db(&l, 220.0 * 2f64.powf(7.0 / 12.0)); + assert!(rest < -40.0, "{rest:.1} dB beside the tone"); + } + + /// Level of everything but the strongest component near `want`, against that component, in + /// the settled output. + fn beside_tone_db(y: &[f32], want: f64) -> f64 { + let tail = settled(y); + let tone = tone_amplitude(tail, peak_hz(tail, want * 0.98, want * 1.02), SR as f64) / std::f64::consts::SQRT_2; + db((rms(tail).powi(2) - tone * tone).max(0.0).sqrt() / tone) + } + + /// The output of a burst, shifted or not, comes from taps within the spacing of the latency: + /// nothing sounds earlier than `latency - tail` or later than `latency + tail` around it. + #[test] + fn a_shifted_burst_stays_within_the_spacing_of_the_latency() { + for semis in [0.0, -24.0, -3.0, 5.0, 24.0] { + let mut p = shifter(semis, 0.0); + let (n, at, len) = (8000, 1777, 1000); + let mut rng = Rng::new(7); + let mut x = vec![0.0f32; n]; + x[at..at + len].iter_mut().for_each(|v| *v = 0.5 * rng.uniform()); + let y = run(&mut p, &x); + let reach = p.tail_samples(); + let (lo, hi) = (at + p.latency() - reach, at + len + p.latency() + reach); + assert!(y.iter().enumerate().all(|(i, v)| *v == 0.0 || (lo..hi).contains(&i)), "{semis}"); + assert!(y.iter().any(|v| v.abs() > 0.05), "{semis}: the burst is lost"); + } + } + + /// Over whole sweeps, the oldest sample either tap reads, interpolation included, lies within + /// the latency plus the tail, so a render that compensates the latency and runs the tail past + /// the end of the input keeps every sample the taps still hold. + #[test] + fn the_tail_covers_the_oldest_sample_a_tap_reads() { + for semis in [-24.0, -3.0, 5.0, 24.0] { + let mut p = shifter(semis, 0.0); + let oldest = (0..SR as usize).map(|_| p.advance()).map(|t| t.delay_a.max(t.delay_b) as usize + 2).max().unwrap_or(0); + assert!(oldest > p.latency(), "{semis}: the taps never sweep past the latency"); + assert!(oldest <= p.latency() + p.tail_samples(), "{semis}: a tap reads {oldest} samples back"); + } + } + + /// A gliding voiced tone with a shift change part way gives the same output however the + /// stream is cut into blocks, spacing changes included. + #[test] + fn output_does_not_depend_on_how_the_stream_is_cut() { + let n = 40_000; + let x: Vec = (0..n) + .map(|i| (0.4 * (2.0 * std::f64::consts::PI * (120.0 * i as f64 / 48_000.0 + 0.6 * (i as f64 / 48_000.0).powi(2) * 200.0)).sin()) as f32) + .collect(); + let change = 17_321; + let run_cut = |sizes: &mut dyn FnMut() -> usize| { + let mut p = shifter(4.0, -20.0); + let mut y = x.clone(); + let mut pos = 0; + while pos < n { + if pos == change { + p.set_param("semitones", -9.0); + } + let mut len = sizes().min(n - pos); + if pos < change { + len = len.min(change - pos); + } + p.process(&mut [&mut y[pos..pos + len]]); + pos += len; + } + y + }; + let whole = run_cut(&mut || usize::MAX); + let mut rng = Rng::new(11); + let cut = run_cut(&mut || (rng.next_u64() % 700) as usize); + assert!(whole.iter().zip(&cut).all(|(a, b)| a.to_bits() == b.to_bits())); + } + + /// NaN, infinite and the largest finite samples in a shifted voice give finite output, and + /// the voice is still shifted afterwards. + #[test] + fn non_finite_and_huge_samples_give_finite_output() { + let mut p = shifter(-7.0, 0.0); + let mut x = sine(200.0, 0.5, SR as f64, SR as usize * 2, 0.0); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + x[3000 + i * 1500] = bad; + x[3001 + i * 1500] = bad; + } + let y = run(&mut p, &x); + assert!(y.iter().all(|v| v.is_finite())); + let want = 200.0 * 2f64.powf(-7.0 / 12.0); + let tail = settled(&y); + assert!(cents(peak_hz(tail, want * 0.9, want * 1.1), want).abs() < 2.0); + assert!(db(rms(tail) / (0.5 / std::f64::consts::SQRT_2)).abs() < 1.0, "level {}", rms(tail)); + } + + /// Two-pole resonance magnitude at `f`, 1 at `center`. + fn resonance(f: f64, center: f64, bandwidth: f64) -> f64 { + center * bandwidth / ((center * center - f * f).powi(2) + (f * bandwidth).powi(2)).sqrt() + } + + /// A vowel: harmonics of `f0` up to 6 kHz shaped by two formants (`f1` with an 80 Hz + /// bandwidth, `f2` with 120 Hz and half the level) over a floor 34 dB down. + fn vowel(f0: f64, f1: f64, f2: f64, sr: f64, n: usize) -> Vec { + let harmonics: Vec<(f64, f64)> = (1..) + .map(|k| k as f64 * f0) + .take_while(|f| *f < 6000.0) + .map(|f| (f, 0.02 + resonance(f, f1, 80.0) + 0.5 * resonance(f, f2, 120.0))) + .collect(); + (0..n) + .map(|i| { + let t = i as f64 / sr; + (0.08 * harmonics.iter().map(|(f, a)| a * (2.0 * std::f64::consts::PI * f * t).sin()).sum::()) as f32 + }) + .collect() + } + + /// The envelope peak of `y` between `lo` and `hi` Hz, read from the amplitudes of the + /// harmonics of `f0` with a parabola through the strongest one and its neighbors (in dB). + fn envelope_peak(y: &[f32], f0: f64, lo: f64, hi: f64, sr: f64) -> f64 { + let amp = |k: usize| tone_amplitude(y, k as f64 * f0, sr).max(1e-12).ln(); + let ks = (lo / f0).ceil() as usize..=(hi / f0).floor() as usize; + let k = ks.max_by(|a, b| amp(*a).total_cmp(&(*b))).unwrap_or(1); + let (a, b, c) = (amp(k - 1), amp(k), amp(k + 1)); + let denom = a - 2.0 * b + c; + let shift = if denom.abs() > 1e-12 { (0.5 * (a - c) / denom).clamp(-1.0, 1.0) } else { 0.0 }; + (k as f64 + shift) * f0 + } + + /// The second of `y` after its first half second, at the rate `sr`. + fn settled_at(y: &[f32], sr: f64) -> &[f32] { + &y[sr as usize / 2..sr as usize * 3 / 2] + } + + /// The two formants of the vowel test signal (600 and 2000 Hz) in `y`, each looked for within + /// a window moved by `ratio`, with `y`'s harmonics at multiples of `f0`. + fn formants(y: &[f32], f0: f64, ratio: f64, sr: f64) -> (f64, f64) { + let tail = settled_at(y, sr); + (envelope_peak(tail, f0, 400.0 * ratio, 1000.0 * ratio, sr), envelope_peak(tail, f0, 1400.0 * ratio, 3000.0 * ratio, sr)) + } + + /// Level of everything off the harmonics of `f0` in `y`'s settled second, against the whole, + /// in dB. + fn off_harmonics_db(y: &[f32], f0: f64, sr: f64) -> f64 { + let tail = settled_at(y, sr); + let total = rms(tail).powi(2); + let on: f64 = (1..).map(|k| k as f64 * f0).take_while(|f| *f < sr / 2.0 - f0).map(|f| tone_amplitude(tail, f, sr).powi(2) / 2.0).sum(); + 10.0 * ((total - on).max(1e-30) / total).log10() + } + + /// A formant shift moves both formants of a vowel by the ratio, within a tenth of the move for + /// the first and 5% for the second, while every partial stays on the harmonics of the + /// unchanged fundamental. Checked at three voice pitches and three sample rates. + #[test] + fn a_formant_shift_moves_the_envelope_and_keeps_the_harmonics() { + for sr in [44_100.0, 48_000.0, 96_000.0] { + for f0 in [110.0, 150.0, 220.0] { + let x = vowel(f0, 600.0, 2000.0, sr, sr as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + for semis in [-4.0f32, 4.0] { + let mut f = VoiceFormant::new(sr as f32, 1); + assert!(f.set_param("semitones", semis)); + let mut y = x.clone(); + f.process(&mut [&mut y]); + let r = 2f64.powf(semis as f64 / 12.0); + let (q1, q2) = formants(&y, f0, r, sr); + let at = format!("{sr} Hz, f0 {f0}, {semis:+} st: formants {p1:.0} and {p2:.0} moved to {q1:.0} and {q2:.0}"); + assert!((q1 / (p1 * r) - 1.0).abs() < 0.12, "{at}"); + assert!((q2 / (p2 * r) - 1.0).abs() < 0.05, "{at}"); + let off = off_harmonics_db(&y, f0, sr); + assert!(off < -30.0, "{at}: {off:.1} dB off the harmonics"); + } + } + } + } + + /// Keep Formants: the pitch moves up a fourth, and the formants of the vowel stay where they + /// were (where without it they move with the pitch). + #[test] + fn keep_formants_holds_the_envelope_while_the_pitch_moves() { + let (sr, f0) = (SR as f64, 150.0); + let x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + let r = 2f64.powf(5.0 / 12.0); + for keep in [false, true] { + let mut p = shifter(5.0, 0.0); + assert!(p.set_param("formant_follow", if keep { 1.0 } else { 0.0 })); + p.reset(); + let y = run(&mut p, &x); + let want = if keep { 1.0 } else { r }; + let (q1, q2) = formants(&y, f0 * r, want, sr); + let at = format!("keep {keep}: formants {p1:.0} and {p2:.0} read {q1:.0} and {q2:.0}"); + assert!((q1 / (p1 * want) - 1.0).abs() < 0.12, "{at}"); + assert!((q2 / (p2 * want) - 1.0).abs() < 0.05, "{at}"); + assert!(cents(peak_hz(settled(&y), f0 * r * 0.98, f0 * r * 1.02), f0 * r).abs() < 2.0, "keep {keep}: pitch"); + } + } + + /// Keep Formants adds the formant shifter's latency to the pitch shifter's while it is on, at + /// each rate. + #[test] + fn the_latency_reports_the_formant_stage() { + for sr in [44_100.0, 48_000.0, 96_000.0] { + let n = VoiceFormant::new(sr, 2).latency(); + assert!(n > 0, "{sr}"); + let mut p = VoicePitch::new(sr, 2); + let base = p.latency(); + assert!(p.set_param("formant_follow", 1.0)); + assert_eq!(p.latency(), base + n, "{sr}"); + assert!(p.set_param("formant_follow", 0.0)); + assert_eq!(p.latency(), base, "{sr}"); + } + } + + /// After a burst of noise ends, the formant shifter and the pitch shifter with Keep Formants + /// fall silent within `latency + tail_samples`, so an offline render that drains that long + /// keeps all of the output. + #[test] + fn formant_output_ends_within_the_reported_tail() { + let (n, at, len) = (12_000, 1_777, 1_000); + let mut rng = Rng::new(17); + let mut x = vec![0.0f32; n]; + x[at..at + len].iter_mut().for_each(|v| *v = 0.5 * rng.uniform()); + let mut f = VoiceFormant::new(SR, 1); + assert!(f.set_param("semitones", 7.0)); + let mut p = shifter(-5.0, 0.0); + assert!(p.set_param("formant_follow", 1.0)); + p.reset(); + let fxs: [&mut dyn AudioEffect; 2] = [&mut f, &mut p]; + for fx in fxs { + let mut y = x.clone(); + fx.process(&mut [&mut y]); + let end = at + len + fx.latency() + fx.tail_samples(); + assert!(y[end..].iter().all(|v| *v == 0.0), "{}: output after {end}", fx.id()); + } + } + + /// Switching Keep Formants on fades the shifter's own output out over 10 ms and then fades the + /// formant stage's output, 512 samples later, in over 10 ms: the two never sound together, + /// so their different delays cannot comb-filter the voice. Checked at a shift of 0, where the + /// stage passes the voice unchanged. + #[test] + fn switching_keep_formants_fades_through_silence() { + let x = vowel(170.0, 650.0, 1900.0, SR as f64, 12_000); + let at = 4_000; + let mut plain = shifter(0.0, 0.0); + let y = run(&mut plain, &x); + let mut p = shifter(0.0, 0.0); + let mut out = x.clone(); + p.process(&mut [&mut out[..at]]); + assert!(p.set_param("formant_follow", 1.0)); + p.process(&mut [&mut out[at..]]); + let n = p.follow.n; + let step = 1.0 / (SR as f64 * BYPASS_MS as f64 / 1000.0); + for i in at..x.len() { + let m = ((i - at + 1) as f64 * step).min(1.0); + let want = if m < 0.5 { (1.0 - 2.0 * m) * y[i] as f64 } else { (2.0 * m - 1.0) * y[i - n] as f64 }; + assert!((out[i] as f64 - want).abs() < 1e-4, "sample {i}: {} against {want}", out[i]); + } + } + + /// The formant shifter with a shift change part way, and the pitch shifter with Keep Formants + /// switched on and off part way, give the same output however the stream is cut into blocks. + #[test] + fn formant_output_does_not_depend_on_how_the_stream_is_cut() { + let n = 40_000; + let x = vowel(130.0, 700.0, 1800.0, SR as f64, n); + let changes: [(usize, &str, f32); 3] = [(9_001, "semitones", 3.0), (17_321, "formant_follow", 1.0), (29_999, "formant_follow", 0.0)]; + let run_cut = |make: &dyn Fn() -> Box, sizes: &mut dyn FnMut() -> usize| { + let mut fx = make(); + let mut y = x.clone(); + let mut pos = 0; + while pos < n { + for (at, id, v) in changes { + if pos == at { + fx.set_param(id, v); + } + } + let next = changes.iter().map(|c| c.0).find(|at| *at > pos).unwrap_or(n); + let len = sizes().min(next - pos); + fx.process(&mut [&mut y[pos..pos + len]]); + pos += len; + } + y + }; + let makers: [&dyn Fn() -> Box; 2] = [ + &|| { + let mut f = VoiceFormant::new(SR, 1); + f.set_param("semitones", -5.0); + Box::new(f) + }, + &|| Box::new(shifter(-3.0, 0.0)), + ]; + for make in makers { + let whole = run_cut(make, &mut || usize::MAX); + let mut rng = Rng::new(13); + let cut = run_cut(make, &mut || (rng.next_u64() % 700) as usize); + assert!(whole.iter().zip(&cut).all(|(a, b)| a.to_bits() == b.to_bits())); + assert!(whole.iter().any(|v| v.abs() > 0.05)); + } + } + + /// NaN, infinite and the largest finite samples in a vowel give finite output from the formant + /// shifter and from Keep Formants, and the formants are still moved afterwards. + #[test] + fn formant_stage_output_stays_finite() { + let (sr, f0) = (SR as f64, 150.0); + let mut x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + x[3000 + i * 1500] = bad; + x[3001 + i * 1500] = bad; + } + let mut f = VoiceFormant::new(SR, 2); + assert!(f.set_param("semitones", 4.0)); + let (mut l, mut r) = (x.clone(), x.clone()); + f.process(&mut [&mut l, &mut r]); + assert!(l.iter().chain(&r).all(|v| v.is_finite())); + let ratio = 2f64.powf(4.0 / 12.0); + let (q1, _) = formants(&l, f0, ratio, sr); + assert!((q1 / (p1 * ratio) - 1.0).abs() < 0.12, "{q1}"); + let mut p = shifter(-7.0, 0.0); + assert!(p.set_param("formant_follow", 1.0)); + let y = run(&mut p, &x); + assert!(y.iter().all(|v| v.is_finite())); + assert!(rms(settled(&y)) > 0.01); + let shifted_f0 = f0 * 2f64.powf(-7.0 / 12.0); + let (q1, q2) = formants(&y, shifted_f0, 1.0, sr); + assert!((q1 / p1 - 1.0).abs() < 0.12, "Keep Formants: {p1} read {q1}"); + assert!((q2 / p2 - 1.0).abs() < 0.05, "Keep Formants: {p2} read {q2}"); + } + + /// A block that leaves channels out feeds them silence, so when they come back without a + /// reset none of their earlier audio sounds. Checked for the formant shifter and for the + /// pitch shifter with and without Keep Formants. + #[test] + fn channels_left_out_of_a_block_come_back_silent() { + let mut rng = Rng::new(19); + let noise: Vec = (0..4_000).map(|_| 0.5 * rng.uniform()).collect(); + let mut f = VoiceFormant::new(SR, 3); + assert!(f.set_param("semitones", 4.0)); + let mut plain = VoicePitch::new(SR, 3); + assert!(plain.set_param("semitones", 5.0)); + plain.reset(); + let mut keep = VoicePitch::new(SR, 3); + assert!(keep.set_param("semitones", 5.0) && keep.set_param("formant_follow", 1.0)); + keep.reset(); + let fxs: [&mut dyn AudioEffect; 3] = [&mut f, &mut plain, &mut keep]; + for fx in fxs { + let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone()); + fx.process(&mut [&mut a, &mut b, &mut c]); + let mut a = noise.clone(); + fx.process(&mut [&mut a]); + let (mut a, mut b, mut c) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + fx.process(&mut [&mut a, &mut b, &mut c]); + assert!(b.iter().chain(&c).all(|v| *v == 0.0), "{}: earlier audio came back", fx.id()); + } + } + + /// With Keep Formants on, a channel left out of a short block while its line still holds an + /// impulse passes that impulse to the formant stage, so after it comes back its output matches + /// a channel that was never left out. + #[test] + fn a_short_gap_keeps_the_formant_stage_fed() { + for semitones in [0.0, 5.0] { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("semitones", semitones) && p.set_param("formant_follow", 1.0)); + p.reset(); + let (mut a, mut b) = (vec![0.0f32; 480], vec![0.0f32; 480]); + a[0] = 1.0; + b[0] = 1.0; + p.process(&mut [&mut a, &mut b]); + // The impulse leaves the delay line during samples 480 to 735, while `b` is left out. + let mut a = vec![0.0f32; 256]; + p.process(&mut [&mut a]); + let (mut a, mut b) = (vec![0.0f32; 2_000], vec![0.0f32; 2_000]); + p.process(&mut [&mut a, &mut b]); + assert!(a.iter().any(|v| v.abs() > 0.01), "{semitones}: the impulse never came out"); + assert_eq!(a, b, "{semitones}: the left-out channel lost the impulse"); + } + } + + /// Leaving a silent third channel out of a block does not change the pitch the tracker finds, + /// so a shifted voice comes out the same on the channels that remain. + #[test] + fn a_silent_channel_left_out_keeps_the_tracked_pitch() { + let n = SR as usize; + let (low, high) = (sine(187.5, 0.2, SR as f64, n, 0.0), sine(375.0, 0.24, SR as f64, n, 0.0)); + let left: Vec = low.iter().zip(&high).map(|(a, b)| a + b).collect(); + let right: Vec = low.iter().zip(&high).map(|(a, b)| -a + b).collect(); + let mut out = Vec::new(); + for omit in [false, true] { + let mut p = VoicePitch::new(SR, 3); + assert!(p.set_param("semitones", 5.0)); + p.reset(); + let (mut l, mut r, mut s) = (left.clone(), right.clone(), vec![0.0f32; n]); + if omit { + p.process(&mut [&mut l, &mut r]); + } else { + p.process(&mut [&mut l, &mut r, &mut s]); + } + out.push((l, r)); + } + assert!(out[0] == out[1], "leaving a silent channel out changed the tracked pitch"); + } + + /// The tracker finds a voice's period down to 70 Hz and reports nothing for silence. + #[test] + fn the_tracker_reaches_70_hz() { + for f in [72.0, 110.0, 440.0, 950.0] { + let mut t = Tracker::new(SR, 1); + for v in sine(f, 0.3, SR as f64, SR as usize / 4, 0.0) { + t.push(v, v); + } + let period = t.period.unwrap_or(0.0); + assert!((SR as f64 / period / f - 1.0).abs() < 0.005, "{f} Hz read as {} Hz", SR as f64 / period); + } + let mut t = Tracker::new(SR, 1); + (0..SR as usize / 4).for_each(|_| t.push(0.0, 0.0)); + assert!(t.period.is_none()); + } +} diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs index 59bfaa1741..22270476da 100644 --- a/crates/audio-dsp/src/lib.rs +++ b/crates/audio-dsp/src/lib.rs @@ -171,8 +171,10 @@ pub trait AudioEffect: Send { /// Parameter descriptions (same as the registry entry's). fn params(&self) -> &'static [ParamSpec]; /// Set a parameter by id; the value is clamped to its range. Returns `false` for unknown ids. - /// Takes effect from the next processed sample. Gains, mix amounts and equalizer bands move to - /// the new value smoothly; the crate documentation lists which other parameters change at once. + /// Updates the target immediately. Sample-based effects use the target from the next processed + /// sample. Frame-based effects may apply it at the next frame callback while earlier output + /// remains queued. Gains, mix amounts and equalizer bands move to the new value smoothly; the + /// crate documentation lists which other parameters change at once. fn set_param(&mut self, id: &str, value: f32) -> bool; /// Current (target) value of a parameter. fn param(&self, id: &str) -> Option; @@ -182,7 +184,11 @@ pub trait AudioEffect: Send { /// Process one block in place. All channel slices must have the same length (the shortest /// length is used otherwise). Zero-length blocks are allowed. fn process(&mut self, channels: &mut [&mut [f32]]); - /// Processing latency in samples (look-ahead / STFT delay) for delay compensation. + /// Processing latency in samples (look-ahead / STFT delay) for delay compensation. It does + /// not change with the parameters, except for `voice_pitch`'s `formant_follow` (Keep + /// Formants), which adds the formant stage's latency while it is on. The value changes as + /// soon as the switch changes, while the output crossfades between the two delays over the + /// next 20 ms, so during that fade the output does not match the reported latency. fn latency(&self) -> usize { 0 } @@ -197,7 +203,11 @@ pub trait AudioEffect: Send { None } /// How long the output keeps sounding after the input stops, in samples (reverb and delay - /// tails), so an offline render can run past the end of its input. + /// tails), so an offline render can run past the end of its input. The count starts after + /// the latency: a render that keeps the tail runs `latency() + tail_samples()` samples past + /// the end of its input. An effect whose output decays without reaching zero (a feedback + /// delay, a resonator) reports where the decay falls below a cutoff, 60 dB under its start + /// for the feedback delays and resonators, so quieter output can still follow that point. fn tail_samples(&self) -> usize { 0 } @@ -460,6 +470,37 @@ pub(crate) mod testutil { } } + /// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope), + /// noise bursts (consonants) and pauses. + pub fn speechy(sr: f64, secs: f64, seed: u64) -> Vec { + let n = (sr * secs) as usize; + let mut rng = Rng::new(seed); + let mut out = vec![0.0f32; n]; + let mut i = 0usize; + while i < n { + let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; + let kind = rng.uniform(); + let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); + let glide = 1.0 + 0.3 * rng.uniform() as f64; + let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5); + for k in 0..len.min(n - i) { + let t = k as f64 / sr; + let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; + let v = if kind > 0.3 { + let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); + (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::() + } else if kind > -0.4 { + rng.uniform() + } else { + 0.0 + }; + out[i + k] = v * env * amp; + } + i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize; + } + out + } + pub fn sine(freq: f64, amp: f64, sr: f64, n: usize, phase: f64) -> Vec { (0..n).map(|i| (amp * (2.0 * std::f64::consts::PI * freq * i as f64 / sr + phase).sin()) as f32).collect() } diff --git a/crates/audio-dsp/src/sync.rs b/crates/audio-dsp/src/sync.rs index d117ecba3f..2ea3b75aac 100644 --- a/crates/audio-dsp/src/sync.rs +++ b/crates/audio-dsp/src/sync.rs @@ -354,38 +354,7 @@ pub fn find_offset(a: &[f32], b: &[f32], sample_rate: u32, opts: &SyncOptions) - #[cfg(test)] mod tests { use super::*; - use crate::testutil::Rng; - - /// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope), - /// noise bursts (consonants) and pauses. - fn speechy(sr: f64, secs: f64, seed: u64) -> Vec { - let n = (sr * secs) as usize; - let mut rng = Rng::new(seed); - let mut out = vec![0.0f32; n]; - let mut i = 0usize; - while i < n { - let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; - let kind = rng.uniform(); - let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); - let glide = 1.0 + 0.3 * rng.uniform() as f64; - let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5); - for k in 0..len.min(n - i) { - let t = k as f64 / sr; - let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; - let v = if kind > 0.3 { - let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); - (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::() - } else if kind > -0.4 { - rng.uniform() - } else { - 0.0 - }; - out[i + k] = v * env * amp; - } - i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize; - } - out - } + use crate::testutil::{Rng, speechy}; /// `x` delayed by `delay` samples (fractional: windowed-sinc interpolation), scaled by `gain`, /// optionally colored by a zero-phase low-pass (`[k, 1-2k, k]`, so the delay stays exact), with diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 7981f3a013..100986d8b1 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -24,7 +24,7 @@ decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa- # The symphonia fallback for the formats with no native decoder yet. symphonia = ["decode-native", "dep:symphonia"] # Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders. -# All but Opus are also file formats of `encode` and `FileEncoder`. +# All but Opus are also file formats of `encode` and `FileEncoder`; all are codecs of `PacketEncoder`. encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode", "vorbis-encode"] # Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files. lossless-encode = ["pcm-encode", "flac-encode"] @@ -44,6 +44,8 @@ aac-decode = ["craft-media/bitstream"] # The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`. aac-encode = ["craft-media/bitstream", "craft-media/isobmff"] opus-decode = [] +# SMPTE ST 302M (AES3 audio in MPEG-2 transport streams): packet decoder and encoder. +s302m = [] # ADPCM (`adpcm`): IMA WAV, Microsoft, Yamaha and Flash (SWF) decoders and encoders. adpcm = ["craft-media/bitstream"] # QOA (Quite OK Audio) files: decoder and encoder in the `qoa` module, each on its own. @@ -54,6 +56,7 @@ qoa-encode = [] g722 = [] # ITU-T G.726 ADPCM speech codec (16/24/32/40 kbit/s). g726 = [] +# The Opus encoder (`opus::encoder`), and Opus through `PacketEncoder`. opus-encode = [] # GSM 06.10 full-rate speech: decoder and encoder in the `gsm` module, each on its own. gsm = ["gsm-decode", "gsm-encode"] diff --git a/crates/audio/README.md b/crates/audio/README.md index bd80b54069..3b868392a8 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -31,22 +31,23 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | | `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | -| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | +| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`, `wav_float_header_with_bwf`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | -| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` | +| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` | | `alac-decode` | `alac::Decoder` | none | -| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` | -| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none | +| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A; `PacketEncoder` for ALAC | craft-media `isobmff` | +| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder`; with `opus-encode`, `PacketEncoder` for Opus | none | | `vorbis-encode` | `vorbis::encoder::Encoder` (pure Rust); `encode_ogg_vorbis`, `encode_ogg` and `encode` for Ogg Vorbis files (whole buffer; not `FileEncoder`) | craft-media `ogg` | | `vorbis-decode` | `vorbis::decoder::Decoder` (packets), `vorbis::decoder::decode_ogg` (whole Ogg Vorbis files); native Vorbis I: floors 0 and 1, residues 0 to 2, channel coupling, both block sizes. `decode` still reads Vorbis files through symphonia | craft-media `ogg` | | `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` | -| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` | +| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams; `PacketEncoder` for them | craft-media `bitstream` | | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | | `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` | -| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` | +| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3; `PacketEncoder` for MP3 | craft-media `bitstream` | | `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` | | `adpcm` | `adpcm::{ima, ms, yamaha, swf}`: decoders and encoders for IMA WAV, Microsoft, Yamaha and Flash ADPCM | craft-media `bitstream` | +| `s302m` | `s302m::{decode, Encoder}`: SMPTE ST 302M packets (AES3 audio in MPEG-2 transport streams), 2 to 8 channels of 16, 20 or 24 bits | none | | `gsm-decode`, `gsm-encode` (`gsm`) | `gsm::Decoder`, `gsm::Encoder`, `gsm::decode`, `gsm::encode`: GSM 06.10 full-rate speech, bit-exact, raw `.gsm` and WAV (GSM 6.10) packings | none | | `vmd-decode` | `vmd::Decoder`: Sierra VMD sound (8-bit PCM and 16-bit DPCM), frame by frame from `craft_media::vmd` | none | | `peaks` | `peaks::Peaks` | none | @@ -214,9 +215,13 @@ packet. Opus with empty `extradata` and 1 or 2 channels (RTP, MPEG-TS) needs no To seek: position your demuxer at the packet that starts `preroll()` frames or more before the target, call `reset()`, decode from there, and drop the output before the target. -The codec modules are also usable on their own. `aac::Decoder` and `opus::Decoder` return the -codec's channel order; `aac::wav_order(channel_config)` and `opus::wav_order(channels)` map it to -WAV order. `ac3::Decoder` and `mpa::Decoder` output WAV order. +The codec modules are also usable on their own. `aac::Decoder`, `opus::Decoder` and +`vorbis::decoder::Decoder` return the codec's channel order; `aac::wav_order(channel_config)`, +`opus::wav_order(channels)` and `vorbis::wav_order(channels)` map it to WAV order, and +`vorbis::layout(channels)` gives the speakers of the result. `opus::wav_order` applies only to +mapping family 1. Family 0 is mono or stereo, which is already in WAV order. For other families, +`TrackDecoder` assigns no conventional speaker mapping and leaves channels in stream order. +`ac3::Decoder` and `mpa::Decoder` output WAV order. ### Encode a file @@ -311,12 +316,76 @@ file needs that step before it is written again. An M4A's edit list skips the AAC encoder's priming (1024 frames) and ends at the last frame written, so the file decodes to the length that went in. An MP3, AC-3 or E-AC-3 stream has no -place for that (see [Limits](#limits)). For a container of your own, use the codec modules below. +place for that (see [Limits](#limits)). For a container of your own, use `PacketEncoder` below. + +### Encode packets for your own container + +`PacketEncoder` is the encode-side counterpart of `TrackDecoder`: one interface over the AAC-LC, +ALAC, MP3, AC-3, E-AC-3 and Opus encoders for an app that muxes the audio itself (a video export +to MP4, Matroska or MXF). It returns packets and writes no file; `FileEncoder` writes its coded +formats through it. + +```rust +use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder}; + +let opts = EncodeOptions::new(EncodeFormat::Aac).with_layout(info.layout).with_bitrate(384_000); +let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 6)?; +for block in blocks { // planar f32 in WAV order, any length + for p in enc.encode(&block.channels, block.frames())? { + mux.write(p.pts, p.duration, &p.data)?; // pts and duration in samples at the rate + } +} +for p in enc.finish()? { + mux.write(p.pts, p.duration, &p.data)?; +} +let params = enc.codec_params(); // codec, rate, channels, extradata: what TrackDecoder::new takes +let priming = enc.priming(); // decoded samples before the first input frame +let padding = enc.padding(); // decoded samples after the last one +``` + +It takes the `EncodeOptions` of `FileEncoder` and reads `rate_control`, `layout`, and for ALAC +`bit_depth` and `dither`; `format` is ignored, so `EncodeOptions::default()` with a bit rate will +do for any codec. Input is planar `f32` in WAV channel order. `layout` names the speakers, the +channels are reordered into the codec's order, and ALAC's samples are quantized to the bit depth. +`layout()` reports the speakers the stream carries, in WAV order: the codec's layout for the count +(AAC's 5.1 has side surrounds, ALAC's back surrounds), or the AC-3 coding mode the layout chose. + +| `CodecId` | Feature | Frames per packet | `extradata()` | `priming()` | +|---|---|---|---|---| +| `Aac` (LC) | `aac-encode` | 1024 | `AudioSpecificConfig` | 1024 | +| `Alac` | `alac-encode` | 4096, the last one shorter | `alac` box payload / CodecPrivate | 0 | +| `Mp3` | `mp3-encode` | 1152 (576 below 32 kHz), one frame per packet | empty | 1057 | +| `Ac3`, `Eac3` | `ac3-encode`, `eac3-encode` | 1536 | empty | 256 | +| `Opus` | `opus-encode` | 960 (20 ms) | `OpusHead` | the pre-skip | + +The sample rates, channel counts and layouts are those of the `EncodeFormat` of the same name; +Opus takes 48 kHz mono or stereo at a constant bit rate, 64 kbit/s per channel by default. A codec +with no encoder here, and one whose feature is off, are `Unsupported`; settings a codec cannot take +get the error `EncodeOptions::check` gives for the format. + +Timing: a packet's `pts` is where its decoded audio starts, counted from the first decoded sample, +so input frame `n` is at `n + priming()`. `finish` pads the end with silence until a decoder +returns every input frame, and the durations add up to `priming() + frames() + padding()`. With no +input there are no packets: the durations add up to 0 and `padding()` is 0, while `priming()` still +reports the codec's delay. A muxer +skips the priming (MP4: `TrackConfig::media_start` or an edit list; Matroska: `CodecDelay`; Opus: +the pre-skip, which `OpusHead` already holds) and trims the padding (the end of an MP4 edit, +Matroska's `DiscardPadding`). ALAC's `extradata` records the largest packet and the average bit +rate, so read it after `finish`. `bitrate()` is the constant rate used (`None` for ALAC and AAC by +quality); `bit_depth()` is ALAC's. + +`encode` refuses a block without one slice per channel, or with a slice shorter than `frames`, +and encodes nothing; the encoder stays usable, so the caller can correct the block and call again. +After `finish`, or after encoding itself failed (the block's packets are lost), every call returns +an error. +E-AC-3 7.1 is encoded as 7.1, and this crate's `TrackDecoder` plays its 5.1 substream (see +[Limits](#limits)). ### Encode AAC packets -For an `.m4a` file, use `EncodeFormat::Aac` above. `aac::Encoder` is the packet encoder behind it, -for muxing into a container of your own: +For an `.m4a` file, use `EncodeFormat::Aac` above, and for packets in WAV channel order, +`PacketEncoder`. `aac::Encoder` is the codec's own encoder behind both, with the settings +`EncodeOptions` does not have (bandwidth, TNS, M/S stereo, window shape, ADTS): ```rust use craft_audio::AudioError; @@ -573,7 +642,35 @@ Each codec module's rustdoc lists the coding tools it implements. | MP2 encoder (`mpa::encoder`) | ISO/IEC 11172-3 (§2.4, Annex B and C), 13818-3 | Layer II, constant bit rate, mono or stereo (no joint stereo), 32/44.1/48 kHz at the spec's rate/mode pairs and 16/22.05/24 kHz at 8–160 kbit/s; no CRC | our decoder and ffmpeg decode the frames; SNR of 20–37 dB on tone mixes, and the 481-sample filter delay matches | | MP3 decoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, MPEG-1/2/2.5, 8–48 kHz, every bit rate, CBR and VBR; mono, stereo, dual channel, joint stereo (mid/side and intensity); long, short and mixed blocks; bit reservoir; CRC read, not checked; Xing / Info / VBRI and LAME tags; no free format (read through symphonia) | ffmpeg's float decoder: 127–131 dB SNR on LAME streams of every sampling frequency (CBR, VBR, CRC, no reservoir, transients with short blocks) and on this crate's encoder's; intensity stereo and mixed blocks through LAME frames edited to use them (112–131 dB) | | MP3 encoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, constant bit rate: 32–320 kbit/s at 32/44.1/48 kHz, 8–160 kbit/s at 16/22.05/24 kHz; mono, stereo, joint stereo (mid/side); bit reservoir; long blocks only; no Xing/Info tag, VBR, CRC or free format | ffmpeg decodes every Huffman code as intended; full encodes at every sampling frequency checked with ffprobe and by SNR of ffmpeg's decode | -| ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder, same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | +| ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder (except 24- and 32-bit packets quiet enough to shift off fewer low bytes, such as silence), same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | + +### ALAC encoding + +Apple's reference encoder stores the low byte (24-bit) or low two bytes (32-bit) of every sample +uncompressed. This encoder shifts off fewer bytes, per element and per packet, when the samples +allow it: at 24 bits a packet that peaks below −54 dBFS keeps no uncompressed byte; at 32 bits one +below −54 dBFS keeps one, and a mono or LFE element below −102 dBFS none (a 32-bit pair always keeps +one). Other packets are the same as the reference's, and decoders need no change. + +Stream sizes in MB (10⁶ bytes) for 4 minutes at 48 kHz in 4096-frame packets. "Reference" is this +encoder with the reference's fixed shift; Apple's `afconvert` gives the same sizes for the 24-bit stereo rows. The +music is synthetic (decaying harmonic notes over a noise floor, peaking at −3 dBFS); a stem plays +5 or 10 seconds in every 20. + +| Material | Depth / ch | PCM | Reference | This encoder | Saved | +|---|---|---|---|---|---| +| Music throughout | 24 / 2 | 69.1 | 45.5 | 45.5 | 0% | +| Music, 2 s of digital silence at each end | 24 / 2 | 69.1 | 45.1 | 44.7 | 0.8% | +| Stem playing half the time, digital silence between | 24 / 2 | 69.1 | 34.3 | 22.8 | 33% | +| Stem playing a quarter of the time, digital silence between | 24 / 2 | 69.1 | 28.7 | 11.5 | 60% | +| The same, noise at −110 dBFS in place of silence | 24 / 2 | 69.1 | 32.6 | 25.1 | 23% | +| Quiet music, peaking at −60 dBFS | 24 / 2 | 69.1 | 27.7 | 20.1 | 27% | +| Digital silence | 24 / 2 | 69.1 | 23.1 | 0.09 | 99.6% | +| 5.1: music in front, surrounds a quarter of the time, silent LFE | 24 / 6 | 207.4 | 108.7 | 79.9 | 26% | +| Stem playing a quarter of the time, digital silence between | 32 / 1 | 46.1 | 25.9 | 8.7 | 66% | +| Stem playing a quarter of the time, digital silence between | 32 / 2 | 92.2 | 51.7 | 34.5 | 33% | +| Quiet music, peaking at −60 dBFS | 32 / 2 | 92.2 | 50.7 | 43.2 | 15% | +| Digital silence | 32 / 2 | 92.2 | 46.2 | 23.1 | 50% | ### MP3 encoding diff --git a/crates/audio/src/alac/encoder.rs b/crates/audio/src/alac/encoder.rs index 7fc842597b..e4211dc5b1 100644 --- a/crates/audio/src/alac/encoder.rs +++ b/crates/audio/src/alac/encoder.rs @@ -8,7 +8,11 @@ //! //! The search (stereo matrixing, 4 or 8 predictor coefficients) and the state kept across //! packets (coefficients, the last matrixing, and the buffers the trial runs read stale parts of) -//! follow the reference, so for the same input this writes the same packets as it. +//! follow the reference, so for the same input this writes the same packets as it, with one +//! exception: the shifted-off low bytes. The reference passes 1 (24-bit) or 2 (32-bit) low bytes +//! of every sample through uncompressed, even for silence. Here an element shifts off fewer bytes +//! in a packet whose samples fit well within the width the reference predicts (see +//! [`packet_shift`]), so silence and quiet passages are not padded with a byte or two per sample. use super::ag::{self, AgParams}; use super::bits::{BitCounter, BitSink, BitWriter}; @@ -100,6 +104,25 @@ fn bytes_shifted(bit_depth: u32) -> u32 { } } +/// The bytes an element shifts off in one packet: the fewest, down from the reference's +/// [`bytes_shifted`], that leave every sample at least one bit narrower than the width the +/// reference predicts (`bit_depth − 8 · bytes_shifted`). The predictor then works on values no +/// wider than in the reference, so its arithmetic stays in the same range; only fewer low bytes go +/// out uncompressed. The spare bit is there because at the full width, coding the low byte through +/// the predictor costs about as much as storing it, and for 24-bit mono measured 2% more. +/// A 32-bit pair keeps at least 1: with none, its prediction width (33 bits) exceeds the 32 the +/// format allows. +fn packet_shift(bit_depth: u32, channels: &[&[i32]]) -> u32 { + let reference = bytes_shifted(bit_depth); + let width = bit_depth - reference * 8 - 1; + let floor = u32::from(bit_depth == 32 && channels.len() == 2); + let fits = |bytes: u32| { + let (lo, hi) = (-(1i64 << (width - 1)), (1i64 << (width - 1)) - 1); + channels.iter().flat_map(|c| c.iter()).all(|&x| (lo..=hi).contains(&i64::from(x >> (bytes * 8)))) + }; + (floor..reference).find(|&b| fits(b)).unwrap_or(reference) +} + impl Encoder { /// An encoder for `cfg`. pub fn new(cfg: EncoderConfig) -> Result { @@ -191,11 +214,12 @@ impl Encoder { w.put(cpe_tag, 4); cpe_tag += 1; let (l, r) = (channels[index], channels[index + 1]); + let bs = packet_shift(self.bit_depth, &[l, r]); // as in the reference, fast mode applies to stereo streams only if self.cfg.fast && channels.len() == 2 { - self.encode_stereo_fast(&mut w, index, l, r)?; + self.encode_stereo_fast(&mut w, index, l, r, bs)?; } else { - self.encode_stereo(&mut w, index, l, r)?; + self.encode_stereo(&mut w, index, l, r, bs)?; } index += 2; } @@ -203,7 +227,8 @@ impl Encoder { let tag = if element == ID_LFE { &mut lfe_tag } else { &mut sce_tag }; w.put(*tag, 4); *tag += 1; - self.encode_mono(&mut w, index, channels[index])?; + let bs = packet_shift(self.bit_depth, &[channels[index]]); + self.encode_mono(&mut w, index, channels[index], bs)?; index += 1; } } @@ -231,10 +256,10 @@ impl Encoder { } /// `EncodeStereo`: a channel pair with the matrixing and coefficient search. - fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> { + /// `bs`: the bytes shifted off, from [`packet_shift`]. + fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = l.len(); - let bs = bytes_shifted(self.bit_depth); let chan_bits = self.bit_depth - bs * 8 + 1; let partial = self.partial(n); let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0); @@ -329,10 +354,9 @@ impl Encoder { } /// `EncodeStereoFast`: a channel pair without matrixing or search. - fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> { + fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = l.len(); - let bs = bytes_shifted(self.bit_depth); let chan_bits = self.bit_depth - bs * 8 + 1; let partial = self.partial(n); let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0); @@ -396,10 +420,9 @@ impl Encoder { } /// `EncodeMono`: one channel (SCE or LFE). - fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32]) -> Result<()> { + fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = input.len(); - let bs = bytes_shifted(self.bit_depth); let shift = bs * 8; let chan_bits = self.bit_depth - shift; let partial = self.partial(n); @@ -563,4 +586,84 @@ mod tests { let mut dec = Decoder::new(&enc.cookie()).unwrap(); assert_eq!(dec.decode(&p).unwrap(), vec![noise[..4096].to_vec()]); } + + /// One packet of `frames` frames per element, encoded and decoded back; its size in bytes. + fn packet_bytes(cfg: EncoderConfig, input: &[Vec]) -> usize { + let mut enc = Encoder::new(cfg).unwrap(); + let chunk: Vec<&[i32]> = input.iter().map(Vec::as_slice).collect(); + let p = enc.encode(&chunk).unwrap(); + let mut dec = Decoder::new(&enc.cookie()).unwrap(); + assert_eq!(dec.decode(&p).unwrap(), input, "{cfg:?}"); + p.len() + } + + /// The reference shifts 1 (24-bit) or 2 (32-bit) low bytes of every sample off and stores them + /// uncompressed, so a 4096-frame stereo packet of 24-bit silence was 8224 bytes (#1368). + #[test] + fn silence_is_a_few_bytes_at_every_depth() { + for bits in [16, 20, 24, 32] { + for ch in [1, 2, 6] { + for fast in [false, true] { + let cfg = EncoderConfig::new(48_000, ch, bits).with_fast(fast); + let bytes = packet_bytes(cfg, &vec![vec![0; 4096]; usize::from(ch)]); + // a 32-bit pair keeps one shifted byte per sample: the format allows no less + let floor = if bits == 32 { 4096 * 2 * (usize::from(ch) / 2) } else { 0 }; + assert!(bytes <= floor + 40 * usize::from(ch), "{bits} bits, {ch} ch, fast {fast}: {bytes} bytes"); + } + } + } + } + + /// Quiet audio (within 12 bits) at 24 and 32 bits shifts nothing off and comes within 10% of + /// the same audio at 16 bits (the wider prediction width makes the coder's escapes longer); + /// the reference stored a byte or two more per sample. Samples at the edges of each width and + /// loud audio decode exactly. + #[test] + fn quiet_packets_compress_like_16_bit_audio_and_loud_ones_round_trip() { + let quiet = signal(4096, 2, 12); + let at16 = packet_bytes(EncoderConfig::new(48_000, 2, 16), &quiet); + let at24 = packet_bytes(EncoderConfig::new(48_000, 2, 24), &quiet); + assert!(at24 * 10 <= at16 * 11, "24-bit {at24} bytes, 16-bit {at16}"); + let mono = vec![quiet[0].clone()]; + let at16 = packet_bytes(EncoderConfig::new(48_000, 1, 16), &mono); + let at32 = packet_bytes(EncoderConfig::new(48_000, 1, 32), &mono); + assert!(at32 * 10 <= at16 * 11, "32-bit mono {at32} bytes, 16-bit {at16}"); + // the samples just past each narrower width, and loud audio, decode exactly + for bits in [24u32, 32] { + for ch in [1u8, 2] { + let edge: Vec> = (0..ch) + .map(|c| { + (0..4096) + .map(|i| match (i + usize::from(c)) % 4 { + 0 => (16_384 << (bits - 24)) - 1, + 1 => -(16_384 << (bits - 24)), + 2 => 16_384 << (bits - 24), + _ => -(16_384 << (bits - 24)) - 1, + }) + .collect() + }) + .collect(); + packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &edge); + packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &signal(4096, usize::from(ch), bits)); + } + } + } + + #[test] + fn the_shift_is_the_fewest_bytes_that_keep_the_reference_width() { + let z = [0i32; 4]; + assert_eq!(packet_shift(16, &[&z]), 0); + assert_eq!(packet_shift(24, &[&z, &z]), 0); + assert_eq!(packet_shift(24, &[&[16_383, -16_384], &z]), 0); + assert_eq!(packet_shift(24, &[&[16_384], &z]), 1); + assert_eq!(packet_shift(24, &[&[-16_385]]), 1); + assert_eq!(packet_shift(24, &[&[32_767]]), 1); + assert_eq!(packet_shift(32, &[&z]), 0); + assert_eq!(packet_shift(32, &[&[16_383]]), 0); + assert_eq!(packet_shift(32, &[&z, &z]), 1); + assert_eq!(packet_shift(32, &[&[1 << 21]]), 1); + assert_eq!(packet_shift(32, &[&[1 << 22]]), 2); + assert_eq!(packet_shift(32, &[&[i32::MIN]]), 2); + assert_eq!(packet_shift(32, &[&[i32::MAX], &z]), 2); + } } diff --git a/crates/audio/src/alac/mod.rs b/crates/audio/src/alac/mod.rs index 14bbbf6c50..d580fd9c28 100644 --- a/crates/audio/src/alac/mod.rs +++ b/crates/audio/src/alac/mod.rs @@ -23,7 +23,9 @@ //! reference: hostile input returns errors instead of reading or writing out of bounds, integer //! arithmetic wraps where C would overflow, the 4- and 8-tap predictor loops are folded into the //! general one (same values), the sample-width variants of the matrix routines into one routine -//! over `i32`, and the encoder fills in the cookie's average bit rate. +//! over `i32`, the encoder fills in the cookie's average bit rate, and it shifts off fewer low +//! bytes in packets whose samples fit a narrower width (silence and quiet passages at 24 and 32 +//! bits), where the reference always passes them through uncompressed. // The bit I/O, coder, predictor and matrix modules serve both halves; with only one of // `alac-decode` and `alac-encode` built, the other half's routines are unused. diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 29054288ec..6cc18ab901 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -19,10 +19,13 @@ //! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar //! `f32` in WAV channel order. //! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also -//! gives [`wav_float_header`]), FLAC (feature `flac-encode`), AAC-LC and ALAC in M4A -//! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`, -//! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature +//! gives [`wav_float_header`] and [`wav_float_header_with_bwf`]), FLAC (feature `flac-encode`), +//! AAC-LC and ALAC in M4A (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams +//! (`mp3-encode`, `ac3-encode`, `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature //! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder. +//! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`, +//! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC, +//! MP3, AC-3, E-AC-3 or Opus, with their timing and codec configuration, for an app's own muxer. //! - [`wav_pcm`], [`aiff_pcm`] (feature `decode-native`) and [`pcm_wav_file`], [`pcm_wav_header`], //! [`pcm_aiff_file`], [`pcm_aiff_header`] (feature `pcm-encode`): the integer PCM of a WAV or AIFF //! file bit for bit, and minimal files around such PCM, for essence embedded in other containers. @@ -32,7 +35,8 @@ //! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`] //! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder; //! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), [`adpcm`] -//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`dsd`] (`dsd`: DSF and DSDIFF files to PCM), +//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`s302m`] (`s302m`: SMPTE 302M packets), +//! [`dsd`] (`dsd`: DSF and DSDIFF files to PCM), //! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech), [`vmd`] (`vmd-decode`: //! Sierra VMD sound). //! @@ -64,6 +68,15 @@ pub mod mp3; pub mod mpa; #[cfg(any(feature = "opus-decode", feature = "opus-encode"))] pub mod opus; +#[cfg(any( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" +))] +mod packet; #[cfg(any( feature = "aac-decode", feature = "alac-decode", @@ -79,6 +92,8 @@ pub mod peaks; pub mod qoa; #[cfg(feature = "decode-native")] mod read; +#[cfg(feature = "s302m")] +pub mod s302m; #[cfg(feature = "sbc")] pub mod sbc; #[cfg(any( @@ -157,6 +172,15 @@ pub use buffer::AudioBuffer; pub use craft_media; pub use craft_media::{ByteSource, CodecId, CodecParams, Container, PcmFormat, ReadSeekSource}; pub use layout::{ChannelLayout, Speaker}; +#[cfg(any( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" +))] +pub use packet::{EncodedPacket, PacketEncoder}; #[cfg(feature = "decode-native")] pub use read::SharedSource; #[cfg(feature = "decode-native")] @@ -185,8 +209,6 @@ pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; feature = "eac3-encode" ))] pub use write::FileEncoder; -#[cfg(feature = "pcm-encode")] -pub use write::wav_float_header; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -200,6 +222,8 @@ pub use write::wav_float_header; pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; +#[cfg(feature = "pcm-encode")] +pub use write::{wav_float_header, wav_float_header_with_bwf}; /// Errors from probing, decoding and encoding. #[non_exhaustive] diff --git a/crates/audio/src/packet.rs b/crates/audio/src/packet.rs new file mode 100644 index 0000000000..2d1ab7d621 --- /dev/null +++ b/crates/audio/src/packet.rs @@ -0,0 +1,696 @@ +//! [`PacketEncoder`]: one interface over the AAC-LC, ALAC, MP3, AC-3, E-AC-3 and Opus encoders, for +//! a caller that puts the packets in its own container. It takes planar `f32` in WAV channel order, +//! maps the channels onto the codec's order, and returns packets with their timing; the coded +//! formats of [`FileEncoder`](crate::FileEncoder) are written through it. + +// Each codec is its own feature: with only some of them built, the other halves of the shared +// code are unused. +#![cfg_attr( + not(all( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" + )), + allow(dead_code, unused_imports, unused_variables, unused_mut) +)] + +use crate::layout::channel_map; +use crate::{AudioError, ChannelLayout, CodecId, CodecParams, EncodeFormat, EncodeOptions, RateControl, Result}; + +/// Maximum frames handed to a codec per internal call, bounding that call's input and output. +/// `PacketEncoder::encode` collects packets across all chunks, so its returned vector grows with +/// the caller's input block. Also the frames of an ALAC packet. +pub(crate) const CHUNK: usize = 4096; + +/// Bits per second per channel when no rate is asked for: AAC and Opus. +const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; +const OPUS_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; +/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per +/// full-bandwidth channel). +const DEFAULT_KBPS_PER_CHANNEL: u32 = 96; + +/// Opus's layouts by channel count: RFC 7845 mapping family 0 (mono, and stereo as L R). +const OPUS_LAYOUT_MASKS: [&[u32]; 2] = [&[0x4], &[0x3]]; + +/// One packet from a [`PacketEncoder`]. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EncodedPacket { + /// The coded bytes: an AAC raw data block (no ADTS header), an ALAC packet, one MP3 frame, + /// one AC-3 syncframe or an E-AC-3 access unit, one Opus packet. + pub data: Vec, + /// Where the packet's decoded audio starts, in samples at the sample rate from the first + /// decoded sample of the stream. The encoder's [priming](PacketEncoder::priming) comes first, + /// so input frame `n` is at `n + priming`. + pub pts: u64, + /// The samples per channel the packet decodes to, the last packet's padding included. + pub duration: u32, +} + +/// Encodes audio to packets of one codec, for a muxer of the caller's own: the encode-side +/// counterpart of [`TrackDecoder`](crate::TrackDecoder). Built from a [`CodecId`] and the +/// [`EncodeOptions`] of [`FileEncoder`](crate::FileEncoder), of which it reads the rate control, +/// the layout, and for ALAC the bit depth and dither. +/// +/// Input is planar `f32` in WAV channel order, one slice per channel, at any block size; packets +/// come out as they are completed, and [`finish`](Self::finish) returns the rest. What a container +/// needs to describe the track is on the encoder: [`codec_params`](Self::codec_params) (codec, +/// rate, channels and [`extradata`](Self::extradata)), [`layout`](Self::layout), +/// [`priming`](Self::priming), and after `finish` [`padding`](Self::padding). +/// +/// | Codec | Feature | Packet | `extradata` | Priming | +/// |---|---|---|---|---| +/// | [`CodecId::Aac`] (LC) | `aac-encode` | 1024 frames | `AudioSpecificConfig` | 1024 | +/// | [`CodecId::Alac`] | `alac-encode` | 4096 frames | the `alac` box / CodecPrivate | 0 | +/// | [`CodecId::Mp3`] | `mp3-encode` | 1152 frames (576 below 32 kHz) | none | 1057 | +/// | [`CodecId::Ac3`], [`CodecId::Eac3`] | `ac3-encode`, `eac3-encode` | 1536 frames | none | 256 | +/// | [`CodecId::Opus`] | `opus-encode` | 960 frames (20 ms) | `OpusHead` | the pre-skip | +/// +/// ``` +/// # #[cfg(all(feature = "aac-encode", feature = "aac-decode"))] { +/// use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder, TrackDecoder}; +/// +/// let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128_000); +/// let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 2)?; +/// let block = [vec![0.25f32; 4800], vec![-0.25f32; 4800]]; // 0.1 s, one Vec per channel +/// let mut packets = enc.encode(&block, 4800)?; +/// packets.extend(enc.finish()?); +/// assert_eq!(enc.priming(), 1024); +/// assert_eq!(packets.iter().map(|p| u64::from(p.duration)).sum::(), 1024 + 4800 + enc.padding()); +/// +/// // The description a muxer writes is what a decoder reads. +/// let mut dec = TrackDecoder::new(&enc.codec_params(), &[])?; +/// assert_eq!(dec.decode(&packets[0].data)?.frames(), 1024); +/// # } +/// # Ok::<(), craft_audio::AudioError>(()) +/// ``` +pub struct PacketEncoder { + codec: CodecId, + inner: Inner, + sample_rate: u32, + /// The speakers of the channels encoded, in WAV order. + layout: ChannelLayout, + /// For each codec channel, the caller's channel that feeds it. + map: Vec, + bitrate: Option, + /// The integer depth of a lossless codec. + bit_depth: Option, + /// Where the next packet starts. + pts: u64, + /// Frames of input taken. + frames: u64, + finished: bool, + /// Set when a call failed: the packets of that block are lost, so the stream has a gap and + /// every later call is refused. + failed: bool, +} + +impl std::fmt::Debug for PacketEncoder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PacketEncoder") + .field("codec", &self.codec) + .field("sample_rate", &self.sample_rate) + .field("layout", &self.layout) + .field("frames", &self.frames) + .finish_non_exhaustive() + } +} + +/// A packet encoder of one of the codecs, taking planar `f32` in its own channel order. +enum Inner { + #[cfg(feature = "aac-encode")] + Aac(Box), + #[cfg(feature = "alac-encode")] + Alac { + enc: Box, + quantizers: Vec, + /// Quantized samples of the packet being filled, per channel. + pending: Vec>, + }, + #[cfg(feature = "mp3-encode")] + Mp3 { + enc: Box, + /// Bytes the encoder returned that do not yet make a whole frame. + bytes: Vec, + }, + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Ac3 { + enc: Box, + /// The block with every sample finite and within ±1, as the encoder requires. + planes: Vec>, + }, + #[cfg(feature = "opus-encode")] + Opus { + enc: Box, + /// Interleaved samples of the frame being filled. + pending: Vec, + /// Frames of the decoded stream the packets so far cover. + coded: u64, + }, +} + +/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`. +fn labels(mask: u32) -> String { + ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::>().join(" ") +} + +/// The speakers of the caller's layout, for an error message. +fn given(layout: &ChannelLayout) -> String { + layout.mask().map_or_else(|| "without speaker assignment".into(), labels) +} + +/// [`channel_map`] for a codec with one layout per channel count (the first of `masks`), and +/// that layout; or why the audio does not fit. +fn fixed_map(masks: &[u32], name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result<(Vec, ChannelLayout)> { + let Some(&mask) = masks.first() else { + return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels()))); + }; + let map = channel_map(mask, order, layout).ok_or_else(|| { + AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout))) + })?; + Ok((map, ChannelLayout::from_mask(mask))) +} + +/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for +/// 8 channels configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc. +#[cfg(feature = "aac-encode")] +pub(super) fn aac_order(channels: usize) -> Option<&'static [usize]> { + if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) } +} + +/// The lowest AAC bit rate used, per channel: 6 kbit/s, and a quarter of the sample rate (256 +/// bits a frame). The encoder accepts less, and from about half of this down codes silence; a +/// stream of silence is no answer to a low bit rate (or to kbit/s given as bit/s). +#[cfg(feature = "aac-encode")] +fn aac_floor_per_channel(sample_rate: u32) -> u32 { + (sample_rate / 4).max(6000) +} + +/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a +/// quality of 0–1 spans the encoder's VBR range. +#[cfg(feature = "aac-encode")] +pub(super) fn aac_mode(rate: Option, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode { + use crate::aac::BitrateMode; + let (lo, hi) = crate::aac::cbr_range(sample_rate, channels); + let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo)); + // An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone. + let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps }; + match rate { + None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))), + Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)), + // NaN stays NaN, which the encoder refuses. + Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)), + } +} + +/// The bit rate in bits per second for a codec with constant bit rates only. +fn constant_bps(name: &str, rate: Option, default: u32) -> Result { + match rate { + None => Ok(default), + Some(RateControl::Bitrate(bps)) => Ok(bps), + Some(RateControl::Quality(_)) => { + Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality"))) + } + } +} + +/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding +/// mode whose speakers the layout names, at the nearest bit rate the stream can carry. +#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] +pub(super) fn ac3_config( + codec: crate::ac3::encoder::Codec, + sample_rate: u32, + layout: &ChannelLayout, + rate: Option, +) -> Result<(crate::ac3::encoder::Config, Vec)> { + use crate::ac3::encoder::{Codec, CodingMode, Config}; + use CodingMode::*; + let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" }; + let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; + let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| { + // 7.1 is an E-AC-3 programme with an LFE; the encoder has no other. + if mode == Surround71 && (codec != Codec::Eac3 || !lfe) { + return None; + } + let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe }; + let map = channel_map(config.channel_layout().mask()?, None, layout)?; + Some((config, map)) + }); + let Some((mut config, map)) = found else { + return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout)))); + }; + let full = config.mode.channels() as u32; + let want = constant_bps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full * 1000)? / 1000; + // What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of + // the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold. + let least = if config.mode == Surround71 { 384 } else { 32 * full }; + config.bitrate_kbps = match codec { + Codec::Ac3 => { + let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least); + crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor) + } + Codec::Eac3 => { + let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 }; + want.clamp(least, most.max(least)) + } + }; + Ok((config, map)) +} + +/// The feature a codec's encoder is built with, or `None` for a codec with no encoder here. +fn feature(codec: CodecId) -> Option<&'static str> { + Some(match codec { + CodecId::Aac => "aac-encode", + CodecId::Alac => "alac-encode", + CodecId::Mp3 => "mp3-encode", + CodecId::Ac3 => "ac3-encode", + CodecId::Eac3 => "eac3-encode", + CodecId::Opus => "opus-encode", + _ => return None, + }) +} + +impl PacketEncoder { + /// An encoder of `codec` for `channels` channels at `sample_rate`. Of `opts` it reads + /// `rate_control` and `layout` (as [`FileEncoder`](crate::FileEncoder) does: the speakers of + /// the caller's channels, mapped onto the codec's layout), and for ALAC `bit_depth` and + /// `dither`; `format`, `bwf` and `force_rf64` are for files and ignored. + /// + /// Opus takes 48 kHz mono or stereo at a constant bit rate (64 kbit/s per channel when none + /// is asked for); the others take what their [`EncodeFormat`] lists. A codec this crate has + /// no encoder for, and one whose feature is not built, are [`AudioError::Unsupported`]. A + /// rate, channel count, layout or rate control the codec cannot take is refused with the error + /// [`EncodeOptions::check`] gives for the format (`Unsupported` for a layout or rate control). + pub fn new(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, channels: u16) -> Result { + let Some(feature) = feature(codec) else { + return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))); + }; + let built = [ + (CodecId::Aac, cfg!(feature = "aac-encode")), + (CodecId::Alac, cfg!(feature = "alac-encode")), + (CodecId::Mp3, cfg!(feature = "mp3-encode")), + (CodecId::Ac3, cfg!(feature = "ac3-encode")), + (CodecId::Eac3, cfg!(feature = "eac3-encode")), + (CodecId::Opus, cfg!(feature = "opus-encode")), + ]; + if !built.contains(&(codec, true)) { + return Err(AudioError::Unsupported(format!("encoding {} needs the `{feature}` feature", codec.name()))); + } + let n = usize::from(channels); + // As the file writers word it. + if channels == 0 { + return Err(AudioError::Encode("buffer has no channels".into())); + } + if sample_rate == 0 { + return Err(AudioError::Encode("sample rate is 0".into())); + } + if let Some(layout) = &opts.layout + && layout.channels() != channels + { + return Err(AudioError::Encode(format!("a {}-channel layout for {channels} channels", layout.channels()))); + } + let given = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels)); + let (inner, map, layout, bitrate, bit_depth) = match codec { + #[cfg(feature = "aac-encode")] + CodecId::Aac => { + let (map, layout) = fixed_map(EncodeFormat::Aac.layout_masks(channels), "AAC", aac_order(n), &given)?; + let mode = aac_mode(opts.rate_control, sample_rate, n); + let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, n, 0) }; + let bitrate = match mode { + crate::aac::BitrateMode::Cbr(bps) => Some(bps), + crate::aac::BitrateMode::Vbr(_) => None, + }; + (Inner::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, layout, bitrate, None) + } + #[cfg(feature = "alac-encode")] + CodecId::Alac => { + let count = u8::try_from(channels).unwrap_or(u8::MAX); + let (map, layout) = fixed_map(EncodeFormat::Alac.layout_masks(channels), "ALAC", crate::alac::alac_order(count), &given)?; + let bits = match opts.bit_depth { + crate::BitDepth::Int16 => 16, + crate::BitDepth::Int24 => 24, + crate::BitDepth::Int32 => 32, + crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())), + }; + let config = crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32); + let enc = crate::alac::Encoder::new(config)?; + let quantizers = crate::write::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, n); + (Inner::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); n] }, map, layout, None, Some(bits)) + } + #[cfg(feature = "mp3-encode")] + CodecId::Mp3 => { + let (map, layout) = fixed_map(EncodeFormat::Mp3.layout_masks(channels), "MP3", None, &given)?; + let want = constant_bps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * u32::from(channels) * 1000)? / 1000; + // A sample rate MP3 has not is the encoder's to refuse. + let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want); + let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, n, kbps))?; + (Inner::Mp3 { enc: Box::new(enc), bytes: Vec::new() }, map, layout, Some(kbps.saturating_mul(1000)), None) + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + CodecId::Ac3 | CodecId::Eac3 => { + let which = if codec == CodecId::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 }; + let (config, map) = ac3_config(which, sample_rate, &given, opts.rate_control)?; + let enc = crate::ac3::encoder::Encoder::new(config)?; + let layout = enc.channel_layout(); + let bitrate = Some(config.bitrate_kbps.saturating_mul(1000)); + (Inner::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); n] }, map, layout, bitrate, None) + } + #[cfg(feature = "opus-encode")] + CodecId::Opus => { + let masks = n.checked_sub(1).and_then(|i| OPUS_LAYOUT_MASKS.get(i)).copied().unwrap_or_default(); + let (map, layout) = fixed_map(masks, "Opus", None, &given)?; + if sample_rate != 48_000 { + return Err(AudioError::Unsupported(format!("Opus is encoded at 48000 Hz, not {sample_rate} Hz"))); + } + let bps = constant_bps("Opus", opts.rate_control, OPUS_DEFAULT_BPS_PER_CHANNEL * u32::from(channels))?; + let enc = crate::opus::encoder::Encoder::new(channels as u8, bps)?; + let bitrate = Some(enc.bitrate()); + (Inner::Opus { enc: Box::new(enc), pending: Vec::new(), coded: 0 }, map, layout, bitrate, None) + } + #[allow(unreachable_patterns)] + _ => return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))), + }; + Ok(PacketEncoder { codec, inner, sample_rate, layout, map, bitrate, bit_depth, pts: 0, frames: 0, finished: false, failed: false }) + } + + /// The codec of the packets. + pub fn codec(&self) -> CodecId { + self.codec + } + + /// The sample rate of the audio and of the packets' timing. + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + /// The number of channels. + pub fn channels(&self) -> u16 { + self.layout.channels() + } + + /// The speakers of the channels encoded, in WAV order: the codec's layout for the channel + /// count (for AC-3 and E-AC-3, the coding mode's), which is what a decoder reports. Where the + /// codec has one surround pair, it is the codec's (AAC's 5.1 has side surrounds, ALAC's back + /// ones), whichever pair the caller's layout named. + pub fn layout(&self) -> ChannelLayout { + self.layout + } + + /// The constant bit rate in bits per second for all channels together, as + /// [`RateControl::Bitrate`] describes the rate the stream settles on; `None` for ALAC and + /// for AAC at a constant quality. + pub fn bitrate(&self) -> Option { + self.bitrate + } + + /// The bits per sample of a lossless codec (ALAC), `None` for the lossy ones. + pub fn bit_depth(&self) -> Option { + self.bit_depth + } + + /// The codec configuration a container stores: AAC's `AudioSpecificConfig` (MP4 `esds` + /// decoder-specific info, Matroska CodecPrivate), ALAC's configuration as MP4's `alac` box + /// and Matroska's CodecPrivate hold it, Opus's `OpusHead`; empty for MP3, AC-3 and E-AC-3. + /// ALAC's records the largest packet and the average bit rate so far, so read it after + /// [`finish`](Self::finish). + pub fn extradata(&self) -> Vec { + match &self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => enc.audio_specific_config(), + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, .. } => enc.cookie(), + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, .. } => enc.opus_head(), + #[allow(unreachable_patterns)] + _ => Vec::new(), + } + } + + /// The codec, sample rate, channels and [`extradata`](Self::extradata): the description + /// [`TrackDecoder::new`](crate::TrackDecoder::new) takes, and what a muxer's track needs. + pub fn codec_params(&self) -> CodecParams { + CodecParams::new(self.codec).with_sample_rate(self.sample_rate).with_channels(self.channels()).with_extradata(self.extradata()) + } + + /// Decoded samples before the first input frame: the encoder's delay, which a container + /// skips (an MP4 edit list's media time, Matroska's CodecDelay, Opus's pre-skip, which + /// `OpusHead` already holds). 0 for ALAC. + /// + /// This is the codec's delay and does not depend on the input. An encoder that is given no + /// input returns no packets, and this still reports the delay. + pub fn priming(&self) -> u32 { + match &self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => enc.priming_samples(), + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, .. } => enc.delay(), + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, .. } => enc.priming_samples(), + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, .. } => u32::from(enc.pre_skip()), + #[allow(unreachable_patterns)] + _ => 0, + } + } + + /// Frames of input taken so far. + pub fn frames(&self) -> u64 { + self.frames + } + + /// Decoded samples after the last input frame, which a container trims (the end of an MP4 + /// edit, Matroska's DiscardPadding): the packets' durations add up to + /// [`priming`](Self::priming) + [`frames`](Self::frames) + this. Complete after + /// [`finish`](Self::finish). + /// + /// The sum holds once there is input. With none, [`finish`](Self::finish) returns no packets, + /// so the durations add up to 0 and this is 0, while `priming` is still the codec's delay: a + /// muxer writes an empty track and has no priming to skip. + pub fn padding(&self) -> u64 { + self.pts.saturating_sub(u64::from(self.priming()).saturating_add(self.frames)) + } + + /// Encodes the first `frames` frames of `block`, one slice per channel in WAV order + /// (`&[Vec]`, `&[&[f32]]`, …), and returns the packets completed. Samples are full scale + /// at ±1; NaN is taken as 0, and what a codec cannot carry above full scale is clipped. + /// + /// Internal codec calls process at most 4096 frames at a time, but this method collects their + /// packets in one returned vector whose memory use grows with `frames`. For streaming with + /// bounded memory, pass bounded input blocks and consume each returned batch before encoding + /// the next block, as [`FileEncoder`](crate::FileEncoder) does for coded formats. + /// + /// `block` must have one slice per channel, each at least `frames` long; otherwise nothing is + /// encoded and the error is [`AudioError::Encode`]. A call after [`finish`](Self::finish) is + /// an error too. When encoding itself fails, the packets of the block are lost, and every + /// later call fails rather than return a stream with a gap. + pub fn encode>(&mut self, block: &[C], frames: usize) -> Result> { + self.usable()?; + let channels = usize::from(self.channels()); + if block.len() != channels { + return Err(AudioError::Encode(format!("a block of {} channels for a {channels}-channel stream", block.len()))); + } + if let Some(short) = block.iter().map(|c| c.as_ref().len()).filter(|&n| n < frames).min() { + return Err(AudioError::Encode(format!("{frames} frames asked for, but a channel holds {short}"))); + } + let mut out = Vec::new(); + for at in (0..frames).step_by(CHUNK) { + let end = frames.min(at + CHUNK); + let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect(); + if let Err(e) = self.push(&planes, &mut out) { + self.failed = true; + return Err(e); + } + self.frames = self.frames.saturating_add((end - at) as u64); + } + Ok(out) + } + + /// Encodes what the encoder still holds, padded with silence to whole packets and as far as + /// a decoder needs to return every input frame after the priming, and returns the last + /// packets. Later calls of [`encode`](Self::encode) and `finish` are errors; the description + /// ([`extradata`](Self::extradata), [`padding`](Self::padding)) stays readable. + pub fn finish(&mut self) -> Result> { + self.usable()?; + self.finished = true; + let mut out = Vec::new(); + let done = self.drain(&mut out); + if done.is_err() { + self.failed = true; + } + done.map(|()| out) + } + + fn usable(&self) -> Result<()> { + if self.failed { + Err(AudioError::Encode("the packet encoder already failed; its stream is incomplete".into())) + } else if self.finished { + Err(AudioError::Encode("the packet encoder is finished".into())) + } else { + Ok(()) + } + } + + /// Appends a packet of `duration` decoded samples at the current position. + fn emit(pts: &mut u64, out: &mut Vec, data: Vec, duration: u32) { + out.push(EncodedPacket { data, pts: *pts, duration }); + *pts = pts.saturating_add(u64::from(duration)); + } + + /// Encodes `planes` (one slice per codec channel, equally long, at most [`CHUNK`] frames) + /// and appends the packets completed. + fn push(&mut self, planes: &[&[f32]], out: &mut Vec) -> Result<()> { + let pts = &mut self.pts; + match &mut self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => { + for data in enc.encode(planes) { + Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32); + } + } + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, quantizers, pending } => { + let frames = planes.first().map_or(0, |p| p.len()); + let mut at = 0; + while at < frames { + let filled = pending.first().map_or(0, Vec::len); + let end = frames.min(at + CHUNK.saturating_sub(filled).max(1)); + for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) { + dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s))); + } + at = end; + if pending.first().is_some_and(|p| p.len() >= CHUNK) { + alac_packet(enc, pending, pts, out)?; + } + } + } + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, bytes } => { + bytes.extend(enc.encode(planes)); + mp3_frames(enc, bytes, pts, out)?; + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, planes: clean } => { + for (dst, src) in clean.iter_mut().zip(planes) { + dst.clear(); + dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })); + } + let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect(); + for p in enc.push(&refs)? { + Self::emit(pts, out, p.data, p.samples); + } + } + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, pending, coded } => { + let frames = planes.first().map_or(0, |p| p.len()); + for i in 0..frames { + pending.extend(planes.iter().map(|p| p.get(i).copied().map_or(0.0, |s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) }))); + if pending.len() == crate::opus::encoder::Encoder::FRAME_SIZE * planes.len() { + opus_packet(enc, pending, coded, pts, out)?; + } + } + } + } + Ok(()) + } + + /// Encodes what the codec still holds and appends the last packets. + fn drain(&mut self, out: &mut Vec) -> Result<()> { + let pts = &mut self.pts; + match &mut self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => { + for data in enc.flush() { + Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32); + } + } + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, pending, .. } => { + if pending.first().is_some_and(|p| !p.is_empty()) { + alac_packet(enc, pending, pts, out)?; + } + } + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, bytes } => { + bytes.extend(enc.flush()); + mp3_frames(enc, bytes, pts, out)?; + if !bytes.is_empty() { + return Err(AudioError::Encode(format!("the MP3 encoder ended with {} bytes that are not a whole frame", bytes.len()))); + } + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, .. } => { + for p in enc.finish()?.packets { + Self::emit(pts, out, p.data, p.samples); + } + } + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, pending, coded } => { + // Every input frame decodes after the pre-skip: as many packets as that takes. + let size = crate::opus::encoder::Encoder::FRAME_SIZE as u64; + let needed = if self.frames == 0 { 0 } else { (self.frames + u64::from(enc.pre_skip())).div_ceil(size) * size }; + let width = usize::from(enc.channels()); + while *coded < needed { + pending.resize(crate::opus::encoder::Encoder::FRAME_SIZE * width, 0.0); + opus_packet(enc, pending, coded, pts, out)?; + } + } + } + Ok(()) + } +} + +/// Encodes the pending samples as one ALAC packet and empties them. +#[cfg(feature = "alac-encode")] +fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec], pts: &mut u64, out: &mut Vec) -> Result<()> { + let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect(); + let frames = refs.first().map_or(0, |p| p.len()) as u32; + let data = enc.encode(&refs)?; + pending.iter_mut().for_each(Vec::clear); + PacketEncoder::emit(pts, out, data, frames); + Ok(()) +} + +/// Encodes one full frame of pending interleaved samples as an Opus packet and empties them. +#[cfg(feature = "opus-encode")] +fn opus_packet( + enc: &mut crate::opus::encoder::Encoder, + pending: &mut Vec, + coded: &mut u64, + pts: &mut u64, + out: &mut Vec, +) -> Result<()> { + let data = enc.encode_float(pending)?; + pending.clear(); + let size = crate::opus::encoder::Encoder::FRAME_SIZE as u32; + *coded += u64::from(size); + PacketEncoder::emit(pts, out, data, size); + Ok(()) +} + +/// Splits the whole MP3 frames off the front of `bytes`. The encoder writes constant-rate frames +/// back to back, so each one's length follows from its header's padding bit. +#[cfg(feature = "mp3-encode")] +fn mp3_frames(enc: &crate::mp3::Encoder, bytes: &mut Vec, pts: &mut u64, out: &mut Vec) -> Result<()> { + let samples = enc.frame_samples(); + let config = enc.config(); + // Bytes per frame: samples / 8 × bit rate / sample rate, plus the padding slot. + let base = (samples as u64 / 8 * u64::from(config.bitrate_kbps) * 1000 / u64::from(config.sample_rate.max(1))) as usize; + let mut at = 0; + while let Some(header) = bytes.get(at..at + 4) { + if header[0] != 0xFF || header[1] & 0xE0 != 0xE0 { + return Err(AudioError::Encode("the MP3 encoder returned bytes that are not a frame".into())); + } + let len = base + usize::from((header[2] >> 1) & 1); + let Some(frame) = bytes.get(at..at + len).filter(|_| len > 4) else { break }; + PacketEncoder::emit(pts, out, frame.to_vec(), samples as u32); + at += len; + } + bytes.drain(..at); + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/audio/src/write/coded/tests.rs b/crates/audio/src/packet/tests.rs similarity index 90% rename from crates/audio/src/write/coded/tests.rs rename to crates/audio/src/packet/tests.rs index cbdbd3375b..0056a6b162 100644 --- a/crates/audio/src/write/coded/tests.rs +++ b/crates/audio/src/packet/tests.rs @@ -1,6 +1,6 @@ use super::*; -use crate::Speaker; +use crate::{CodecId, Speaker}; fn map(mask: u32, order: Option<&[usize]>, layout: u32) -> Option> { channel_map(mask, order, &ChannelLayout::from_mask(layout)) @@ -165,3 +165,25 @@ fn the_listed_sample_rates_are_the_encoders() { assert_eq!(EncodeFormat::Aac.sample_rates().unwrap(), sorted(&crate::aac::SAMPLE_RATES)); assert_eq!(EncodeFormat::Mp3.sample_rates().unwrap(), sorted(&crate::mp3::SAMPLE_RATES)); } + +/// A codec whose feature is not built is refused, as `EncodeOptions::check` refuses its format. +#[test] +fn unbuilt_codecs_are_unsupported() { + let built = [ + (CodecId::Aac, cfg!(feature = "aac-encode")), + (CodecId::Alac, cfg!(feature = "alac-encode")), + (CodecId::Mp3, cfg!(feature = "mp3-encode")), + (CodecId::Ac3, cfg!(feature = "ac3-encode")), + (CodecId::Eac3, cfg!(feature = "eac3-encode")), + (CodecId::Opus, cfg!(feature = "opus-encode")), + ]; + let opts = EncodeOptions::default().with_bit_depth(crate::BitDepth::Int16); + for (codec, built) in built { + let made = PacketEncoder::new(codec, &opts, 48_000, 2); + if built { + assert!(made.is_ok(), "{codec:?}: {made:?}"); + } else { + assert!(matches!(&made, Err(AudioError::Unsupported(m)) if m.contains("feature")), "{codec:?}: {made:?}"); + } + } +} diff --git a/crates/audio/src/s302m.rs b/crates/audio/src/s302m.rs new file mode 100644 index 0000000000..09f5d6a4c3 --- /dev/null +++ b/crates/audio/src/s302m.rs @@ -0,0 +1,271 @@ +//! SMPTE ST 302M: AES3 audio carried in MPEG-2 transport stream packets (feature `s302m`): a +//! packet decoder ([`decode`]) and encoder ([`Encoder`]) for the payload of one PES packet. +//! +//! A packet is a 4-byte header and the audio. The header is the size in bytes of the audio (16 bits, +//! big-endian), then 16 bits: the channel count code (2 bits; 0 to 3 for 2, 4, 6 or 8 channels), the +//! identification of the first channel (8 bits), the sample size code (2 bits; 0, 1 and 2 for 16, 20 +//! and 24 bits) and 4 alignment bits. The audio is, for every frame, one 40-, 48- or 56-bit group +//! per channel pair, the pairs in order: each pair is two AES3 subframes, the left channel then the +//! right one, each of the sample (least significant bit first) and four flag bits (V, U, C and a +//! frame-start flag set on the left subframe of each channel pair in the first frame of every block of 192 frames). The +//! bits go out in transmission order, so a byte holds them most significant bit first. +//! +//! Samples are signed `i32` in the stream's own range (16, 20 or 24 bits, not scaled). The +//! decoder reads the flags and ignores them; the encoder writes the validity, user and channel +//! status bits as zero and sets the frame-start flag. +//! +//! Written from the standard's description of the packet and the AES3 subframe. ffmpeg is only run +//! as a black-box oracle in the tests. + +/// The most audio bytes one packet can hold (the size field is 16 bits). +pub const MAX_AUDIO_BYTES: usize = 0xFFFF; + +/// What went wrong decoding or encoding. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The packet is damaged, truncated, or uses a reserved code. + #[error("malformed SMPTE 302M packet: {0}")] + Malformed(&'static str), + /// The settings or samples given to the encoder cannot be written. + #[error("SMPTE 302M cannot encode: {0}")] + InvalidInput(&'static str), +} + +/// `Result` of this module. +pub type Result = std::result::Result; + +/// The header of a packet. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Header { + /// 2, 4, 6 or 8. + pub channels: usize, + /// The identification of the first channel (as the stream gives it). + pub channel_id: u8, + /// 16, 20 or 24. + pub bits: u32, + /// The alignment bits as written. + pub alignment: u8, + /// Bytes of audio after the header. + pub audio_bytes: usize, +} + +impl Header { + /// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` are unsupported or overflow. + pub fn frame_bytes(&self) -> usize { + if !matches!(self.channels, 2 | 4 | 6 | 8) { + return 0; + } + let pair_bytes = match self.bits { + 16 => 5, + 20 => 6, + 24 => 7, + _ => return 0, + }; + (self.channels / 2).checked_mul(pair_bytes).unwrap_or(0) + } +} + +/// Parse the 4-byte header at the start of `packet`. +pub fn parse_header(packet: &[u8]) -> Result
{ + let [a, b, c, d, ..] = *packet else { return Err(Error::Malformed("shorter than the header")) }; + let size = usize::from(u16::from_be_bytes([a, b])); + let word = u16::from_be_bytes([c, d]); + let channels = 2 * (usize::from(word >> 14) + 1); + let bits = match (word >> 4) & 3 { + 0 => 16, + 1 => 20, + 2 => 24, + _ => return Err(Error::Malformed("reserved sample size code")), + }; + Ok(Header { channels, channel_id: ((word >> 6) & 0xFF) as u8, bits, alignment: (word & 0xF) as u8, audio_bytes: size }) +} + +/// One decoded packet. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Decoded { + /// The packet header. + pub header: Header, + /// Interleaved samples, `header.channels` per frame. + pub samples: Vec, +} + +/// Bit `i` of a byte string in transmission order (the first bit sent is the least significant bit of the sample, held in the most significant bit of the byte). +fn bit(bytes: &[u8], i: usize) -> u32 { + bytes.get(i / 8).map_or(0, |b| u32::from((b >> (7 - i % 8)) & 1)) +} + +/// Decode the payload of one PES packet. +pub fn decode(packet: &[u8]) -> Result { + let header = parse_header(packet)?; + let audio = packet.get(4..).unwrap_or(&[]); + if audio.len() < header.audio_bytes { + return Err(Error::Malformed("the audio is shorter than the header says")); + } + let audio = audio.get(..header.audio_bytes).unwrap_or(&[]); + let frame_bytes = header.frame_bytes(); + if frame_bytes == 0 || audio.len() % frame_bytes != 0 { + return Err(Error::Malformed("the audio is not a whole number of frames")); + } + let n = header.bits as usize; + let mut samples = Vec::with_capacity(audio.len() / (n + 4) * 8 / 2); + for frame in audio.chunks_exact(frame_bytes) { + for pos in (0..header.channels).map(|c| c * (n + 4)) { + let mut v = 0u32; + for k in 0..n { + v |= bit(frame, pos + k) << k; + } + // sign-extend the n-bit sample + let shift = 32 - n as u32; + samples.push(((v << shift) as i32) >> shift); + } + } + Ok(Decoded { header, samples }) +} + +/// A packet encoder. It counts frames so that the frame-start flag falls on the first frame of +/// every block of 192. +#[derive(Debug, Clone)] +pub struct Encoder { + channels: usize, + bits: u32, + channel_id: u8, + frames: u64, +} + +impl Encoder { + /// An encoder for `channels` (2, 4, 6 or 8) channels of `bits` (16, 20 or 24) bits. + pub fn new(channels: usize, bits: u32) -> Result { + if !matches!(channels, 2 | 4 | 6 | 8) { + return Err(Error::InvalidInput("SMPTE 302M carries 2, 4, 6 or 8 channels")); + } + if !matches!(bits, 16 | 20 | 24) { + return Err(Error::InvalidInput("SMPTE 302M samples have 16, 20 or 24 bits")); + } + Ok(Encoder { channels, bits, channel_id: 0, frames: 0 }) + } + + /// Set the identification of the first channel written in the header (0 by default). + pub fn channel_id(mut self, id: u8) -> Encoder { + self.channel_id = id; + self + } + + /// The most frames one packet can hold. + pub fn max_frames(&self) -> usize { + MAX_AUDIO_BYTES / (self.channels / 2 * ((self.bits as usize + 4) * 2 / 8)) + } + + /// Encode interleaved samples (a whole number of frames, at most [`Encoder::max_frames`], each + /// within the sample size) as one packet payload. + pub fn encode(&mut self, samples: &[i32]) -> Result> { + if samples.is_empty() || !samples.len().is_multiple_of(self.channels) { + return Err(Error::InvalidInput("the samples are not a whole number of frames")); + } + let frames = samples.len() / self.channels; + if frames > self.max_frames() { + return Err(Error::InvalidInput("too many frames for one packet")); + } + let n = self.bits as usize; + let limit = 1i64 << (n - 1); + if samples.iter().any(|&s| i64::from(s) < -limit || i64::from(s) >= limit) { + return Err(Error::InvalidInput("a sample is outside the sample size")); + } + let frame_bytes = self.channels / 2 * ((n + 4) * 2 / 8); + let audio_bytes = frames * frame_bytes; + let code = match self.bits { + 16 => 0u16, + 20 => 1, + _ => 2, + }; + let word = (((self.channels / 2 - 1) as u16) << 14) | (u16::from(self.channel_id) << 6) | (code << 4); + let mut out = Vec::with_capacity(4 + audio_bytes); + out.extend((audio_bytes as u16).to_be_bytes()); + out.extend(word.to_be_bytes()); + out.resize(4 + audio_bytes, 0); + for (f, frame) in samples.chunks_exact(self.channels).enumerate() { + let start = (self.frames + f as u64).is_multiple_of(192); + let base = 4 + f * frame_bytes; + for (c, &s) in frame.iter().enumerate() { + let pos = c * (n + 4); + let v = (s as u32) & ((1u32 << n) - 1); + for k in 0..n { + set_bit(&mut out, base, pos + k, (v >> k) & 1); + } + // flags V, U, C, then the frame-start flag on the left subframe of each pair + if c % 2 == 0 && start { + set_bit(&mut out, base, pos + n + 3, 1); + } + } + } + self.frames += frames as u64; + Ok(out) + } +} + +fn set_bit(out: &mut [u8], base: usize, i: usize, v: u32) { + if v != 0 + && let Some(b) = out.get_mut(base + i / 8) + { + *b |= 0x80 >> (i % 8); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_packet() { + // stereo 16-bit, one frame: L = 0x1234, R = 0xFEFF, the first frame of a block + let packet = [0x00, 0x05, 0x00, 0x00, 0x2c, 0x48, 0x1f, 0xf7, 0xf0]; + let d = decode(&packet).unwrap(); + assert_eq!(d.samples, vec![0x1234, -257]); + assert_eq!((d.header.channels, d.header.bits), (2, 16)); + let mut e = Encoder::new(2, 16).unwrap(); + assert_eq!(e.encode(&[0x1234, -257]).unwrap(), packet); + } + + #[test] + fn settings_and_packets_are_checked() { + assert!(Encoder::new(1, 16).is_err()); + assert!(Encoder::new(2, 18).is_err()); + let mut e = Encoder::new(2, 16).unwrap(); + assert!(e.encode(&[]).is_err()); + assert!(e.encode(&[1]).is_err()); + assert!(e.encode(&[40_000, 0]).is_err()); + assert!(decode(&[0, 1]).is_err()); + assert!(decode(&[0, 5, 0, 0x30, 0, 0, 0, 0, 0]).is_err()); + assert!(decode(&[0, 5, 0, 0, 0, 0]).is_err()); + assert!(decode(&[0, 4, 0, 0, 0, 0, 0, 0]).is_err()); + } + + #[test] + fn header_frame_bytes_overflow_does_not_panic() { + let h = Header { channels: usize::MAX, channel_id: 0, bits: 24, alignment: 0, audio_bytes: 0 }; + assert_eq!(h.frame_bytes(), 0); + } + + #[test] + fn header_frame_bytes_rejects_unsupported_channels() { + for bits in [16, 20, 24] { + for channels in [0, 1, 3, 5, 7, 9, 10, usize::MAX] { + let header = Header { channels, channel_id: 0, bits, alignment: 0, audio_bytes: 0 }; + assert!(Encoder::new(channels, bits).is_err()); + assert_eq!(header.frame_bytes(), 0, "{channels} channels, {bits} bits"); + } + } + } + + #[test] + fn header_frame_bytes_rejects_unsupported_depth() { + let h_max = Header { channels: 2, channel_id: 0, bits: u32::MAX, alignment: 0, audio_bytes: 0 }; + assert_eq!(h_max.frame_bytes(), 0); + + let h_unsupported = Header { channels: 2, channel_id: 0, bits: 18, alignment: 0, audio_bytes: 0 }; + assert_eq!(h_unsupported.frame_bytes(), 0); + + let h_zero = Header { channels: 2, channel_id: 0, bits: 0, alignment: 0, audio_bytes: 0 }; + assert_eq!(h_zero.frame_bytes(), 0); + } +} diff --git a/crates/audio/src/vorbis/mod.rs b/crates/audio/src/vorbis/mod.rs index 15b81bb26d..bb2dbec062 100644 --- a/crates/audio/src/vorbis/mod.rs +++ b/crates/audio/src/vorbis/mod.rs @@ -1,7 +1,83 @@ //! Vorbis I: the pure-Rust [`decoder`] (feature `vorbis-decode`) and [`encoder`] (feature //! `vorbis-encode`). `craft_audio::decode` still reads Vorbis files through symphonia. +//! +//! Both work in Vorbis channel order (Vorbis I §4.3.9). [`wav_order`] maps decoded channels to the +//! WAV order the rest of craft-audio uses, and [`layout`] gives the speakers they then feed. + +use crate::ChannelLayout; #[cfg(feature = "vorbis-decode")] pub mod decoder; #[cfg(feature = "vorbis-encode")] pub mod encoder; + +/// Channel order for Vorbis surround (Vorbis I §4.3.9: L C R for three, L C R Ls Rs for five, +/// L C R Ls Rs LFE for 5.1, L C R Ls Rs Cb LFE for 6.1, L C R Ls Rs Lb Rb LFE for 7.1): output +/// channel → decoded channel, giving the WAV order (L R C LFE back… side…) of [`layout`]. `None` for +/// 1, 2 and 4 channels, which are already in WAV order, and for more than 8, whose order the +/// specification leaves to the application. +/// +/// ``` +/// let vorbis: Vec> = (0..6).map(|c| vec![c as f32]).collect(); // L C R Ls Rs LFE +/// let order = craft_audio::vorbis::wav_order(6).unwrap(); +/// let wav: Vec> = order.iter().map(|&c| vorbis[c].clone()).collect(); // L R C LFE Ls Rs +/// assert_eq!(wav[3], vec![5.0]); +/// ``` +pub fn wav_order(channels: usize) -> Option<&'static [usize]> { + Some(match channels { + 3 => &[0, 2, 1], + 5 => &[0, 2, 1, 3, 4], + 6 => &[0, 2, 1, 5, 3, 4], + 7 => &[0, 2, 1, 6, 5, 3, 4], + 8 => &[0, 2, 1, 7, 5, 6, 3, 4], + _ => return None, + }) +} + +/// The speakers of a Vorbis stream with `channels` channels, in WAV order (after [`wav_order`]): +/// mono, stereo, L R C, quad, 5.0, 5.1, 6.1 with a back center and side surrounds, and 7.1 with +/// backs and sides. Other counts are unordered. For 7 channels this differs from +/// [`ChannelLayout::default_for`], which puts the surrounds at the back. +pub fn layout(channels: u16) -> ChannelLayout { + match channels { + 1 => ChannelLayout::MONO, + 2 => ChannelLayout::STEREO, + 3 => ChannelLayout::SURROUND_3_0, + 4 => ChannelLayout::QUAD, + 5 => ChannelLayout::SURROUND_5_0, + 6 => ChannelLayout::SURROUND_5_1, + 7 => ChannelLayout::SURROUND_6_1, + 8 => ChannelLayout::SURROUND_7_1, + _ => ChannelLayout::unordered(channels), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Speaker::{self, *}; + + /// Vorbis I §4.3.9, one row per channel count, in the order a stream carries the channels. + const VORBIS_ORDER: [&[Speaker]; 8] = [ + &[FrontCenter], + &[FrontLeft, FrontRight], + &[FrontLeft, FrontCenter, FrontRight], + &[FrontLeft, FrontRight, BackLeft, BackRight], + &[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight], + &[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight, Lfe], + &[FrontLeft, FrontCenter, FrontRight, SideLeft, SideRight, BackCenter, Lfe], + &[FrontLeft, FrontCenter, FrontRight, SideLeft, SideRight, BackLeft, BackRight, Lfe], + ]; + + #[test] + fn reordered_channels_feed_the_layout_speakers() { + for (i, stream) in VORBIS_ORDER.iter().enumerate() { + let channels = i + 1; + let wav: Vec = match wav_order(channels) { + Some(order) => order.iter().map(|&c| stream[c]).collect(), + None => stream.to_vec(), + }; + assert_eq!(wav, layout(channels as u16).speakers(), "{channels} channels"); + } + } +} diff --git a/crates/audio/src/write/coded.rs b/crates/audio/src/write/coded.rs index 0d0dd626f4..040d590d0d 100644 --- a/crates/audio/src/write/coded.rs +++ b/crates/audio/src/write/coded.rs @@ -1,7 +1,7 @@ //! The coded formats of [`FileEncoder`](crate::FileEncoder): AAC-LC and ALAC in M4A (through -//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] maps the caller's -//! WAV-order channels onto the encoder's order, drives the packet encoder, and for M4A records the -//! encoder's priming and the exact length in the edit list. +//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] drives a +//! [`PacketEncoder`], which maps the caller's WAV-order channels onto the codec's order, and for +//! M4A records the encoder's priming and the exact length in the edit list. // Each codec is its own feature, and so are the two sinks: with only some of them built, the // other halves of the shared code are unused. @@ -11,271 +11,10 @@ )] use super::failed_write_error; -use super::pcm::validate_layout; -use crate::layout::channel_map; -use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, RateControl, Result}; +use crate::packet::{EncodedPacket, PacketEncoder}; +use crate::{AudioBuffer, AudioError, CodecId, EncodeFormat, EncodeOptions, Result}; use std::io::{Cursor, Seek, Write}; -/// Frames handed to the encoder at a time, so its buffers and the packets waiting to be written -/// stay small however long a block is. Also the frames of an ALAC packet. -const CHUNK: usize = 4096; - -/// Bits per second per channel when no rate is asked for: AAC. -const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; -/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per -/// full-bandwidth channel). -const DEFAULT_KBPS_PER_CHANNEL: u32 = 96; - -/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`. -fn labels(mask: u32) -> String { - ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::>().join(" ") -} - -/// [`channel_map`] for a format with one layout per channel count ([`EncodeFormat::layout_masks`]), -/// or why the audio does not fit. -fn fixed_map(format: EncodeFormat, name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result> { - let Some(&mask) = format.layout_masks(layout.channels()).first() else { - return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels()))); - }; - channel_map(mask, order, layout).ok_or_else(|| { - AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout))) - }) -} - -/// The speakers of the caller's layout, for an error message. -fn given(layout: &ChannelLayout) -> String { - layout.mask().map_or_else(|| "without speaker assignment".into(), labels) -} - -/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for 8 channels -/// configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc. -#[cfg(feature = "aac-encode")] -fn aac_order(channels: usize) -> Option<&'static [usize]> { - if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) } -} - -/// The lowest AAC bit rate the writer uses, per channel: 6 kbit/s, and a quarter of the sample -/// rate (256 bits a frame). The encoder accepts less, and from about half of this down codes -/// silence; a file of silence is no answer to a low bit rate (or to kbit/s given as bit/s). -#[cfg(feature = "aac-encode")] -fn aac_floor_per_channel(sample_rate: u32) -> u32 { - (sample_rate / 4).max(6000) -} - -/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a -/// quality of 0–1 spans the encoder's VBR range. -#[cfg(feature = "aac-encode")] -fn aac_mode(rate: Option, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode { - use crate::aac::BitrateMode; - let (lo, hi) = crate::aac::cbr_range(sample_rate, channels); - let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo)); - // An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone. - let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps }; - match rate { - None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))), - Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)), - // NaN stays NaN, which the encoder refuses. - Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)), - } -} - -/// The bit rate in kbit/s for a codec with constant bit rates only. -fn constant_kbps(name: &str, rate: Option, default: u32) -> Result { - match rate { - None => Ok(default), - Some(RateControl::Bitrate(bps)) => Ok(bps / 1000), - Some(RateControl::Quality(_)) => { - Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality"))) - } - } -} - -/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding -/// mode whose speakers the layout names, at the nearest bit rate the stream can carry. -#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] -fn ac3_config( - codec: crate::ac3::encoder::Codec, - sample_rate: u32, - layout: &ChannelLayout, - rate: Option, -) -> Result<(crate::ac3::encoder::Config, Vec)> { - use crate::ac3::encoder::{Codec, CodingMode, Config}; - use CodingMode::*; - let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" }; - let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; - let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| { - // 7.1 is an E-AC-3 programme with an LFE; the encoder has no other. - if mode == Surround71 && (codec != Codec::Eac3 || !lfe) { - return None; - } - let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe }; - let map = channel_map(config.channel_layout().mask()?, None, layout)?; - Some((config, map)) - }); - let Some((mut config, map)) = found else { - return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout)))); - }; - let full = config.mode.channels() as u32; - let want = constant_kbps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full)?; - // What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of - // the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold. - let least = if config.mode == Surround71 { 384 } else { 32 * full }; - config.bitrate_kbps = match codec { - Codec::Ac3 => { - let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least); - crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor) - } - Codec::Eac3 => { - let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 }; - want.clamp(least, most.max(least)) - } - }; - Ok((config, map)) -} - -/// One encoded packet and the frames it decodes to. -struct Packet { - data: Vec, - frames: u32, -} - -/// A packet encoder of any of the codecs, taking planar `f32` in its own channel order. -enum Codec { - #[cfg(feature = "aac-encode")] - Aac(Box), - #[cfg(feature = "alac-encode")] - Alac { - enc: Box, - quantizers: Vec, - /// Quantized samples of the packet being filled, per channel. - pending: Vec>, - }, - #[cfg(feature = "mp3-encode")] - Mp3(Box), - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Ac3 { - enc: Box, - /// The block with every sample finite and within ±1, as the encoder requires. - planes: Vec>, - }, -} - -impl Codec { - /// Encodes `planes` (one slice per encoder channel, equally long, at most [`CHUNK`] frames) - /// and appends the packets completed. - fn push(&mut self, planes: &[&[f32]], out: &mut Vec) -> Result<()> { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => out.extend(enc.encode(planes).into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })), - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, quantizers, pending } => { - let frames = planes.first().map_or(0, |p| p.len()); - let mut at = 0; - while at < frames { - let filled = pending.first().map_or(0, Vec::len); - let end = frames.min(at + CHUNK.saturating_sub(filled).max(1)); - for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) { - dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s))); - } - at = end; - if pending.first().is_some_and(|p| p.len() >= CHUNK) { - alac_packet(enc, pending, out)?; - } - } - } - #[cfg(feature = "mp3-encode")] - Codec::Mp3(enc) => { - let data = enc.encode(planes); - if !data.is_empty() { - out.push(Packet { data, frames: 0 }); - } - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Codec::Ac3 { enc, planes: clean } => { - for (dst, src) in clean.iter_mut().zip(planes) { - dst.clear(); - dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })); - } - let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect(); - out.extend(enc.push(&refs)?.into_iter().map(|p| Packet { data: p.data, frames: p.samples })); - } - } - Ok(()) - } - - /// Encodes what the encoder still holds and appends the last packets. - fn finish(&mut self, out: &mut Vec) -> Result<()> { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => out.extend(enc.flush().into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })), - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, pending, .. } => { - if pending.first().is_some_and(|p| !p.is_empty()) { - alac_packet(enc, pending, out)?; - } - } - #[cfg(feature = "mp3-encode")] - Codec::Mp3(enc) => { - let data = enc.flush(); - if !data.is_empty() { - out.push(Packet { data, frames: 0 }); - } - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Codec::Ac3 { enc, .. } => out.extend(enc.finish()?.packets.into_iter().map(|p| Packet { data: p.data, frames: p.samples })), - } - Ok(()) - } - - /// Decoded frames before the first frame of the audio. - fn priming(&self) -> u32 { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => enc.priming_samples(), - #[allow(unreachable_patterns)] - _ => 0, - } - } - - /// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` - /// frames in all): the configuration a decoder needs, with the average bit rate. - #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - fn sample_entry(&self, sample_rate: u32, channels: u32, bytes: u64, frames: u64) -> Option { - use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry}; - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => { - let mut entry = SampleEntry::aac(enc.audio_specific_config(), channels, sample_rate); - if let CodecConfig::Aac(config) = &mut entry.codec - && frames > 0 - { - let bps = u128::from(bytes) * 8 * u128::from(sample_rate) / u128::from(frames); - config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX); - } - Some(entry) - } - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, .. } => { - let bits = u16::from(enc.encoder_config().bit_depth); - Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.cookie() }, channels, f64::from(sample_rate), bits)) - } - #[allow(unreachable_patterns)] - _ => None, - } - } -} - -/// Encodes the pending samples as one ALAC packet and empties them. -#[cfg(feature = "alac-encode")] -fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec], out: &mut Vec) -> Result<()> { - let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect(); - let frames = refs.first().map_or(0, |p| p.len()) as u32; - let data = enc.encode(&refs)?; - pending.iter_mut().for_each(Vec::clear); - out.push(Packet { data, frames }); - Ok(()) -} - /// A muxer's error as this crate's: a failed write stays an I/O error. #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] fn mux_error(e: craft_media::isobmff::Error) -> AudioError { @@ -285,6 +24,31 @@ fn mux_error(e: craft_media::isobmff::Error) -> AudioError { } } +/// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` frames in +/// all): the configuration a decoder needs, with the average bit rate. +#[cfg(any(feature = "aac-encode", feature = "alac-encode"))] +fn sample_entry(enc: &PacketEncoder, bytes: u64, frames: u64) -> Option { + use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry}; + let (rate, channels) = (enc.sample_rate(), u32::from(enc.channels())); + match enc.codec() { + CodecId::Aac => { + let mut entry = SampleEntry::aac(enc.extradata(), channels, rate); + if let CodecConfig::Aac(config) = &mut entry.codec + && frames > 0 + { + let bps = u128::from(bytes) * 8 * u128::from(rate) / u128::from(frames); + config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX); + } + Some(entry) + } + CodecId::Alac => { + let bits = u16::from(enc.bit_depth().unwrap_or(16)); + Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.extradata() }, channels, f64::from(rate), bits)) + } + _ => None, + } +} + /// An M4A file being written: one audio track whose samples are the packets. /// /// The last packet is held back until the length is known: its duration is cut to the audio's @@ -298,9 +62,8 @@ struct M4a { track: Option, entry: craft_media::isobmff::SampleEntry, sample_rate: u32, - channels: u32, priming: u32, - held: Option, + held: Option, /// Frames and bytes of the packets written, the held one not counted. frames: u64, bytes: u64, @@ -308,13 +71,14 @@ struct M4a { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] impl M4a { - fn new(out: W, codec: &Codec, sample_rate: u32, channels: u32) -> Result { + fn new(out: W, enc: &PacketEncoder) -> Result { use craft_media::isobmff::{Brand, Mp4Writer, WriterOptions}; - let entry = codec.sample_entry(sample_rate, channels, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?; + let entry = sample_entry(enc, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?; + let sample_rate = enc.sample_rate(); let mut options = WriterOptions::new(Brand::Mp4); options.movie_timescale = sample_rate; let mux = Mp4Writer::new(out, options).map_err(mux_error)?; - Ok(M4a { mux, track: None, entry, sample_rate, channels, priming: codec.priming(), held: None, frames: 0, bytes: 0 }) + Ok(M4a { mux, track: None, entry, sample_rate, priming: enc.priming(), held: None, frames: 0, bytes: 0 }) } fn track(&mut self, has_audio: bool) -> Result { @@ -333,7 +97,7 @@ impl M4a { Ok(track) } - fn sample(&mut self, packet: &Packet, duration: u32) -> Result<()> { + fn sample(&mut self, packet: &EncodedPacket, duration: u32) -> Result<()> { let track = self.track(true)?; let sample = craft_media::isobmff::WriteSample { data: &packet.data, duration, composition_offset: 0, is_sync: true }; self.mux.write_sample(track, sample).map_err(mux_error)?; @@ -342,22 +106,22 @@ impl M4a { Ok(()) } - fn write(&mut self, packet: Packet) -> Result<()> { + fn write(&mut self, packet: EncodedPacket) -> Result<()> { if let Some(held) = self.held.replace(packet) { - self.sample(&held, held.frames)?; + self.sample(&held, held.duration)?; } Ok(()) } - /// Writes the last packet, cut to the end of `audio_frames` frames of audio, and the `moov`. - fn finish(mut self, codec: &Codec, audio_frames: u64) -> Result { + /// Writes the last packet, cut to the end of the audio the encoder took, and the `moov`. + fn finish(mut self, enc: &PacketEncoder) -> Result { if let Some(held) = self.held.take() { - let rest = (u64::from(self.priming) + audio_frames).saturating_sub(self.frames); - self.sample(&held, rest.min(u64::from(held.frames)) as u32)?; + let rest = (u64::from(self.priming) + enc.frames()).saturating_sub(self.frames); + self.sample(&held, rest.min(u64::from(held.duration)) as u32)?; } let track = self.track(false)?; // The configuration is complete only now: the bit rate, and ALAC's largest packet. - if let Some(entry) = codec.sample_entry(self.sample_rate, self.channels, self.bytes, self.frames) { + if let Some(entry) = sample_entry(enc, self.bytes, self.frames) { self.mux.set_sample_entry(track, entry).map_err(mux_error)?; } self.mux.finish().map_err(mux_error) @@ -374,15 +138,8 @@ enum Sink { /// A file of one of the coded formats written block by block. pub(crate) struct Writer { - codec: Codec, + enc: PacketEncoder, sink: Sink, - /// For each encoder channel, the caller's channel that feeds it. - map: Vec, - /// The constant bit rate the encoder was set to, bits per second; `None` for ALAC and for - /// AAC at a constant quality. - bitrate: Option, - frames: u64, - packets: Vec, /// Set when a write has failed: the encoder and the sink no longer agree, so the writer /// refuses every later call. failed: bool, @@ -390,68 +147,23 @@ pub(crate) struct Writer { impl Writer { pub(crate) fn new(out: W, opts: &EncodeOptions, sample_rate: u32, channels: usize) -> Result { - validate_layout(channels, sample_rate)?; - let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels as u16)); - let (codec, map, bitrate) = match opts.format { - #[cfg(feature = "aac-encode")] - EncodeFormat::Aac => { - let map = fixed_map(EncodeFormat::Aac, "AAC", aac_order(channels), &layout)?; - let mode = aac_mode(opts.rate_control, sample_rate, channels); - let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, channels, 0) }; - let bitrate = match mode { - crate::aac::BitrateMode::Cbr(bps) => Some(bps), - crate::aac::BitrateMode::Vbr(_) => None, - }; - (Codec::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, bitrate) - } - #[cfg(feature = "alac-encode")] - EncodeFormat::Alac => { - let count = u8::try_from(channels).unwrap_or(u8::MAX); - let map = fixed_map(EncodeFormat::Alac, "ALAC", crate::alac::alac_order(count), &layout)?; - let bits = match opts.bit_depth { - crate::BitDepth::Int16 => 16, - crate::BitDepth::Int24 => 24, - crate::BitDepth::Int32 => 32, - crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())), - }; - let enc = crate::alac::Encoder::new(crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32))?; - let quantizers = super::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, channels); - (Codec::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); channels] }, map, None) - } - #[cfg(feature = "mp3-encode")] - EncodeFormat::Mp3 => { - let map = fixed_map(EncodeFormat::Mp3, "MP3", None, &layout)?; - let want = constant_kbps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * channels as u32)?; - // A sample rate MP3 has not is the encoder's to refuse. - let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want); - let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, channels, kbps))?; - (Codec::Mp3(Box::new(enc)), map, Some(kbps.saturating_mul(1000))) - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - EncodeFormat::Ac3 | EncodeFormat::Eac3 => { - let codec = if opts.format == EncodeFormat::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 }; - let (config, map) = ac3_config(codec, sample_rate, &layout, opts.rate_control)?; - let enc = crate::ac3::encoder::Encoder::new(config)?; - (Codec::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); channels] }, map, Some(config.bitrate_kbps.saturating_mul(1000))) - } - #[allow(unreachable_patterns)] - f => return Err(AudioError::Unsupported(format!("writing {f:?}"))), - }; + let channels = u16::try_from(channels).map_err(|_| AudioError::Encode("too many channels".into()))?; + let enc = PacketEncoder::new(opts.format.codec(), opts, sample_rate, channels)?; let sink = match opts.format { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &codec, sample_rate, channels as u32)?)), + EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &enc)?)), _ => Sink::Raw(out), }; - Ok(Writer { codec, sink, map, bitrate, frames: 0, packets: Vec::new(), failed: false }) + Ok(Writer { enc, sink, failed: false }) } pub(crate) fn bitrate(&self) -> Option { - self.bitrate + self.enc.bitrate() } - /// Hands the packets waiting to the sink. - fn drain(&mut self) -> Result<()> { - for packet in self.packets.drain(..) { + /// Hands `packets` to the sink. + fn drain(&mut self, packets: Vec) -> Result<()> { + for packet in packets { match &mut self.sink { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] Sink::M4a(m4a) => m4a.write(packet)?, @@ -466,16 +178,16 @@ impl Writer { if self.failed { return Err(failed_write_error()); } - for at in (0..frames).step_by(CHUNK) { - let end = frames.min(at + CHUNK); - let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect(); - let written = self.codec.push(&planes, &mut self.packets).and_then(|()| self.drain()); + // A block at a time, so the packets waiting for the sink stay few however long it is. + for at in (0..frames).step_by(crate::packet::CHUNK) { + let end = frames.min(at + crate::packet::CHUNK); + let part: Vec<&[f32]> = block.iter().map(|c| c.as_ref().get(at..end).unwrap_or_default()).collect(); + let written = self.enc.encode(&part, end - at).and_then(|packets| self.drain(packets)); if let Err(e) = written { self.failed = true; return Err(e); } } - self.frames = self.frames.saturating_add(frames as u64); Ok(()) } @@ -483,11 +195,11 @@ impl Writer { if self.failed { return Err(failed_write_error()); } - self.codec.finish(&mut self.packets)?; - self.drain()?; + let last = self.enc.finish()?; + self.drain(last)?; match self.sink { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - Sink::M4a(m4a) => m4a.finish(&self.codec, self.frames), + Sink::M4a(m4a) => m4a.finish(&self.enc), Sink::Raw(mut out) => { out.flush()?; Ok(out) @@ -501,6 +213,3 @@ pub(crate) fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> w.write(&buf.channels, buf.frames())?; Ok(w.finish()?.into_inner()) } - -#[cfg(test)] -mod tests; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index bbb42601ec..25267e9a05 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -8,7 +8,7 @@ mod aiff; mod coded; #[cfg(feature = "flac-encode")] pub(crate) mod flac; -mod pcm; +pub(crate) mod pcm; #[cfg(feature = "vorbis-encode")] mod vorbis; #[cfg(feature = "vorbis-encode")] @@ -449,8 +449,32 @@ impl EncodeOptions { /// ``` #[cfg(feature = "pcm-encode")] pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result> { + float_header(sample_rate, channels, None, frames) +} + +/// [`wav_float_header`] with a BWF `bext` chunk holding `bwf` before the format chunk. The length +/// still doesn't depend on `frames`, so the header is rewritten in place the same way. +/// +/// ``` +/// use craft_audio::{BwfInfo, wav_float_header_with_bwf}; +/// +/// let bwf = BwfInfo::default().with_originator("Recorder").with_time_reference(48_000 * 3_600); +/// let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap(); +/// let samples = [0.25f32, -0.25, 0.5, -0.5]; +/// file.extend(samples.iter().flat_map(|s| s.to_le_bytes())); +/// let header = wav_float_header_with_bwf(48_000, 2, 2, &bwf).unwrap(); +/// file[..header.len()].copy_from_slice(&header); +/// assert!(header.windows(4).any(|id| id == b"bext")); +/// ``` +#[cfg(feature = "pcm-encode")] +pub fn wav_float_header_with_bwf(sample_rate: u32, channels: u16, frames: u64, bwf: &crate::BwfInfo) -> Result> { + float_header(sample_rate, channels, Some(bwf), frames) +} + +#[cfg(feature = "pcm-encode")] +fn float_header(sample_rate: u32, channels: u16, bwf: Option<&crate::BwfInfo>, frames: u64) -> Result> { if channels == 0 || sample_rate == 0 { return Err(AudioError::Encode("a WAV needs channels and a sample rate".into())); } - wav::header(usize::from(channels), sample_rate, (32, true), None, None, frames, false) + wav::header(usize::from(channels), sample_rate, (32, true), bwf, None, frames, false) } diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 2e58cd6332..dd7005fbfb 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -1,4 +1,7 @@ -use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe}; +use craft_audio::{ + AudioBuffer, BitDepth, BwfInfo, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe, wav_float_header, + wav_float_header_with_bwf, +}; fn sine(sr: u32, channels: usize, frames: usize) -> AudioBuffer { let mut b = AudioBuffer::new(sr, channels as u16, frames); @@ -64,3 +67,26 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() { } } } + +#[test] +fn float_wav_header_with_bwf_keeps_its_bext_as_the_file_grows() { + let take = sine(48_000, 2, 1_000); + let bwf = BwfInfo::default() + .with_description("take 3") + .with_originator("recorder") + .with_origination("2026-11-20", "18:30:00") + .with_time_reference(48_000 * 66_600); + let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap(); + let len = file.len(); + assert!(len > wav_float_header(48_000, 2, 0).unwrap().len()); + file.extend(take.interleaved().iter().flat_map(|s| s.to_le_bytes())); + file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 600, &bwf).unwrap()); + let (info, decoded) = decode(&file, None).unwrap(); + assert_eq!((info.bwf.as_ref(), decoded.frames()), (Some(&bwf), 600)); + file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 1_000, &bwf).unwrap()); + let opts = EncodeOptions::default().with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()); + assert_eq!(file, encode(&take, &opts).unwrap()); + let big = wav_float_header_with_bwf(48_000, 2, 600_000_000, &bwf).unwrap(); + assert_eq!((&big[..4], big.len()), (&b"RF64"[..], len)); + assert!(wav_float_header_with_bwf(48_000, 0, 0, &bwf).is_err()); +} diff --git a/crates/audio/tests/codecs/alac.rs b/crates/audio/tests/codecs/alac.rs index 2d52234e86..8038c3ceb9 100644 --- a/crates/audio/tests/codecs/alac.rs +++ b/crates/audio/tests/codecs/alac.rs @@ -153,3 +153,39 @@ fn ffmpeg_decodes_our_alac_exactly() { } } } + +/// Quiet and silent passages at 24 and 32 bits, which our encoder codes with fewer shifted-off +/// low bytes than Apple's reference (#1368), decode exactly in ffmpeg. The packets alternate +/// between silence, audio within 12 bits, audio at the narrower widths' edges and full scale, so +/// one stream changes its shift from packet to packet. +#[test] +fn ffmpeg_decodes_our_quiet_alac_exactly() { + let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("alac oracle") else { return }; + for (channels, bits) in [(1, 24), (2, 24), (6, 24), (1, 32), (2, 32)] { + let full = input(channels, bits, 4 * 4096); + let wav: Vec> = full + .iter() + .map(|c| { + c.iter() + .enumerate() + .map(|(i, &x)| match i / 4096 { + 0 => 0, + 1 => x >> (bits - 12), + 2 => (x >> (bits - 15)) << (bits - 24), + _ => x, + }) + .collect() + }) + .collect(); + // ffmpeg does not decode escaped 32-bit stereo frames: keep the full-scale packet for 24 + let wav: Vec> = if bits == 32 { wav.iter().map(|c| c[..3 * 4096].to_vec()).collect() } else { wav }; + let m4a = our_m4a(&wav, bits, 4096); + let path = dir().join(format!("ours_quiet_{channels}ch_{bits}.m4a")); + std::fs::write(&path, &m4a).unwrap(); + let theirs = ffmpeg_decode(&ff, &path, channels, bits); + assert!(theirs == wav, "{channels} ch, {bits} bits: ffmpeg's decode differs from the input"); + if bits <= 24 { + assert!(our_decode(&m4a, bits) == wav, "{channels} ch, {bits} bits: our decode differs"); + } + } +} diff --git a/crates/audio/tests/codecs/main.rs b/crates/audio/tests/codecs/main.rs index 41829be5c9..4701426cd8 100644 --- a/crates/audio/tests/codecs/main.rs +++ b/crates/audio/tests/codecs/main.rs @@ -18,6 +18,7 @@ mod mp3_encoder_oracle; mod mpa_oracle; mod opus; mod opusenc; +mod packet_encoder; mod routing_oracle; mod track_decoder; #[cfg(feature = "vorbis-encode")] diff --git a/crates/audio/tests/codecs/opusenc/modes.rs b/crates/audio/tests/codecs/opusenc/modes.rs index a48ad2d444..723510a0f9 100644 --- a/crates/audio/tests/codecs/opusenc/modes.rs +++ b/crates/audio/tests/codecs/opusenc/modes.rs @@ -268,9 +268,7 @@ fn extreme_inputs_stay_decodable() { let (enc, packets) = encode(OpusEncoder::with_mode(c as u8, rate * c as u32, mode, bw).unwrap(), &planar); assert!(packets.iter().all(|p| p.len() >= 3 && p.len() <= 1276), "{name} {mode:?}: packet sizes"); let dec = decode(&enc.opus_head(), &packets); - let peak = dec.iter().flatten().fold(0f32, |m, v| m.max(v.abs())); - let snr = if name == "nan" { f64::NAN } else { snr_search(&planar[0], &dec[0], 2).0 }; - eprintln!("{name} {mode:?}/{bw:?} {c} ch: peak {peak:.2}, SNR {snr:.1} dB, {:.1} kb/s", bitrate(&packets) / 1000.0); + assert_eq!(dec.len(), c, "{name} {mode:?}/{bw:?} {c} ch: decoded channels"); assert!(dec.iter().all(|ch| ch.iter().all(|v| v.is_finite() && v.abs() <= 4.0)), "{name} {mode:?}/{bw:?} {c} ch: bad output"); } } diff --git a/crates/audio/tests/codecs/packet_encoder.rs b/crates/audio/tests/codecs/packet_encoder.rs new file mode 100644 index 0000000000..584255d152 --- /dev/null +++ b/crates/audio/tests/codecs/packet_encoder.rs @@ -0,0 +1,244 @@ +//! `PacketEncoder`: every codec round-trips through `TrackDecoder` from the description the +//! encoder gives, at the length that was encoded and with each channel on its speaker. + +use std::io::Cursor; + +use craft_audio::{ + AudioError, BitDepth, ChannelLayout, CodecId, EncodeFormat, EncodeOptions, EncodedPacket, FileEncoder, PacketEncoder, TrackDecoder, +}; + +/// `channels` channels of `frames` frames, each a tone of its own frequency low enough for an LFE. +fn tones(sample_rate: u32, channels: usize, frames: usize) -> Vec> { + (0..channels) + .map(|c| { + let step = (40.0 + 9.0 * c as f32) * std::f32::consts::TAU / sample_rate as f32; + (0..frames).map(|i| ((i as f32 * step).sin() * 0.4 * 32768.0).round() / 32768.0).collect() + }) + .collect() +} + +/// Normalised correlation of two signals over the samples both have. +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + let (x, y) = (f64::from(x), f64::from(y)); + ab += x * y; + aa += x * x; + bb += y * y; + } + ab / (aa * bb).sqrt().max(1e-30) +} + +/// Encodes `input` in uneven blocks and returns the packets. +fn encode(enc: &mut PacketEncoder, input: &[Vec]) -> Vec { + let frames = input[0].len(); + let mut packets = Vec::new(); + let mut at = 0; + for n in [1, 999, 4096, 10_000, 7, usize::MAX].into_iter().cycle() { + let n = n.min(frames - at); + let block: Vec<&[f32]> = input.iter().map(|c| &c[at..at + n]).collect(); + packets.extend(enc.encode(&block, n).unwrap()); + at += n; + if at == frames { + break; + } + } + packets.extend(enc.finish().unwrap()); + packets +} + +/// Encodes, checks the timing the packets carry, decodes them from the encoder's description, and +/// returns the decoded audio from the first input frame on, cut to the input's length, and the +/// layout the decoder reports. +fn decode_back(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec]) -> (PacketEncoder, Vec>, ChannelLayout) { + let frames = input[0].len(); + let mut enc = PacketEncoder::new(codec, opts, sample_rate, input.len() as u16).unwrap(); + let packets = encode(&mut enc, input); + assert_eq!(enc.frames(), frames as u64); + // The packets follow one another, and add up to the priming, the audio and the padding. + let mut pts = 0; + for p in &packets { + assert_eq!(p.pts, pts, "{codec:?}"); + pts += u64::from(p.duration); + } + assert_eq!(pts, u64::from(enc.priming()) + frames as u64 + enc.padding(), "{codec:?}"); + let last = packets.last().map_or(0, |p| u64::from(p.duration)); + assert!(enc.padding() < last, "{codec:?}: {} samples of padding after a packet of {last}", enc.padding()); + + let lookahead: Vec<&[u8]> = packets.iter().take(craft_audio::LOOKAHEAD_PACKETS).map(|p| p.data.as_slice()).collect(); + let mut dec = TrackDecoder::new(&enc.codec_params(), &lookahead).unwrap(); + assert_eq!((dec.codec(), dec.sample_rate()), (codec, sample_rate), "{codec:?}"); + let mut out = vec![Vec::new(); usize::from(dec.channels())]; + for p in &packets { + let block = dec.decode(&p.data).unwrap(); + assert_eq!(block.frames(), p.duration as usize, "{codec:?}: a packet's duration is what it decodes to"); + for (o, c) in out.iter_mut().zip(block.channels) { + o.extend(c); + } + } + let skip = enc.priming() as usize; + let out = out.into_iter().map(|c| c[skip..skip + frames].to_vec()).collect(); + (enc, out, dec.layout()) +} + +/// [`decode_back`] for a codec whose decoder returns every channel: on the speakers encoded. +fn round_trip(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec]) -> (PacketEncoder, Vec>) { + let (enc, out, layout) = decode_back(codec, opts, sample_rate, input); + assert_eq!(layout, enc.layout(), "{codec:?}"); + (enc, out) +} + +/// Each decoded channel is its input channel, in place: it matches that channel and no other. The +/// AC-3 encoders low-pass the LFE, which shifts its phase, so the match is by magnitude. +fn assert_in_place(codec: CodecId, input: &[Vec], output: &[Vec], least: f64) { + for (c, got) in output.iter().enumerate() { + let scores: Vec = input.iter().map(|want| correlation(want, got).abs()).collect(); + let least = if matches!(codec, CodecId::Ac3 | CodecId::Eac3) && c == 3 { 0.5 } else { least }; + assert!(scores[c] > least, "{codec:?} channel {c}: {scores:?}"); + for (other, &score) in scores.iter().enumerate().filter(|&(o, _)| o != c) { + assert!(score < scores[c] - 0.3, "{codec:?} channel {c} matches channel {other}: {scores:?}"); + } + } +} + +#[test] +fn aac_round_trips_in_place() { + let input = tones(48_000, 6, 30_001); + let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(384_000); + let (enc, out) = round_trip(CodecId::Aac, &opts, 48_000, &input); + assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (1024, ChannelLayout::SURROUND_5_1_SIDE, Some(384_000))); + assert_eq!(enc.extradata().len(), 2, "an AudioSpecificConfig for channel configuration 6"); + assert_in_place(CodecId::Aac, &input, &out, 0.95); +} + +/// 16-bit ALAC is lossless: the input comes back bit for bit. +#[test] +fn alac_round_trips_exactly() { + let input = tones(44_100, 6, 10_000); + let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(ChannelLayout::SURROUND_5_1); + let (enc, out) = round_trip(CodecId::Alac, &opts, 44_100, &input); + assert_eq!((enc.priming(), enc.padding(), enc.bit_depth(), enc.layout()), (0, 0, Some(16), ChannelLayout::SURROUND_5_1)); + assert_eq!(out, input); +} + +#[test] +fn mp3_round_trips_in_place() { + for (rate, frame) in [(48_000, 1152), (44_100, 1152), (24_000, 576)] { + let input = tones(rate, 2, 20_000); + let opts = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(192_000); + let mut enc = PacketEncoder::new(CodecId::Mp3, &opts, rate, 2).unwrap(); + let packets = encode(&mut enc, &input); + assert!(packets.iter().all(|p| p.duration == frame && p.data[0] == 0xFF), "{rate} Hz"); + let (enc, out) = round_trip(CodecId::Mp3, &opts, rate, &input); + assert_eq!((enc.priming(), enc.extradata()), (1057, vec![])); + assert_in_place(CodecId::Mp3, &input, &out, 0.95); + } +} + +#[test] +fn ac3_round_trips_in_place() { + let input = tones(48_000, 6, 20_000); + let (enc, out) = round_trip(CodecId::Ac3, &EncodeOptions::new(EncodeFormat::Ac3), 48_000, &input); + assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (256, ChannelLayout::SURROUND_5_1_SIDE, Some(448_000))); + assert_in_place(CodecId::Ac3, &input, &out, 0.9); +} + +#[test] +fn eac3_round_trips_in_place() { + let input = tones(48_000, 6, 20_000); + let (enc, out) = round_trip(CodecId::Eac3, &EncodeOptions::new(EncodeFormat::Eac3), 48_000, &input); + assert_eq!((enc.priming(), enc.layout()), (256, ChannelLayout::SURROUND_5_1_SIDE)); + assert_in_place(CodecId::Eac3, &input, &out, 0.9); +} + +/// 7.1 E-AC-3 is encoded as 7.1; `TrackDecoder` plays its 5.1 independent substream (see the +/// README), at the same length. +#[test] +fn eac3_7_1_decodes_as_its_5_1_substream() { + let input = tones(48_000, 8, 20_000); + let opts = EncodeOptions::new(EncodeFormat::Eac3).with_layout(ChannelLayout::SURROUND_7_1); + let (enc, out, layout) = decode_back(CodecId::Eac3, &opts, 48_000, &input); + assert_eq!((enc.layout(), enc.channels(), layout), (ChannelLayout::SURROUND_7_1, 8, ChannelLayout::SURROUND_5_1_SIDE)); + assert!(out.iter().all(|c| c.len() == 20_000)); +} + +#[test] +fn opus_round_trips_in_place() { + for channels in [1, 2] { + let input = tones(48_000, channels, 20_000); + let opts = EncodeOptions::default().with_bitrate(128_000); + let (enc, out) = round_trip(CodecId::Opus, &opts, 48_000, &input); + let head = enc.extradata(); + assert_eq!((&head[..8], head[9], u32::from(u16::from_le_bytes([head[10], head[11]]))), (&b"OpusHead"[..], channels as u8, enc.priming())); + assert_in_place(CodecId::Opus, &input, &out, 0.9); + } +} + +/// The raw streams `FileEncoder` writes are the packets in a row. +#[test] +fn file_encoder_writes_the_packets() { + for (format, layout) in [(EncodeFormat::Mp3, ChannelLayout::STEREO), (EncodeFormat::Ac3, ChannelLayout::SURROUND_5_1)] { + let input = tones(48_000, usize::from(layout.channels()), 12_345); + let opts = EncodeOptions::new(format).with_layout(layout); + let mut file = FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, layout.channels()).unwrap(); + file.write(&input, 12_345).unwrap(); + let file = file.finish().unwrap().into_inner(); + let mut enc = PacketEncoder::new(format.codec(), &opts, 48_000, layout.channels()).unwrap(); + let packets: Vec = encode(&mut enc, &input).into_iter().flat_map(|p| p.data).collect(); + assert_eq!(file, packets, "{format:?}"); + } +} + +/// What a codec cannot take is refused, and as `EncodeOptions::check` refuses it for the format. +#[test] +fn unsupported_settings_are_refused() { + let unsupported = + |codec, opts: &EncodeOptions, rate, channels| matches!(PacketEncoder::new(codec, opts, rate, channels), Err(AudioError::Unsupported(_))); + let opts = EncodeOptions::default(); + assert!(unsupported(CodecId::Vorbis, &opts, 48_000, 2)); + assert!(unsupported(CodecId::Flac, &opts, 48_000, 2)); + assert!(unsupported(CodecId::Opus, &opts, 44_100, 2)); + assert!(unsupported(CodecId::Opus, &opts, 48_000, 3)); + assert!(unsupported(CodecId::Opus, &opts.clone().with_quality(0.5), 48_000, 2)); + for (codec, format, rate, channels) in [ + (CodecId::Mp3, EncodeFormat::Mp3, 96_000, 2), + (CodecId::Mp3, EncodeFormat::Mp3, 48_000, 0), + (CodecId::Mp3, EncodeFormat::Mp3, 48_000, 6), + (CodecId::Ac3, EncodeFormat::Ac3, 48_000, 8), + (CodecId::Aac, EncodeFormat::Aac, 44_000, 2), + ] { + let opts = EncodeOptions::new(format); + let (packets, file) = (PacketEncoder::new(codec, &opts, rate, channels).map(drop), opts.check(rate, channels)); + assert_eq!(format!("{packets:?}"), format!("{file:?}"), "{codec:?} {rate} {channels}"); + assert!(packets.is_err()); + } + assert!(unsupported(CodecId::Alac, &opts.clone().with_bit_depth(BitDepth::Float32), 48_000, 2)); + assert!(unsupported(CodecId::Ac3, &opts.clone().with_layout(ChannelLayout::unordered(2)), 48_000, 2)); + // A layout for another channel count is the caller's mistake. + assert!(matches!(PacketEncoder::new(CodecId::Aac, &opts.with_layout(ChannelLayout::STEREO), 48_000, 1), Err(AudioError::Encode(_)))); +} + +/// Blocks that do not fit, and calls after `finish`, are errors that leave the stream as it was. +#[test] +fn misuse_is_an_error() { + let mut enc = PacketEncoder::new(CodecId::Aac, &EncodeOptions::new(EncodeFormat::Aac), 48_000, 2).unwrap(); + let short = [vec![0.0f32; 10], vec![0.0; 5]]; + assert!(matches!(enc.encode(&short, 10), Err(AudioError::Encode(_)))); + assert!(matches!(enc.encode(&short[..1], 5), Err(AudioError::Encode(_)))); + assert_eq!(enc.frames(), 0); + assert!(enc.encode(&short, 5).unwrap().is_empty()); + assert_eq!(enc.finish().unwrap().len(), 2, "5 frames after 1024 of priming fit in two packets"); + assert!(matches!(enc.finish(), Err(AudioError::Encode(_)))); + assert!(matches!(enc.encode(&short, 5), Err(AudioError::Encode(_)))); + // An encoder given nothing returns nothing: no packets, no frames and no padding. `priming` + // is the codec's delay either way, so it equals that of an encoder that was given input. + for codec in [CodecId::Aac, CodecId::Alac, CodecId::Mp3, CodecId::Ac3, CodecId::Eac3, CodecId::Opus] { + let mut enc = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap(); + assert!(enc.finish().unwrap().is_empty(), "{codec:?}"); + assert_eq!((enc.frames(), enc.padding()), (0, 0), "{codec:?}"); + let mut fed = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap(); + fed.encode(&short, 5).unwrap(); + fed.finish().unwrap(); + assert_eq!(enc.priming(), fed.priming(), "{codec:?}"); + } +} diff --git a/crates/audio/tests/main.rs b/crates/audio/tests/main.rs index 5470dc5530..6e1461348b 100644 --- a/crates/audio/tests/main.rs +++ b/crates/audio/tests/main.rs @@ -36,6 +36,9 @@ mod mp2_encoder_oracle; #[cfg(feature = "qoa")] #[path = "qoa_oracle.rs"] mod qoa_oracle; +#[cfg(feature = "s302m")] +#[path = "s302m_oracle.rs"] +mod s302m_oracle; #[cfg(feature = "sbc")] #[path = "sbc_oracle.rs"] mod sbc_oracle; diff --git a/crates/audio/tests/s302m_oracle.rs b/crates/audio/tests/s302m_oracle.rs new file mode 100644 index 0000000000..1d1a0c60da --- /dev/null +++ b/crates/audio/tests/s302m_oracle.rs @@ -0,0 +1,240 @@ +//! SMPTE 302M (feature `s302m`) against ffmpeg (oracle; skipped when ffmpeg is absent, a failure +//! with `CRAFT_MEDIA_REQUIRE_ORACLES=1`): we decode the packets ffmpeg's encoder puts in a transport +//! stream to the samples ffmpeg decodes, our encoder writes the same bytes, and ffmpeg decodes +//! packets of ours (patched into a transport stream) to our samples. + +use craft_audio::s302m::{Encoder, decode, parse_header}; +use std::path::Path; +use std::process::Command; + +fn signal(channels: usize, frames: usize, seed: u32) -> Vec { + let mut x = seed | 1; + let mut out = Vec::with_capacity(frames * channels); + for i in 0..frames { + for c in 0..channels { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + let tone = ((i as f64) * (0.03 + 0.011 * c as f64)).sin() * 0.6; + let noise = f64::from(x % 2000) / 2000.0 - 0.5; + out.push(((tone + 0.3 * noise) * f64::from(i32::MAX)) as i32); + } + } + out +} + +#[test] +fn round_trips_every_size_and_channel_count() { + for channels in [2usize, 4, 6, 8] { + for bits in [16u32, 20, 24] { + let max = 1i64 << (bits - 1); + let mut e = Encoder::new(channels, bits).expect("encoder"); + let frames = 500; + let samples: Vec = signal(channels, frames, 3).iter().map(|&v| (i64::from(v) * max / (1 << 31)) as i32).collect(); + let mut all = Vec::new(); + for chunk in samples.chunks(channels * 193) { + let p = e.encode(chunk).expect("encode"); + let d = decode(&p).expect("decode"); + assert_eq!((d.header.channels, d.header.bits), (channels, bits)); + all.extend(d.samples); + } + assert_eq!(all, samples, "{channels}ch {bits} bits"); + } + } + // the extremes + for bits in [16u32, 20, 24] { + let (lo, hi) = (-(1i32 << (bits - 1)), (1i32 << (bits - 1)) - 1); + let mut e = Encoder::new(2, bits).expect("encoder"); + assert_eq!(decode(&e.encode(&[lo, hi, hi, lo, 0, -1]).expect("encode")).expect("decode").samples, vec![lo, hi, hi, lo, 0, -1]); + assert!(e.encode(&[hi + 1, 0]).is_err()); + assert!(e.encode(&[lo - 1, 0]).is_err()); + } +} + +#[test] +fn the_packet_size_limit_and_headers_are_checked() { + let mut e = Encoder::new(2, 16).expect("encoder"); + let max = e.max_frames(); + assert!(e.encode(&vec![0; max * 2]).is_ok()); + assert!(e.encode(&vec![0; (max + 1) * 2]).is_err()); + let p = Encoder::new(8, 24).expect("encoder").channel_id(0x55).encode(&[0; 8]).expect("encode"); + let h = parse_header(&p).expect("header"); + assert_eq!((h.channels, h.channel_id, h.bits, h.audio_bytes), (8, 0x55, 24, 28)); + assert_eq!(h.frame_bytes(), 28); +} + +#[test] +fn damaged_packets_are_errors_never_panics() { + let mut e = Encoder::new(4, 24).expect("encoder"); + let p = e.encode(&signal(4, 40, 5).iter().map(|&v| v >> 8).collect::>()).expect("encode"); + for n in 0..p.len() { + let _ = decode(&p[..n]); + } + let mut x = 9u32; + for i in 0..p.len() { + let mut d = p.clone(); + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + d[i] ^= (x >> 8) as u8 | 1; + let _ = decode(&d); + } + assert!(decode(&[]).is_err()); + assert!(decode(&[0xFF, 0xFF, 0, 0, 1, 2, 3]).is_err()); + assert!(decode(&[0, 5, 0, 0x30, 0, 0, 0, 0, 0]).is_err(), "the reserved size code"); +} + +// ---- ffmpeg as the reference + +fn ffmpeg(ff: &Path, args: &[&str]) { + let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +fn s(p: &Path) -> String { + p.to_str().expect("path").to_string() +} + +/// The elementary-stream bytes of every PES packet of PID 0x100 in a transport stream, each as +/// the list of (offset in the file, length) pieces it is spread over. +fn pes_pieces(ts: &[u8]) -> Vec> { + let mut out: Vec> = Vec::new(); + for (i, p) in ts.as_chunks::<188>().0.iter().enumerate() { + if p[0] != 0x47 || ((usize::from(p[1] & 0x1F) << 8) | usize::from(p[2])) != 0x100 { + continue; + } + let mut off = 4; + if p[3] & 0x20 != 0 { + off += 1 + usize::from(p[4]); + } + if p[3] & 0x10 == 0 || off >= 188 { + continue; + } + let mut start = off; + if p[1] & 0x40 != 0 { + // a new PES packet: skip its header (00 00 01 id, length, flags, flags, header length, header) + assert_eq!(&p[off..off + 3], &[0, 0, 1]); + start = off + 9 + usize::from(p[off + 8]); + out.push(Vec::new()); + } + if let Some(last) = out.last_mut() { + last.push((i * 188 + start, 188 - start)); + } + } + out +} + +fn gather(ts: &[u8], pieces: &[(usize, usize)]) -> Vec { + pieces.iter().flat_map(|&(o, n)| ts[o..o + n].iter().copied()).collect() +} + +fn pcm_bytes(samples: &[i32], wide: bool) -> Vec { + if wide { + samples.iter().flat_map(|v| v.to_le_bytes()).collect() + } else { + samples.iter().flat_map(|&v| ((v >> 16) as i16).to_le_bytes()).collect() + } +} + +fn decoded_by_ffmpeg(ff: &Path, ts: &Path, out: &Path, wide: bool) -> Vec { + ffmpeg(ff, &["-i", &s(ts), "-f", if wide { "s32le" } else { "s16le" }, "-acodec", if wide { "pcm_s32le" } else { "pcm_s16le" }, &s(out)]); + let bytes = std::fs::read(out).expect("read"); + if wide { + bytes.as_chunks::<4>().0.iter().map(|b| i32::from_le_bytes(*b)).collect() + } else { + bytes.as_chunks::<2>().0.iter().map(|b| i32::from(i16::from_le_bytes(*b))).collect() + } +} + +#[test] +fn we_decode_and_encode_what_ffmpeg_encodes_and_ffmpeg_decodes_ours() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("s302m"); + for (channels, bits) in [(2usize, 16u32), (2, 20), (2, 24), (4, 20), (4, 24), (6, 16), (6, 20), (8, 20), (8, 24)] { + let name = format!("{channels}ch{bits}"); + let frames = 6000; + let wide = bits > 16; + let pcm = signal(channels, frames, 17); + let raw = dir.join(format!("{name}.pcm")); + std::fs::write(&raw, pcm_bytes(&pcm, wide)).expect("write"); + let ts = dir.join(format!("{name}.ts")); + let ch_str = channels.to_string(); + let raw_str = s(&raw); + let ts_str = s(&ts); + let mut ff_args = vec![ + "-f", + if wide { "s32le" } else { "s16le" }, + "-ar", + "48000", + "-ac", + &ch_str, + "-i", + &raw_str, + "-af", + "asetnsamples=n=1024:p=0", + "-c:a", + "s302m", + "-strict", + "-2", + ]; + if bits == 20 { + ff_args.extend(["-bits_per_raw_sample", "20"]); + } + ff_args.extend(["-f", "mpegts", &ts_str]); + ffmpeg(&ff, &ff_args); + let bytes = std::fs::read(&ts).expect("read"); + let pieces = pes_pieces(&bytes); + assert!(pieces.len() >= 2, "{name}: {} packets", pieces.len()); + let theirs = decoded_by_ffmpeg(&ff, &ts, &dir.join(format!("{name}.out.pcm")), wide); + + let mut enc = Encoder::new(channels, bits).expect("encoder"); + let mut ours: Vec = Vec::new(); + let mut frames_seen = 0usize; + for pes in &pieces { + // the ES bytes of the packet: its own size field says how much of them is the packet + let es = gather(&bytes, pes); + let h = parse_header(&es).expect("header"); + let packet = &es[..4 + h.audio_bytes]; + let d = decode(packet).expect("decode"); + assert_eq!((d.header.channels, d.header.bits), (channels, bits), "{name}"); + // our encoder writes the same bytes ffmpeg's does + assert!(enc.encode(&d.samples).expect("encode") == packet, "{name}: our packet differs from ffmpeg's at frame {frames_seen}"); + frames_seen += d.samples.len() / channels; + // 20-bit and 24-bit samples are scaled to 32 bits by ffmpeg's decoder; 16-bit ones are not + ours.extend(d.samples.iter().map(|&v| if bits == 16 { v } else { v << (32 - bits) })); + } + let n = ours.len().min(theirs.len()); + assert!(n >= (frames - 1600) * channels, "{name}: {n} samples"); + assert!(ours[..n] == theirs[..n], "{name}: our decode differs from ffmpeg's"); + + // ffmpeg decodes our packets: patch them over the same-sized ones in the stream + let mine = signal(channels, frames, 23); + let mut patched = bytes.clone(); + let mut enc = Encoder::new(channels, bits).expect("encoder"); + let mut expect: Vec = Vec::new(); + for pes in &pieces { + let es = gather(&bytes, pes); + let h = parse_header(&es).expect("header"); + let n_frames = h.audio_bytes / h.frame_bytes(); + let at = expect.len(); + let src: Vec = mine[at..at + n_frames * channels].iter().map(|&v| v >> (32 - bits)).collect(); + let packet = enc.encode(&src).expect("encode"); + assert_eq!(packet.len(), 4 + h.audio_bytes); + expect.extend(src.iter().map(|&v| if bits == 16 { v } else { v << (32 - bits) })); + let mut k = 0; + for &(o, len) in pes { + let take = len.min(packet.len() - k); + patched[o..o + take].copy_from_slice(&packet[k..k + take]); + k += take; + } + assert!(k >= packet.len()); + } + let ours_ts = dir.join(format!("{name}.ours.ts")); + std::fs::write(&ours_ts, patched).expect("write"); + let theirs = decoded_by_ffmpeg(&ff, &ours_ts, &dir.join(format!("{name}.ours.pcm")), wide); + let n = expect.len().min(theirs.len()); + assert!(n >= (frames - 1600) * channels, "{name}: {n} samples"); + assert!(expect[..n] == theirs[..n], "{name}: ffmpeg decodes our packets differently"); + println!("{name}: {} PES packets, {n} samples identical both ways", pieces.len()); + } +} diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index 6cca4325a2..9238151b96 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -3,8 +3,8 @@ use std::net::TcpListener; use std::path::PathBuf; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, mpsc}; use std::time::Duration; use craft_automation::agents::AgentLinkStatus; @@ -17,7 +17,6 @@ use craft_automation::ui::agents::AgentsPage; use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles}; use craft_ui::contract::Role; use craft_ui::patterns::preferences::SettingsDraft; -use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use craft_ui::testing::Fixture; use craft_ui::testing::trial; @@ -29,16 +28,40 @@ fn temp_dir(tag: &str) -> tempfile::TempDir { tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") } -/// Waits up to five seconds for `done`. -fn wait_for(mut done: impl FnMut() -> bool) -> bool { - let started = motion::now(); - while !done() { - if started.elapsed() > Duration::from_secs(5) { - return false; +/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns once the thread has +/// finished it and waits for the next. +struct Ticks { + tick: mpsc::SyncSender<()>, + waiting: mpsc::Receiver<()>, +} + +impl Ticks { + /// The clock and the `tick` to give [`AgentSwitch::watch_with`]. + fn new() -> (Self, impl FnMut() -> bool + Send + 'static) { + let (tick, ticks) = mpsc::sync_channel(0); + let (waits, waiting) = mpsc::channel(); + let wait = move || { + let _ = waits.send(()); + ticks.recv().is_ok() + }; + (Self { tick, waiting }, wait) + } + + /// Blocks until the watch thread waits for its next poll; `false` once the thread has ended. + fn waiting(&self) -> bool { + // A hang guard only: the thread answers at once, so the limit is never reached by a run that works. + match self.waiting.recv_timeout(Duration::from_secs(60)) { + Ok(()) => true, + Err(mpsc::RecvTimeoutError::Disconnected) => false, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"), } - std::thread::sleep(Duration::from_millis(5)); + } + + /// Runs one poll; `false` when the thread ended in it instead of waiting for the next one. + fn poll(&self) -> bool { + self.tick.send(()).unwrap(); + self.waiting() } - true } /// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent. @@ -52,8 +75,8 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() { assert!(!AgentSwitch::fixed(false, true).allows(false)); } -/// The switch follows the launcher's list within a poll, wakes the app once per change rather than once per poll, and -/// its thread ends once the last clone is dropped. +/// The switch follows the launcher's list at the next poll, wakes the app once per change rather than once per poll, +/// and its thread ends at the first poll after the last clone is dropped. #[trial] fn the_switch_wakes_once_per_change() { let launcher = Arc::new(AtomicBool::new(false)); @@ -72,28 +95,35 @@ fn the_switch_wakes_once_per_change() { wakes.fetch_add(1, Ordering::Relaxed); } }; - let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let (ticks, tick) = Ticks::new(); + let switch = AgentSwitch::watch_with(true, probe, tick, wake); let clone = switch.clone(); + assert!(ticks.waiting()); assert!(!switch.launcher()); + assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start"); launcher.store(true, Ordering::Relaxed); - assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(ticks.poll()); + assert!(clone.launcher(), "the switch follows the launcher"); assert!(switch.allows(false)); // Many polls with nothing changed. - let polled = probes.load(Ordering::Relaxed); - assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + for _ in 0..10 { + assert!(ticks.poll()); + } + assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll"); + assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll"); launcher.store(false, Ordering::Relaxed); - assert!(wait_for(|| !switch.launcher())); - assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert!(ticks.poll()); + assert!(!switch.launcher()); assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); drop(switch); + assert!(ticks.poll(), "a clone keeps the watch"); drop(clone); - // The thread sees the switch gone at its next poll and stops probing. - std::thread::sleep(Duration::from_millis(50)); - let after_drop = probes.load(Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(50)); - assert_eq!(probes.load(Ordering::Relaxed), after_drop, "the watch ended with the last switch"); + // The thread probes once more, sees the switch gone and ends, so nothing probes after it. + assert!(!ticks.poll(), "the watch ended with the last switch"); + assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended"); + assert_eq!(wakes.load(Ordering::Relaxed), 2); } /// A published connection reads back in its documented shape, and only the process that wrote it removes it. diff --git a/crates/behavior/src/dock/action.rs b/crates/behavior/src/dock/action.rs index 825e63292e..484b9f554f 100644 --- a/crates/behavior/src/dock/action.rs +++ b/crates/behavior/src/dock/action.rs @@ -340,6 +340,16 @@ pub enum Action

{ /// The destination. to: Target

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

, + }, } impl

Location

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

Action

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

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

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

DockPlacement

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

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

{ moving.column.groups.iter_mut().for_each(|group| group.height = height); } let index = place.group_index().ok_or(DockError::InvalidPlacement)?; - let groups = &mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups; + let column = self.column_mut(&place).ok_or(DockError::MissingTarget)?; + // Groups shown at a width of their own, in a floating window or an expanded column, keep it + // as the flyout width of the collapsed column they join. + if column.iconic + && !moving.column.iconic + && let Some(width) = moving.column.width + { + let flyout = (column.width != Some(width)).then_some(width); + moving.column.groups.iter_mut().for_each(|group| group.flyout_width = flyout); + } + let groups = &mut column.groups; let index = (index + usize::from(below)).min(groups.len()); groups.splice(index..index, moving.column.groups); Ok(()) diff --git a/crates/behavior/src/dock/inner.rs b/crates/behavior/src/dock/inner.rs index 93510d78a5..b213dd3177 100644 --- a/crates/behavior/src/dock/inner.rs +++ b/crates/behavior/src/dock/inner.rs @@ -145,6 +145,10 @@ impl Layout

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

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

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

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

Workspace

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

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

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

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

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

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

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

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

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

{ !drop }); self.hidden.truncate(MAX_PANELS); + self.drop_stale_floated(); } } diff --git a/crates/behavior/src/geometry/crop.rs b/crates/behavior/src/geometry/crop.rs index 7fa0422777..4704686970 100644 --- a/crates/behavior/src/geometry/crop.rs +++ b/crates/behavior/src/geometry/crop.rs @@ -544,7 +544,7 @@ const INV_PHI: f64 = 0.618_033_988_749_894_9; const PHI: f64 = 1.0 + INV_PHI; /// The composition guide drawn inside a crop frame, in Photoshop's menu order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropGuide { @@ -727,7 +727,7 @@ fn golden_spiral() -> Vec<[f64; 2]> { } /// When the guide shows. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum GuideShow { diff --git a/crates/behavior/src/quantity.rs b/crates/behavior/src/quantity.rs index 495b781c6d..af3c06e5d1 100644 --- a/crates/behavior/src/quantity.rs +++ b/crates/behavior/src/quantity.rs @@ -82,7 +82,8 @@ impl Reader { self } - /// The digit-group separator, which the reader skips between digits. + /// The digit-group separator, which the reader skips between digits. A comma or point after zero reads as a + /// decimal when it is the number's only separator and digits follow it. #[must_use] pub fn group(mut self, group: char) -> Self { self.group = Some(group); @@ -250,11 +251,6 @@ impl Parse<'_> { } } - /// Whether the group separator at `at` is followed by exactly three digits. - fn three_digits_after(&self, at: usize) -> bool { - self.chars[at + 1..].iter().take_while(|c| digit(**c).is_some()).count() == 3 - } - fn number(&mut self) -> Result { let mut text = String::new(); let mut seen_decimal = false; @@ -264,7 +260,16 @@ impl Parse<'_> { } else if c == self.reader.decimal && !seen_decimal { seen_decimal = true; text.push('.'); - } else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() && self.three_digits_after(self.at) { + } else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() { + let after = &self.chars[self.at + 1..]; + let digits = after.iter().take_while(|c| digit(**c).is_some()).count(); + let only_mark = after.get(digits).is_none_or(|&next| next != c && next != self.reader.decimal); + if text == "0" && matches!(c, '.' | ',') && digits > 0 && only_mark { + seen_decimal = true; + text.push('.'); + } else if digits != 3 { + break; + } } else { break; } @@ -281,6 +286,28 @@ impl Parse<'_> { mod tests { use super::*; + #[test] + fn a_single_group_mark_after_zero_reads_as_a_decimal() { + for (decimal, group) in [('.', ','), (',', '.')] { + let reader = Reader::new().decimal(decimal).group(group).unit("cm", 2.0); + for (text, want) in [ + (format!("0{group}125+2"), 2.125), + (format!("2x0{group}125"), 0.25), + (format!("-0{group}25 cm"), -0.5), + (format!("٠{group}١٢٥"), 0.125), + (format!("1{group}125"), 1125.0), + (format!("1{group}234{decimal}5"), 1234.5), + (format!("0{group}123{group}456"), 123456.0), + (format!("0{group}125{decimal}5"), 125.5), + ] { + assert_eq!(reader.read(&text, None), Ok(want), "{text}"); + } + assert_eq!(reader.read(&format!("0{group}"), None), Err(NotAValue)); + } + let swiss = Reader::new().group('\''); + assert_eq!(swiss.read("0'125", None), Ok(125.0)); + } + #[test] fn expressions_units_and_relative_input_read_through_one_grammar() { let reader = Reader::new().decimal(',').group('.').unit("in", 72.0).unit("pt", 1.0); diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 1985e4bf9c..12c36a01e3 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -66,6 +66,15 @@ pub struct Wheel { pub lines: Vec2, /// Zoom factor; 1 for none. pub zoom: f32, + /// The wheel motion that reached the share as `zoom` instead of `scroll`, in wheel lines: wheel events under the + /// zoom modifier, and the Ctrl+wheel steps the service reads as a touchpad's pinch on Windows and Linux. A line + /// event counts its lines (notches) as the device sent them, a point or page event its points over egui's line + /// scroll speed. It travels with the zoom share, so a taker can count the notches or lines of a Ctrl+wheel that + /// zooms without the zoom speed; zero for a native pinch and for a wheel without the modifier. + pub zoom_lines: Vec2, + /// The running gesture's `zoom_lines` gathered so far, this share included, for the taker that owns the gesture; + /// another taker's share gathers only itself, as with `gathered`. + pub zoom_gathered: Vec2, /// The modifiers held. pub mods: Mods, /// The unit the device reported. @@ -224,6 +233,8 @@ impl Wheel { scroll, lines: Vec2::ZERO, zoom: 1.0, + zoom_lines: Vec2::ZERO, + zoom_gathered: Vec2::ZERO, mods, unit, phase, @@ -245,6 +256,13 @@ impl Wheel { self } + /// The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`). + #[must_use] + pub const fn zoom_lines(mut self, lines: Vec2) -> Self { + self.zoom_lines = lines; + self + } + /// The same gesture with the two-finger touch zoom factor `zoom`. pub const fn touch_zoom(mut self, zoom: f32) -> Self { self.touch_zoom = zoom; @@ -563,13 +581,28 @@ fn for_field(wheel: &Wheel) -> bool { /// Whether `wheel` carries a pinch, a touch zoom, a rotation or a two-finger pan: the zoom share's values. fn pinches(wheel: &Wheel) -> bool { - wheel.zoom != 1.0 || wheel.touch_zoom != 1.0 || wheel.rotation != 0.0 || wheel.touch_rotation != 0.0 || wheel.touch_pan != Vec2::ZERO + wheel.zoom != 1.0 + || wheel.zoom_lines != Vec2::ZERO + || wheel.touch_zoom != 1.0 + || wheel.rotation != 0.0 + || wheel.touch_rotation != 0.0 + || wheel.touch_pan != Vec2::ZERO } /// `wheel` without the zoom share's values: a scroll share carries no pinch or rotation, so a field or a scroll region /// never reads one. const fn scroll_only(wheel: Wheel) -> Wheel { - Wheel { zoom: 1.0, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, touch_pan: Vec2::ZERO, zooms: false, ..wheel } + Wheel { + zoom: 1.0, + zoom_lines: Vec2::ZERO, + zoom_gathered: Vec2::ZERO, + touch_zoom: 1.0, + rotation: 0.0, + touch_rotation: 0.0, + touch_pan: Vec2::ZERO, + zooms: false, + ..wheel + } } /// The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes @@ -715,6 +748,7 @@ fn split_at( Some((_, share)) => { share.scroll += part.scroll; share.zoom *= part.zoom; + share.zoom_lines += part.zoom_lines; share.touch_zoom *= part.touch_zoom; share.rotation += part.rotation; share.touch_rotation += part.touch_rotation; diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index b6eea87da1..be5f2b3a8b 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -224,9 +224,10 @@ fn tabs_closed_together_reopen_together_and_a_tab_closed_alone_stays_closed() { assert_eq!(group_members(workspace.layout(), 2), [2, 3], "it reopens beside 2"); } -/// A panel that floats keeps its docked place until it docks or closes; floating again from the float keeps the first. +/// A panel that floats keeps its docked place until it docks; floating again from the float keeps the first, and a +/// float that closes keeps it while it is closed and after it reopens floating. #[test] -fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { +fn a_floated_panel_keeps_where_it_was_docked_until_it_docks() { let mut workspace = Workspace::new(docked()); let docked_at = workspace.layout().location(&2).unwrap(); workspace.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); @@ -235,10 +236,15 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { assert_eq!(workspace.floated(), [(2, docked_at)], "floating again from the float keeps the first record"); workspace.apply(Action::move_beside(2, 11, DockPlacement::tab(None)), false, allow).unwrap(); assert!(workspace.floated().is_empty(), "docking drops the record"); + let docked_at = workspace.layout().location(&3).unwrap(); workspace.apply(Action::float(3, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); - assert_eq!(workspace.floated().len(), 1); workspace.apply(Action::close(3), false, allow).unwrap(); - assert!(workspace.floated().is_empty(), "closing drops the record"); + assert_eq!(workspace.floated(), [(3, docked_at.clone())], "closing keeps the record"); + workspace.apply(Action::open(3, None), false, allow).unwrap(); + assert!(floats(workspace.layout(), 3), "it reopens floating"); + assert_eq!(workspace.floated(), [(3, docked_at.clone())], "reopening keeps the record"); + workspace.apply(Action::restore(3, docked_at), false, allow).unwrap(); + assert!(!floats(workspace.layout(), 3) && workspace.floated().is_empty(), "docking back drops the record"); } /// A closed panel that floats by itself records the place it would reopen at, as opening it first records, and its old @@ -313,6 +319,45 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare assert_eq!(floated.edge, None, "an expanded column keeps to the edge nearer its rect"); } +/// A group docked into a collapsed column keeps the width it was shown at as its flyout width: a floating window's +/// width, or an expanded column's. A width equal to the column's leaves the flyout following the column, and a group +/// moved between collapsed columns keeps its own flyout width. +#[test] +fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width() { + let flyout = |layout: &Layout, panel: u32| layout.group(&layout.place(&panel).unwrap()).unwrap().flyout_width; + + let mut layout = columns(); + layout.apply(Action::move_floating(6, rect(100.0, 100.0, 420.0, 400.0))).unwrap(); + layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert!(!floats(&layout, 6) && column_of(&layout, 6).iconic); + assert_eq!(flyout(&layout, 6), Some(420.0), "the floating window's width"); + + layout.apply(Action::resize_flyout_width(6, Some(380.0))).unwrap(); + layout.apply(Action::move_group(6, Target::float(rect(100.0, 100.0, 380.0, 400.0)))).unwrap(); + layout.apply(Action::set_iconic(6, false)).unwrap(); + layout.apply(Action::move_floating(6, rect(100.0, 100.0, 300.0, 400.0))).unwrap(); + layout.apply(Action::move_group(6, Target::at(4, DockPlacement::group(false, None)))).unwrap(); + assert_eq!(flyout(&layout, 6), Some(300.0), "the width the window was resized to, not the flyout width it left with"); + + let mut layout = columns(); + layout.apply(Action::resize_column(2, 260.0)).unwrap(); + layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 2), Some(260.0), "the expanded column's width"); + + let mut layout = columns(); + layout.apply(Action::resize_column(3, 300.0)).unwrap(); + layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 6), None, "a width equal to the column's follows the column"); + + let mut layout = columns(); + let start = Node::dock(DockEdge::Start, vec![Column::new(vec![g(&[7], 0)]).with_iconic(true)]); + let Some(root) = layout.root.take() else { panic!("no root") }; + layout.root = Some(Node::split(Axis::X, SplitSize::FixedFirst(48.0), start, root)); + layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap(); + layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 3), Some(350.0), "a group from another collapsed column keeps its own"); +} + /// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a /// column float in its state; groups joining a column, docked or floating, take that column's state. #[test] diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index 4a4e27520f..7259d7212d 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-captions" -description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML/IMSC1/DFXP readers and writers with exact time, and CEA-608/708 coding" +description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL, ASS, TTML/IMSC1/DFXP and the legacy text formats (MicroDVD, MPL2, SubViewer, VPlayer, SAMI) readers and writers with exact time, and CEA-608/708 coding" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/captions/README.md b/crates/captions/README.md index b2f6a195f0..4568526750 100644 --- a/crates/captions/README.md +++ b/crates/captions/README.md @@ -60,6 +60,11 @@ lists at most 20 characters per stream. | TTML `.ttml` (IMSC1) | yes | yes | Writes the IMSC1 Text profile (TTML2 namespaces) with the document's language as `xml:lang` (read back on import): `

` per cue, `
`, styled ``s for `` / `` / ``, `ttm:agent` speakers, exact frame times (`123f`) at the sequence rate. Reads any TTML (TTML1, TTML2, the 2006 `ttaf1` drafts): clock / frame / offset / tick times, `dur`, nested time containers (`body` / `div` begins offset and ends clip their contents; `seq` containers are read as `par` with a warning), timed spans, referenced styles. | | DFXP `.dfxp` | yes | yes | TTML1 with the DFXP presentation profile; clock times in milliseconds (frame-exact after `snap_to_frames`). | | ASS / SSA `.ass`, `.ssa` | yes | yes (ASS v4+) | The `[Events]` section: `Dialogue:` lines through the file's `Format:` line, `Name` as the speaker, `\N`, `\n`, `\h` and the `\i`, `\b`, `\u` override tags kept (as ``, ``, ``); other override tags and drawing lines are dropped. Times are centiseconds. Written files have one `Default` style. | +| MicroDVD `.sub` | yes | yes | `{first}{last}text` with frame numbers; the `{1}{1}fps` line or 23.976 fps. `\|` breaks a line; `{y:i,b,u}` and `{c:$BBGGRR}` style a line (capital `Y` / `C`: the rest of the cue too); other controls are dropped. Writing always names the rate (`WriteOptions::rate`, 23.976 by default) and styles only a line that ``, `` or `` wraps whole. | +| MPL2 `.mpl` | yes | yes | `[start][end]text` in tenths of a second; `\|` breaks a line, a leading `/` makes it italic. | +| SubViewer 2 `.sbv` (also `.sub`) | yes | yes | `start,end` in hundredths of a second after the `[INFORMATION]` header; `[br]` breaks a line. Text only; no styles. | +| VPlayer `.vpl` (also `.txt`) | yes | yes | `HH:MM:SS[.cc]=text` (`:` or a space also separate); only start times, a caption lasts to the next line (empty text clears), four seconds for the last. Text only. | +| SAMI `.smi` | yes | yes | `` blocks, ` ` clears; `
`, ``, ``, ``, `` kept; first language class only. | All cue times are exact `Tick`s. Milliseconds convert exactly (1 ms = 254 016 000 ticks); SCC frames map through `FrameRate::FPS_29_97`. `Document::snap_to_frames` snaps cues to a frame grid and diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index 612aa6f137..4251b79efb 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -4,7 +4,7 @@ //! - **Files:** [SubRip](srt) (`.srt`), [WebVTT](vtt) (`.vtt`), [Scenarist SCC](scc) (`.scc`, //! CEA-608 pop-on, roll-up and paint-on on read; pop-on on write), [MacCaption MCC](mcc) //! (`.mcc`, SMPTE ST 334-2 packets with CEA-608 and CEA-708), [EBU STL](stl) (`.stl`, EBU -//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a +//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`), the legacy text formats [MicroDVD](microdvd) (`.sub`), [MPL2](mpl2) (`.mpl`), [SubViewer 2](subviewer) (`.sub`), [VPlayer](vplayer) (`.vpl`) and [SAMI](sami) (`.smi`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a //! [`Document`] of [`Cue`]s and write back. Readers are forgiving (BOM, UTF-16, Windows-1252 //! fallback, CRLF/CR, missing SRT indexes, `,` or `.` milliseconds, missing hours, no blank //! line between cues); writers are strict. WebVTT cue identifiers, cue settings, `` @@ -36,17 +36,22 @@ pub mod ass; pub mod cea608; pub mod jacosub; pub mod mcc; +pub mod microdvd; #[cfg(feature = "mov-text")] pub mod mov_text; +pub mod mpl2; pub mod pjs; pub mod realtext; +pub mod sami; pub mod scc; pub mod srt; pub mod stl; +pub mod subviewer; mod text; /// Exact time: `craft-timeline`'s ticks, frame rates and timecode fields. pub use craft_timeline::time; pub mod ttml; +pub mod vplayer; pub mod vtt; pub use text::{decode_entities, entity_at, plain_text}; @@ -77,6 +82,16 @@ pub enum Format { Dfxp, /// Advanced SubStation Alpha (also reads SubStation Alpha). Ass, + /// MicroDVD (frame-numbered text). + MicroDvd, + /// MPL2 (times in tenths of a second). + Mpl2, + /// SubViewer 2. + SubViewer, + /// VPlayer (start times only). + VPlayer, + /// SAMI (HTML-like). + Sami, /// Phoenix Japanimation Society (PJS) subtitles. Pjs, /// RealText streaming timed text markup. @@ -86,7 +101,7 @@ pub enum Format { } impl Format { - pub const ALL: [Format; 11] = [ + pub const ALL: [Format; 16] = [ Format::Srt, Format::WebVtt, Format::Scc, @@ -95,6 +110,11 @@ impl Format { Format::Ttml, Format::Dfxp, Format::Ass, + Format::MicroDvd, + Format::Mpl2, + Format::SubViewer, + Format::VPlayer, + Format::Sami, Format::Pjs, Format::RealText, Format::JacoSub, @@ -109,6 +129,11 @@ impl Format { Format::Ttml => "TTML (IMSC1)", Format::Dfxp => "DFXP (TTML1)", Format::Ass => "Advanced SubStation Alpha (ASS)", + Format::MicroDvd => "MicroDVD", + Format::Mpl2 => "MPL2", + Format::SubViewer => "SubViewer 2", + Format::VPlayer => "VPlayer", + Format::Sami => "SAMI", Format::Pjs => "PJS", Format::RealText => "RealText", Format::JacoSub => "JACOsub", @@ -124,6 +149,12 @@ impl Format { Format::Ttml => "ttml", Format::Dfxp => "dfxp", Format::Ass => "ass", + Format::MicroDvd => "sub", + Format::Mpl2 => "mpl", + // SubViewer files are `.sub` too, as MicroDVD ones are; `.sbv` tells the two apart. + Format::SubViewer => "sbv", + Format::VPlayer => "vpl", + Format::Sami => "smi", Format::Pjs => "pjs", Format::RealText => "rt", Format::JacoSub => "jss", @@ -139,6 +170,11 @@ impl Format { "ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml), "dfxp" => Some(Format::Dfxp), "ass" | "ssa" => Some(Format::Ass), + "sub" | "microdvd" => Some(Format::MicroDvd), + "mpl" | "mpl2" => Some(Format::Mpl2), + "subviewer" | "sbv" => Some(Format::SubViewer), + "vplayer" | "vpl" => Some(Format::VPlayer), + "smi" | "sami" => Some(Format::Sami), "pjs" => Some(Format::Pjs), "rt" | "realtext" => Some(Format::RealText), "jss" | "js" | "jacosub" => Some(Format::JacoSub), @@ -292,28 +328,53 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if head.starts_with("[Script Info]") { return Some(Format::Ass); } + if head.get(..5).is_some_and(|h| h.eq_ignore_ascii_case("' || b == b'/') + { + return Some(Format::Sami); + } + if subviewer::is_header(head) { + return Some(Format::SubViewer); + } if realtext::is_realtext(head) { return Some(Format::RealText); } + let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase()); + let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some()); let first_lines: Vec<&str> = head.lines().map(str::trim).filter(|l| !l.is_empty()).take(3).collect(); + if first_lines.first().is_some_and(|l| microdvd::is_cue(l)) { + return Some(Format::MicroDvd); + } + if first_lines.first().is_some_and(|l| mpl2::split_cue(l).is_some()) { + return Some(Format::Mpl2); + } + if ext.as_deref() != Some("srt") && !has_arrow_timing && first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) { + return Some(Format::SubViewer); + } + if !first_lines.is_empty() + && head.lines().map(str::trim_start).filter(|line| !line.trim().is_empty()).take(3).all(|line| vplayer::split_line(line).is_some()) + { + return Some(Format::VPlayer); + } if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) { return Some(Format::Pjs); } if first_lines.iter().any(|l| jacosub::is_timed_line(l)) || (head.starts_with('#') && (head.contains("TimeRes") || head.contains("#T"))) { return Some(Format::JacoSub); } - let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase()); if (head.starts_with('<') && (head.contains("") || head.contains(":tt "))) && (head.contains("ns/ttml") || head.contains("ttaf1")) { let legacy = head.contains("ttaf1") || head.contains("dfxp"); return Some(if ext.as_deref() == Some("dfxp") || (legacy && ext.as_deref() != Some("ttml")) { Format::Dfxp } else { Format::Ttml }); } - let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some()); match ext.as_deref() { Some("srt") if has_arrow_timing || head.is_empty() => Some(Format::Srt), Some("vtt") if has_arrow_timing => Some(Format::WebVtt), - Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "pjs" | "rt" | "jss" | "js") => None, + Some( + "srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "sub" | "mpl" | "vpl" | "smi" | "sami" | "pjs" | "rt" + | "jss" | "js", + ) => None, _ if has_arrow_timing => Some(Format::Srt), _ => None, } @@ -348,6 +409,11 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result { Format::Mcc => mcc::parse(&text), Format::Ttml | Format::Dfxp => ttml::parse(&text), Format::Ass => ass::parse(&text), + Format::MicroDvd => microdvd::parse(&text), + Format::Mpl2 => mpl2::parse(&text), + Format::SubViewer => subviewer::parse(&text), + Format::VPlayer => vplayer::parse(&text), + Format::Sami => sami::parse(&text), Format::Pjs => pjs::parse(&text), Format::RealText => realtext::parse(&text), Format::JacoSub => jacosub::parse(&text), @@ -389,6 +455,11 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec { Format::Ttml => ttml::write(doc, ttml::Flavor::Imsc1, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), Format::Dfxp => ttml::write(doc, ttml::Flavor::Dfxp, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), Format::Ass => ass::write(doc).into_bytes(), + Format::MicroDvd => microdvd::write(doc, opts.rate).into_bytes(), + Format::Mpl2 => mpl2::write(doc).into_bytes(), + Format::SubViewer => subviewer::write(doc).into_bytes(), + Format::VPlayer => vplayer::write(doc).into_bytes(), + Format::Sami => sami::write(doc).into_bytes(), Format::Pjs => pjs::write(doc).into_bytes(), Format::RealText => realtext::write(doc).into_bytes(), Format::JacoSub => jacosub::write(doc).into_bytes(), diff --git a/crates/captions/src/microdvd.rs b/crates/captions/src/microdvd.rs new file mode 100644 index 0000000000..5816373712 --- /dev/null +++ b/crates/captions/src/microdvd.rs @@ -0,0 +1,241 @@ +//! MicroDVD (`.sub`): frame-numbered text. +//! +//! ```text +//! {1}{1}23.976 +//! {24}{72}First line|{y:i}second line in italics +//! ``` +//! +//! A line is `{first frame}{last frame}text`; `|` starts a new line. A first cue `{1}{1}` or `{0}{0}` +//! whose text is a number gives the frame rate; without it the rate is 23.976 fps (the rate other +//! readers assume). Control codes `{y:i}` / `{y:b}` / `{y:u}` (italic, bold, underline; `i,b` together) +//! and `{c:$BBGGRR}` (colour) style the line they start; the capital forms `{Y:…}` and `{C:…}` +//! style every later line of the cue too. Other controls (`{f:…}` font, `{s:…}` size, `{h:…}`, …) +//! are dropped. Writing always starts with the `{1}{1}` rate line and styles a line only when +//! ``, `` or `` wraps all of it; other tags are dropped, and `{`, `}` and `|` in the +//! text become the full-width `{`, `}` and `|`. + +use crate::text::{LineStyle, escape_markup, number, plain_text, whole_line_style, wrap_style}; +use crate::time::FrameRate; +use crate::{Cue, Document, Error, Result}; + +/// The frame rate of a file that does not name one. +pub const DEFAULT_RATE: FrameRate = FrameRate::FPS_23_976; + +/// `{a}{b}text` as its parts. +fn split_cue(line: &str) -> Option<(i64, i64, &str)> { + let rest = line.strip_prefix('{')?; + let (a, rest) = rest.split_once('}')?; + let rest = rest.strip_prefix('{')?; + let (b, text) = rest.split_once('}')?; + Some((number(a.trim())?, number(b.trim())?, text)) +} + +/// Whether `line` is a `{first}{last}text` cue line. +pub(crate) fn is_cue(line: &str) -> bool { + split_cue(line).is_some() +} + +/// The frame rate a header cue's text names. +fn header_rate(text: &str) -> Option { + let fps: f64 = text.trim().parse().ok()?; + (fps.is_finite() && (1.0..=1000.0).contains(&fps)).then(|| FrameRate::from_f64(fps)) +} + +/// A `$BBGGRR` colour as `#rrggbb`. +fn colour(value: &str) -> Option { + let hex = value.trim().strip_prefix('$')?; + if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let (b, rest) = hex.split_at(2); + let (g, r) = rest.split_at(2); + Some(format!("#{}{}{}", r.to_ascii_lowercase(), g.to_ascii_lowercase(), b.to_ascii_lowercase())) +} + +/// What the styling controls of a cue's lines set. +#[derive(Default)] +struct Sticky { + style: LineStyle, + colour: Option, +} + +/// The text of one line without its `{x:…}` controls, and the controls in order. +fn split_controls(line: &str) -> (String, Vec<(char, String)>) { + let mut text = String::new(); + let mut controls = Vec::new(); + let mut rest = line; + while let Some(open) = rest.find('{') { + text.push_str(rest.get(..open).unwrap_or("")); + let after = rest.get(open + 1..).unwrap_or(""); + // Check the fixed-size control prefix before scanning its body. Invalid opening + // braces must not repeatedly scan the same suffix for a closing brace. + let name = after.as_bytes().first().copied().filter(u8::is_ascii_alphabetic); + if let Some(name) = name.filter(|_| after.as_bytes().get(1) == Some(&b':')) { + if let Some((body, tail)) = after.get(2..).and_then(|s| s.split_once('}')) { + controls.push((char::from(name), body.to_string())); + rest = tail; + } else { + // No later control can close either: preserve the entire remaining text. + text.push('{'); + text.push_str(after); + rest = ""; + break; + } + } else { + text.push('{'); + rest = after; + } + } + text.push_str(rest); + (text, controls) +} + +fn apply_style(value: &str, style: &mut LineStyle) { + for flag in value.split([',', ' ', '/']) { + match flag.trim().to_ascii_lowercase().as_str() { + "i" => style.italic = true, + "b" => style.bold = true, + "u" => style.underline = true, + _ => {} + } + } +} + +fn cue_text(raw: &str) -> String { + let mut sticky = Sticky::default(); + let mut lines = Vec::new(); + for line in raw.split('|') { + let (text, controls) = split_controls(line); + let mut style = sticky.style; + let mut line_colour = sticky.colour.clone(); + for (name, value) in controls { + match name { + 'y' => apply_style(&value, &mut style), + 'Y' => { + apply_style(&value, &mut style); + apply_style(&value, &mut sticky.style); + } + 'c' => line_colour = colour(&value).or(line_colour), + 'C' => { + line_colour = colour(&value).or(line_colour); + sticky.colour = line_colour.clone(); + } + _ => {} + } + } + let text = text.trim(); + if text.is_empty() { + continue; + } + lines.push(wrap_style(style, line_colour.as_deref(), &escape_markup(text))); + } + lines.join("\n") +} + +pub fn parse(text: &str) -> Result { + let mut rows = Vec::new(); + let mut rate = DEFAULT_RATE; + let mut has_rate_line = false; + let mut doc = Document::default(); + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + match split_cue(line) { + Some((0, 0, t) | (1, 1, t)) if rows.is_empty() && !has_rate_line && header_rate(t).is_some() => { + rate = header_rate(t).unwrap_or(rate); + has_rate_line = true; + } + Some(row) => rows.push(row), + None => doc.warnings.push(format!("line {}: not a MicroDVD cue, skipped", n + 1)), + } + } + if rows.is_empty() && !has_rate_line && !text.trim().is_empty() { + return Err(Error::NotFormat("MicroDVD")); + } + for (first, last, raw) in rows { + let (start, end) = (rate.tick_of(first), rate.tick_of(last)); + let text = cue_text(raw); + if end <= start || text.is_empty() { + doc.warnings.push(format!("the cue at frame {first} is empty or ends at frame {last}; skipped")); + continue; + } + doc.cues.push(Cue { start, end, text, ..Default::default() }); + } + Ok(doc) +} + +/// Write `doc` with its frames counted at `rate` (None: [`DEFAULT_RATE`]). +pub fn write(doc: &Document, rate: Option) -> String { + let rate = rate.map_or(DEFAULT_RATE, FrameRate::sane); + let mut out = format!("{{1}}{{1}}{:.3}\n", rate.as_f64()); + let frame = |t| rate.frame_at(rate.snap_nearest(t)).max(0); + for c in &doc.cues { + let first = frame(c.start); + let last = frame(c.end).max(first.saturating_add(1)); + let mut lines = Vec::new(); + for line in c.text.lines() { + let (style, inner) = whole_line_style(line); + let text = plain_text(inner).trim().replace('{', "\u{ff5b}").replace('}', "\u{ff5d}").replace('|', "\u{ff5c}"); + if text.is_empty() { + continue; + } + let mut flags = Vec::new(); + for (on, f) in [(style.italic, "i"), (style.bold, "b"), (style.underline, "u")] { + if on { + flags.push(f); + } + } + lines.push(if flags.is_empty() { text } else { format!("{{y:{}}}{text}", flags.join(",")) }); + } + if lines.is_empty() { + continue; + } + out.push_str(&format!("{{{first}}}{{{last}}}{}\n", lines.join("|"))); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn controls_style_lines() { + assert_eq!(cue_text("{y:i,b}x|plain"), "x\nplain"); + assert_eq!(cue_text("{Y:i}a|b"), "a\nb"); + assert_eq!(cue_text("{c:$0000ff}red"), "red"); + assert_eq!(cue_text("{f:Arial}{s:20}a & b {x"), "a & b {x"); + } + + #[test] + fn malformed_controls_inside_valid_cues_are_preserved() { + for raw in ["{".repeat(32_768), "{y:".repeat(16_384)] { + let doc = parse(&format!("{{0}}{{25}}{raw}")).unwrap(); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].text, raw); + } + assert_eq!(cue_text("{{y:i}hello"), "{hello"); + assert_eq!(cue_text("{xx:no}{y:b}hello"), "{xx:no}hello"); + } + + #[test] + fn rate_header() { + let d = parse("{1}{1}25.000\n{25}{50}x\n").unwrap(); + assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25)); + let d = parse("{0}{0}25.000\n{25}{50}x\n{50}{75}29.97\n").unwrap(); + assert_eq!(d.cues.len(), 2); + assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25)); + assert_eq!(d.cues[1].start, FrameRate::FPS_25.tick_of(50)); + assert_eq!(d.cues[1].text, "29.97"); + let d = parse("{25}{50}x\n").unwrap(); + assert_eq!(d.cues[0].start, DEFAULT_RATE.tick_of(25)); + } + + #[test] + fn rejects_other_text() { + assert!(parse("hello\nworld\n").is_err()); + assert!(parse("").unwrap().cues.is_empty()); + } +} diff --git a/crates/captions/src/mpl2.rs b/crates/captions/src/mpl2.rs new file mode 100644 index 0000000000..b7613f073d --- /dev/null +++ b/crates/captions/src/mpl2.rs @@ -0,0 +1,114 @@ +//! MPL2 (`.txt`, `.mpl`): times in tenths of a second. +//! +//! ```text +//! [10][35]First line|/second line in italics +//! ``` +//! +//! A line is `[start][end]text` with times in deciseconds. `|` starts a new line; a `/` at the +//! start of a line makes it italic. Writing marks a line italic only when `` wraps all of it, +//! drops other tags, rounds times to a tenth of a second, writes `|` in text as `|`, and writes +//! a leading `/` in non-italic text as `/`. + +use crate::text::{escape_markup, ms_to_tick, number, plain_text, tick_to_ms, whole_line_style, wrap_style}; +use crate::{Cue, Document, Error, Result}; + +/// `[a][b]text` as its parts. +pub(crate) fn split_cue(line: &str) -> Option<(i64, i64, &str)> { + let rest = line.strip_prefix('[')?; + let (a, rest) = rest.split_once(']')?; + let rest = rest.strip_prefix('[')?; + let (b, text) = rest.split_once(']')?; + Some((number(a.trim())?, number(b.trim())?, text)) +} + +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut found = false; + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let Some((a, b, raw)) = split_cue(line) else { + doc.warnings.push(format!("line {}: not an MPL2 cue, skipped", n + 1)); + continue; + }; + found = true; + let mut lines = Vec::new(); + for l in raw.split('|') { + let (italic, l) = match l.trim().strip_prefix('/') { + Some(r) => (true, r.trim().to_string()), + None => { + let t = l.trim(); + if let Some(rest) = t.strip_prefix('\u{ff0f}') { (false, format!("/{rest}")) } else { (false, t.to_string()) } + } + }; + if !l.is_empty() { + lines.push(wrap_style(crate::text::LineStyle { italic, ..Default::default() }, None, &escape_markup(&l))); + } + } + let (start, end) = (ms_to_tick(a.saturating_mul(100)), ms_to_tick(b.saturating_mul(100))); + if end <= start || lines.is_empty() { + doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1)); + continue; + } + doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() }); + } + if !found && !text.trim().is_empty() { + return Err(Error::NotFormat("MPL2")); + } + Ok(doc) +} + +pub fn write(doc: &Document) -> String { + let mut out = String::new(); + let ds = |t| (tick_to_ms(t) + 50) / 100; + for c in &doc.cues { + let start = ds(c.start); + let end = ds(c.end).max(start + 1); + let mut lines = Vec::new(); + for line in c.text.lines() { + let (style, inner) = whole_line_style(line); + let mut text = plain_text(inner).trim().replace('|', "\u{ff5c}"); + if !style.italic && text.starts_with('/') { + text.replace_range(..1, "\u{ff0f}"); + } + if !text.is_empty() { + lines.push(if style.italic { format!("/{text}") } else { text }); + } + } + if !lines.is_empty() { + out.push_str(&format!("[{start}][{end}]{}\n", lines.join("|"))); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn italics_and_lines() { + let d = parse("[10][35]Hello|/italic\n").unwrap(); + assert_eq!(d.cues[0].text, "Hello\nitalic"); + assert_eq!(d.cues[0].end, ms_to_tick(3500)); + } + + #[test] + fn rejects_other_text() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err()); + } + + #[test] + fn non_italic_leading_slash_roundtrip() { + let doc = Document { + cues: vec![Cue { start: ms_to_tick(1000), end: ms_to_tick(2000), text: "/not italic\n/italic".into(), ..Default::default() }], + ..Default::default() + }; + let written = write(&doc); + assert_eq!(written, "[10][20]/not italic|//italic\n"); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues[0].text, "/not italic\n/italic"); + } +} diff --git a/crates/captions/src/sami.rs b/crates/captions/src/sami.rs new file mode 100644 index 0000000000..29f8281dd9 --- /dev/null +++ b/crates/captions/src/sami.rs @@ -0,0 +1,323 @@ +//! SAMI (`.smi`, `.sami`): Microsoft's HTML-like captions. +//! +//! ```text +//! +//!

First line
second line +//!

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

`, `

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

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

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

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

Hello
world & you\n

 \n

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

{raw}

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

en

kr

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

Brief\n

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

Hello
world\n

 \n

plain & more\n

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

xy<<<<&&&&�&#x;".into(), + format!("{}", "".repeat(10_000)).into_bytes(), + format!("{}", "<".repeat(10_000)).into_bytes(), + vec![0xff, 0xfe, 0x00, 0xd8, 0x00], + vec![0u8; 1000], + ]; + // deterministic noise + let mut x = 0x9e37_79b9u32; + for len in [10usize, 100, 1000] { + let alphabet = b"{}[]<>:=,. \n|&#;0123456789abSYNC"; + let noise: Vec = (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + alphabet[x as usize % alphabet.len()] + }) + .collect(); + inputs.push(noise); + } + for (format, _, _) in FORMATS { + for input in &inputs { + if let Ok(doc) = parse(input, format) { + // what was read writes and reads again + let again = write(&doc, format, WriteOptions::default()); + parse(&again, format).expect("a written file reads back"); + } + } + } +} + +#[test] +fn the_cue_limit_applies() { + let mut text = String::new(); + for i in 0..200 { + text.push_str(&format!("[{}][{}]x\n", i * 10, i * 10 + 5)); + } + assert_eq!(parse(text.as_bytes(), Format::Mpl2).expect("parse").cues.len(), 200); +} diff --git a/crates/captions/tests/it/main.rs b/crates/captions/tests/it/main.rs index 7d8070cad6..9cb0535be6 100644 --- a/crates/captions/tests/it/main.rs +++ b/crates/captions/tests/it/main.rs @@ -1,4 +1,5 @@ mod ass; +mod legacy_text; mod limits; mod literal_roundtrips; mod mcc_708_timing; diff --git a/crates/cdr/Cargo.toml b/crates/cdr/Cargo.toml index edeb8d72e2..9847550082 100644 --- a/crates/cdr/Cargo.toml +++ b/crates/cdr/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-cdr" -description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing" +description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings, and a .cmx writer in the layouts it reads" version.workspace = true edition.workspace = true license.workspace = true @@ -11,7 +11,7 @@ repository.workspace = true workspace = true [features] -# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer. +# Synthetic-file builders for tests and fuzz seeds, of every version; `write` is the crate's writer. synth = [] [dependencies] diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 7c3ddadbb5..772f915350 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -1,7 +1,10 @@ # Where each layout comes from -The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and -`tests/it/provenance.rs` fails when a cited id has no row here. +The reader relies on the record layouts below, and the writer (`src/write.rs`) lays out version 15 +files by the same rows, with R64 to R73 for what only the writer needs. The `.cmx` writer +(`src/cmx_write.rs`) writes in them, with R74 and R77 for what only it needs ("Written fields" lists each +field it sets). Code cites a row by its id (`R1` ...), and `tests/it/provenance.rs` fails when a +cited id has no row here. Sources: @@ -18,8 +21,9 @@ Sources: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE), https://www.rfc-editor.org/rfc/rfc1951 - **F**: the magic database of the `file` utility (BSD-2-Clause), - https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images and - https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images, + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff and + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/archive - **PR**: the PRONOM registry's signatures for versions 1.0, 2.0 and 4.0, https://pronom.nationalarchives.gov.uk/fmt/467.xml, https://pronom.nationalarchives.gov.uk/fmt/466.xml and @@ -52,10 +56,20 @@ Sources: https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs, was read for the order of fields that the notes do not spell out (the table entries, the rendering attributes and the curve body); no code was copied from it +- **LC**: the `.cmx` reader of libcdr (MPL-2.0), `src/lib/CMXParser.cpp`, `src/lib/CMXParser.h` + and `src/lib/CMXDocumentStructure.h` at commit `b5211a57af37dac59a04f6041822a07f4a7cf7d6`, + https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.cpp, + https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.h + and https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXDocumentStructure.h, + read for the header's offsets, the index chunks and the fields of a color entry; no code was + copied from it Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks -confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows; -listed so it can be checked against a file, with what the reader does when it is wrong). +confirmed that no CX file shows), `public-reader` (a layout LC reads), `unconfirmed` (a point no source states and no sample file shows; +listed so it can be checked against a file, with what the reader does when it is wrong). The +"Written fields" table also uses `own` (a value the reader does not read, set as the synthetic test +files of `src/synth_cmx.rs` set it) and `the writer's choice` (a value the reader does not read and +the synthetic test files do not set, chosen by the writer). Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the @@ -119,14 +133,64 @@ file is committed. | R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) | | R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec | | R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) | -| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | +| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list. When that chunk is one the reader passes over or a `page`, the reader may resume instead at a `page` chunk that starts 8 to 64 bytes after it, inside its body, is not empty, ends inside the list and, when the chunk found ends inside the list, reaches its end. It does so only when that page reads with objects and without damage in its instructions, and when walking on from the chunk found and from the page, each without this recovery and entering lists as the reader does, reaches the same position inside the same lists, or leaves the list (at its end, or at stray bytes with no chunk id after them), within 16 steps, with every chunk the reader uses that the first walk reads before then also read by the second, with its body cut at the same place (pages that read without objects aside). Of the chunks that only the second walk reads, or that it reads with its body cut at another place than the first walk does, the header or a table is used only when no other chunk of its id is read, and a page is kept only when it reads with objects and without damage in its instructions. Letters spelling `page` whose length runs past the list are checked the same way. In one read, the search for pages to resume at spends at most four times the length of the RIFF form (cut at the file's length), or 1,048,576 when that is more, counting 64 for each step of a walk and the length of each page body judged; past that, the reader resumes at the first chunk id found. It does the same when a limit stops the read of a page it judges. Pages kept this way are read after the other pages, so they spend only what the limits leave, and keep their place in the file; each is judged once more before it is read. One that a limit stops, or leaves without objects, is left out with the warning for limits; one the limits cut short is read as far as they allow, as other pages are. When the chunks that only these recoveries read make the read stop at a limit, the file is read again without the recoveries, with the warning for limits. Resuming at an inner page, at a chunk the reader passes over that is not followed by another chunk id or by the list's end, or after letters whose length runs past the list is reported as damage (this reader's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | | R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample | | R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | -| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | +| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); LC `CMXParser.cpp` L1698-L1749 (a file with 32-bit coordinates: the model byte and a byte in tag 1, the values in tag 2, other tags passed over), L2254-L2371 (the values of each model: 2 and 3 four bytes, 5 red, green and blue, 9 one byte), `CMXDocumentStructure.h` L138-L139 (the tags); S: every color of the nine CX files is model 2 in the older fields, with the second byte of field 1 5 | sample (model 2), public-reader (the tags and the values of models 2, 5 and 9), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | | R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | -| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample | +| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist; in `balloon.cmx`, `PC.CMX` and `squares.cmx`, solid outlines name `rdot` entry 1, whose field 1 is a count of 0 | sample | | R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) | | R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) | | R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) | | R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) | | R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample | +| R64 | A package of versions 14 to 16 starts with a stored member `mimetype` holding `application/x-vnd.corel.draw.document+zip`; in versions 14 and 15 the RIFF file follows in `content/riffData.cdr` (R25) | F `archive` L1902-L1906 (a first member named `mimetype` at offset 30, stored, with no extra field), L2071-L2077 (the text at offsets 50 and 62); S: every file of LT `testset/15` | public-spec | +| R65 | A `trfd` record has a fourth header field, 0xFFFF, after where its offsets lie; in version 15 its offsets table starts at byte 16; each entry starts with the tag 1300 and a u32 before its type, and a matrix entry ends with 8 bytes after the six f64. The specification names the u32 `len_body`; every sample entry holds 0 there, and the writer writes 0 | KF L1079-L1106 (the 0xFFFF field), L1134-L1141 (the tag and `len_body`); S: every `trfd` record of the 15 files of LT `testset/15` without text (96 bytes, the offsets 24 and 96) | public-spec (the u32 after the tag and the 8 bytes at the end: sample) | +| R66 | A fill's property list from version 13 ends with an empty property (type 0, length 0), then two u16, the overprint flag (u32), an angle and a u32, inside the list's length; a uniform fill's record ends with 8 bytes after the list. The specification names 0, 45 degrees and 60 as the usual values of the first u16, the angle and the last u32, and lists 0, 1 and 13 for the flag | K L1100-L1121 (the 8 bytes), L1122-L1186 (the list and its end); S: the uniform fills of LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr`, whose lists hold 0 in the flag, 45 degrees and 60 there | public-spec | +| R67 | Byte 2 of an object's `flgs` holds 0x08 when the object carries argument 8000 and 0x10 when it is a clipping container (argument 8005); the group of `LIST clpt` that a container clips has 0x80 there | S: LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr` (0x08), `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (0x10 on the container, 0x80 on the clipped group) and `square_blackfill_nooutline_cdr15.cdr` (0 on a plain object) | sample (the reader does not use these bits) | +| R68 | Bit 2 of a point's type byte marks a node that can be edited. In most of the specification's samples it is set on move points and on line and curve ends and clear on control points and on the end that closes a subpath, with exceptions in a few samples of versions 13 and 14; the writer uses that common pattern. A closed subpath ends with an explicit line or curve end at its move point's coordinates, carrying bit 3 | K L2747-L2789 (`can_modify`, `is_closing_path`, from the specification's notes on its sample files) | public-spec (the reader does not use bit 2) | +| R69 | In a version 1300 uniform transparency record (R47), the u32 at byte 105 is a fill id, followed by 8 bytes. The sample's record also holds 261 as a u32 at byte 0, 0xFFFFFFFF at byte 57, 100.0 as an f64 at byte 69 and 2 at byte 81, and 0 in every other byte outside the fields R47 names | KF L707-L745 (`fill_id`); S: the record of LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr` names fill 1, a uniform fill of RGB 255, 255, 255 | public-spec (the field), sample (the white fill and the other values, which the writer writes as the sample holds them; the reader does not use them) | +| R70 | Argument 40050 of a layer is a 16-byte id, different for each layer. The other pages hold an entry for each of the master page's guides, desktop and grid layers: a layer with byte 2 of its flags set and the master layer's object type, name and id, holding nothing; the guides and desktop entries come before the page's own layers and the grid entry after them. The master page holds a guides, a desktop and a grid layer, the grid hidden and locked | K L873-L883 (the id, and the master page's layers named from the other pages by the same id); S: LT `square_blackfill_nooutline_cdr15.cdr` (the master page's three layers, and the entries on its page, in that order, with the master layers' ids) | public-spec (the id), sample (the entries and their order; the reader does not use the id, and leaves the entries out as empty layers that are not drawing layers) | +| R71 | An `outl` chunk from version 13 holds records up to the one of id 1, whose length the specification's samples give as the bytes left in the chunk less 8. In the version 15 samples the id 1 record holds 130 bytes, 8 bytes follow it, and its body holds an f64 1 at bytes 16 and 48, 45 degrees at byte 84 and 60 at byte 88; the writer writes that layout and those values. A record of id 2 holds a color property list that ends at its empty property, without the fields R66 names after a fill's list | KF L1158-L1244 (the records, type 2 a color property list, and the id 1 length in its samples); S: the 18 `outl` chunks of the LT `testset/15` files without text (each 237 bytes, the id 1 record 130 bytes long with those values and 8 bytes of 0 after it, the id 2 record 43 bytes long) | public-spec (the record types and the length), sample (the values; the reader does not use them) | +| R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) | +| R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) | +| R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample | +| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) | + +## Written fields + +`src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table +lists every field it sets. `own` marks a value the reader does not read, which the writer sets as +the synthetic test files of `src/synth_cmx.rs` set it. The header's bounds and instruction count +at bytes 96 to 116 are not written. + +| Field written | Rows | Status | +|---|---|---| +| The RIFF form `CMX1`, chunk ids and sizes, a pad byte after an odd body | R53 | sample | +| Chunk order: `cont`, each `page` chunk followed by its `rlst`, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr`, then `LIST indx` | R53, R77 | sample (`page`, `rlst`, the tables, `LIST indx`), own (the order of the tables; the `rlst` of a page after the first) | +| `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample | +| `cont`: the offset of `ixmr` at bytes 84 to 88, 0xFFFFFFFF for the information list and the picture at bytes 88 to 96 | R77 | public-reader, sample (the picture), own (no information list) | +| `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own | +| `LIST indx`: a layer table `ixlr` for each page, `ixtl` listing them, `ixpg` with each page, and `ixmr` with itself, `ixpg`, `ixtl` and the seven tables | R77 | sample (one page), own (a layer table for each page, `ixtl` listing each, and the page number after the count) | +| `rlst` for each page: its layers' numbers | R77 | sample | +| Table counts and field lists | R55 | sample | +| `rclr` fields 1 and 2, before field 10: the model and 5, then four value bytes; model 2 (CMYK in percent), 5 (red, green, blue, then 0) and 9 (gray, then three zero bytes); a spot color as model 5 with its look at its tint, and the registration color as model 2 with four values of 100 | R56 | sample (the fields, model 2 and the 5), public-reader (models 5 and 9), the writer's choice (the models of spot and registration colors, the zero bytes and the order of the fields) | +| `rclr` field 10: a property list with part 1, the color record (model, palette 5, 4 zero bytes, 4 values), and for a spot color part 3, its name; models 2 (CMYK in percent), 5 (blue, green, red), 9 (gray), 20 (registration) and 21 (blue, green, red at the tint, and the tint in percent) | R11, R14, R56 | public-notes (field 10), public-spec (the models) | +| `rpen` field 1: the width | R57 | public-notes | +| `rpen` field 1 after the width: an aspect of 100, an angle of 0, a matrix type of 1 | R57 | own | +| `rott` field 1: the flags 2, 4, 8 and 16, the caps and the join | R57 | public-notes | +| `rdot` field 1: a count and the lengths in whole outline widths | R57 | public-notes | +| `rdot` field 1 of a solid outline's pattern: a count of 0 | R57, R58 | sample | +| `rotl` field 1: six entries, the screen and the arrowhead pair always 1, a solid outline's dash pattern the entry with a count of 0 | R58 | sample | +| `rota`: one pair of 0 | R59 | sample | +| `rscr`: one screen entry, its field 1 as the sample files write it | R74 | sample | +| Instructions in the short form, and the long form past 65,534 bytes | R60 | sample (short form), public-notes (long form) | +| Begin page, field 1: the page number (from 1), a u32 of 0, the left, top, right and bottom edges of the page's curves (of the page around its center when it has none; all 0 for a page without a size) | R61 | sample (page number 1, the edges), own (the later numbers, the edges of a page with no curves or no size) | +| Begin page, field 1 after the edges: the offset of the end-page instruction, the layer count and the instruction count | R77 | sample | +| Begin page, field 4: the page's width and height | R61 | public-notes | +| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 4 zero bytes, the layer's instruction count, then the name as a u16 byte count and 8-bit characters | R62, R77 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the count; the name), own (the 4 bytes) | +| Begin layer, field 4: the name as a u32 count of UTF-16 code units and the units | R62 | public-notes | +| Begin group, field 1: the edges of the group's curves as the page's are measured (all 0 for a group with none), the groups directly inside it, its instruction count and the offset of the instruction after its end | R77 | sample (the counts and the offset), public-reader (the order), the writer's choice (the edges where they differ from the points' edges, as for a page) | +| End layer, group and page with no fields | R60 | own (the bodies are not read) | +| Curve, field 1: rendering attributes with a uniform fill (type 1, the color entry, screen entry 1) and an outline entry | R63, R74 | sample (the uniform fills of `bars.cmx`, `balloon.cmx` and `PC.CMX` name screen 1) | +| Curve, field 2: the point count, the points as i32 and a type byte each, bit 2 set on every move, line and curve end node and clear on control points, bit 3 on the first and last nodes of a closed subpath that fits in one curve; a closed subpath cut into open pieces gets a line back to its start added when its last point is elsewhere; at most 7,281 points | R16, R62 | sample (the layout), own (bit 2 on the nodes the synthetic files set it on), the writer's choice (bit 2 on a closing node, which the synthetic files leave clear) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 7a842a3abc..e86a8aa393 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -1,10 +1,12 @@ # craft-cdr -A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates). +A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates), and a +writer of version 15 drawings. It reads the `WL` files of versions 1 and 2, the RIFF chunk tree of versions 3 and later with its compressed lists, the ZIP packages that versions 14 and later save (with the data streams of versions 16 and later) and the records listed below, and hands the engine a drawing in points, -with each object's transform. It does not write `.cdr` files. +with each object's transform. `write` writes a drawing back out as a `.cdr` file of version 15 +(see [Writing](#writing)). ## What is read @@ -95,9 +97,105 @@ arrowheads and lenses are not read; the drawing's `warnings` name each kind it h path is left out and the objects it clips are read without it. Files in big-endian byte order and files with 16-bit coordinates are refused. +`write_cmx` writes a drawing as a `.cmx` file with 32-bit coordinates in the layouts `read_cmx` +reads, so that `read_cmx` leaves nothing out because of the `Limits` given: pages with their +sizes, layers with their names, groups, and curves with uniform fills and outlines. What the file +holds differently from the drawing is reported, as below. Rectangles and ellipses are +written as curves, and a clipping container as a group of its fill, the objects it clips +(unclipped) and its outline. A rounded rectangle scaled differently along its two sides gets round +corners, not stretched ones. Hidden layers, groups and shapes, guide and grid layers, guidelines +and master layers are left out; opacity, blend modes, fill rules and locked states are not +written, desktop layers are written as drawing layers, and a spot color with no name opens as a +process color; every use of a named spot color takes the look of its use at the strongest tint +among the uses whose look is known. Each color entry holds the color twice: as the property list +`read_cmx` reads, and as the model and value fields that other readers, such as libcdr, read. In +those fields a spot color is written as its look at its tint, and the registration color as 100 +percent cyan, magenta, yellow and black. + +`write_cmx` returns an error, and writes nothing, for a coordinate, page side or outline width +past the 32-bit range, a negative or NaN outline width, a page side that rounds to 0, more than +65,535 pages, layers on a page or different colors, pens, line types, dash patterns or outlines, a +dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, a depth limit +of 0 (at which `read_cmx` leaves out the index list), more than 65,535 groups directly inside one +group, more chunks, +objects, coordinates or dashes than a read within the limits takes, a file longer than their input +size, and a chunk past its 32-bit size. Otherwise the returned `Written` reports paths split or cut into several curves, dashes +rounded to whole outline widths, nonzero fills that may fill differently, names that open +shortened, spot colors at a tint too low to keep their look, with no name or with no known look +(written black), uses of one ink with different looks, and what was left out or written opaque, +unclipped or unlocked. + +The file holds an index, so that a reader that finds the tables and pages through it, rather than +by their chunk ids, opens it: the header gives where the master index starts, the index list +(`LIST indx`) gives where each table, page, page reference list and layer starts, and the page, +layer and group records give their instruction counts. A page's record also gives where its +end-page instruction starts, and a group's record gives where the instruction after its end-group +instruction starts and the edges of its curves. The record of a page with a size holds the edges of its curves, or +of the page when it has none. The header's bounds and instruction count are not written. +`PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets. + +## Writing + +`write` writes a drawing as a `.cdr` file of version 15: a ZIP package whose first member, +`mimetype`, names the format and whose member `content/riffData.cdr` holds the RIFF file. Each +record is laid out as the reader reads it, by the `PROVENANCE.md` rows it cites. The reader reads +the written file back as the drawing it was written from, to the precision the file stores +(1/254000 inch for coordinates, 1/255 for color components), with the changes listed below the +table. + +| In the drawing | Written as | +|---|---| +| Pages and their sizes; the drawing's page size | pages with a page size argument; `mcfg` | +| The master page's layers and the drawing's guidelines | the master page, with a guides, a desktop and a grid layer | +| Layers: name, kind, hidden and locked | layers with their flags and their kind as the object type | +| Guidelines of a layer | guideline objects in that layer | +| Groups, and clipping containers with the objects they clip | `LIST grp ` lists; containers naming groups of the document's `LIST clpt` | +| Paths, rectangles with each corner's radius, ellipses | curves, rectangles of the version 15 layout, ellipses | +| Uniform fills and outlines (width, color, caps, joins, dashes, behind the fill, scaled with the shape) | fill and outline records, one for each different fill or outline | +| RGB, CMYK, gray, registration and spot colors | color models 5, 3, 9 and 20; a spot color as its look with its tint and its name | +| The nonzero fill rule, opacity and blend modes | the winding argument and the uniform transparency argument | + +Opacity is written as the reader reads argument 8000 (R47), and the fill rule as the reader reads +argument 14001 (R52). The uniform transparency of every public sample R47 cites is 50%, and the +specifications R52 cites do not say which fill rule each winding value means, so the direction of +the opacity value and the value written for nonzero rest on the reader's own reading. Each layer +gets an id (argument 40050), and every other page names the master page's guides, desktop and grid +layers by those ids (R70); the master page's drawing layers are not named from the other pages. + +The drawing's version and warnings are not written. A group that holds no shape or container is +left out, a clipping container whose objects hold none is written as a plain shape, a subpath +without segments is left out, as the reader leaves it out, and a drawing without pages gets one +empty page. A closed subpath whose last segment ends away from its start gets a closing line to +its start, as the file closes subpaths with an explicit point. A drawing without a page size of +its own is written without `mcfg`. Guidelines on the master page's layers read back as the +drawing's guidelines. An empty layer of a page other than a drawing layer, and an empty layer of +the master page, are written and read back left out, as the reader leaves out such layers in any +file. A guideline on a hidden layer reads back hidden, and a guideline angle past the field's +range is written as the same angle within one turn. Hidden groups and objects carry the same hide +bit as hidden layers (R19); the specification's notes date that bit on groups and objects to a +later program release than version 15 files, so a program of that version may show them. A spot +color without a look is written with a black look. Dash lengths are written to whole outline +widths and spot color tints to whole percent, as the file stores them. + +Writing refuses a drawing that the reader would not read whole within the same `Limits` +(objects, coordinates, dashes, arguments, chunks, clipped chunks, nesting depth, clip nesting, +members and sizes), and groups nested deeper than the nesting depth, groups that hold nothing +included. It also refuses what the file cannot hold or the reader would read back otherwise +changed: a coordinate past 32 bits of 1/254000 inch, a number that is not finite, a page width or +height that rounds to less than one coordinate unit, a negative outline width or a positive one +that rounds to 0, a corner radius below 0 or more than a billionth past half the rectangle's +shorter side (a radius within that is written as half), a color value, tint or opacity outside 0 +to 1, more than 10 dash lengths, a negative one or one that rounds past 65,535, a pattern whose +lengths all round to 0, a name longer than 256 UTF-16 units or holding a NUL, a spot color without +a name, at a tint that rounds to 0 percent or at a tint too low for its look to read back within +one step of 1/255, objects on the master page's grid layer, and a guideline at the edge of the +coordinate range with no room for a second point on it whose rounded coordinates lie within 1 +degree of its angle. + ## Provenance -`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status. +`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writers +need, with their public sources and status. Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row. The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the `synth` feature); no third-party file is committed. diff --git a/crates/cdr/src/cmx.rs b/crates/cdr/src/cmx.rs index 4960c4b8df..9dee077b26 100644 --- a/crates/cdr/src/cmx.rs +++ b/crates/cdr/src/cmx.rs @@ -4,6 +4,8 @@ //! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses //! are left out with a warning. +use std::collections::BTreeSet; + use crate::bytes::{Rd, u32_at}; use crate::geometry::path_of; use crate::layout::{self, Profile}; @@ -19,6 +21,16 @@ const FORM: [u8; 4] = *b"CMX1"; const DEFAULT_UNIT: f64 = 1e-7; /// How far past a chunk that runs short the next chunk id is looked for (R53). const RESYNC: usize = 64; +/// How many steps (a chunk, or a jump over stray bytes) the reader walks on from a position it +/// could resume at, to compare it with the first chunk id found (R53). +const LOOKAHEAD: usize = 16; +/// The work counted for one step of a walk ([`walk`]) against [`PROBE_FLOOR`] (R53). +const STEP_COST: usize = 64; +/// The least work one read may spend on recoveries after stray bytes (R53), counted as +/// [`STEP_COST`] for each step of a walk and as the length of each page body judged. A read may +/// spend four times the length of the RIFF form, cut at the file's length, when that is more. Past it, the reader resumes at the +/// first chunk id found. +const PROBE_FLOOR: usize = 1 << 20; /// The chunks the reader uses (R53 to R60). const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"]; /// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them. @@ -52,6 +64,15 @@ struct Chunk<'a> { id: [u8; 4], body: &'a [u8], start: usize, + /// Only a recovery after stray bytes reads the chunk ([`inner_page`]): the header or a table + /// is taken from it only when no other chunk of its id is read, and a page is kept only when it + /// reads with objects and without damage in its instructions. + recovered: bool, +} + +/// The first chunk of id `id` that is not recovered, or else the first recovered one. +fn first_of<'c, 'a>(chunks: &'c [Chunk<'a>], id: &[u8; 4]) -> Option<&'c Chunk<'a>> { + chunks.iter().find(|c| c.id == *id && !c.recovered).or_else(|| chunks.iter().find(|c| c.id == *id)) } /// The tables that page instructions refer to by 1-based index (R55 to R59). @@ -66,9 +87,35 @@ struct Tables { /// Line type, screen, color, arrowheads, pen and dashes. outlines: Vec>, arrowheads: Vec<(u16, u16)>, + /// Missing entries are not reported as damage: a page is read only to judge its instructions + /// ([`page_reads`]). + quiet: bool, } +/// The drawing in `bytes` (R53 to R63). When the chunks that only a recovery after stray bytes +/// reads make the read stop at a limit, the file is read again without the recovery, with the +/// warning for limits. pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result { + let fresh = budget.clone(); + match read_drawing(bytes, budget, true) { + Err(Error::Limit(_)) => { + *budget = fresh; + let mut d = read_drawing(bytes, budget, false)?; + push(&mut d.warnings, Warning::TooDeep); + Ok(d) + } + read => read, + } +} + +/// The drawing as the reader reads it when it resumes after stray bytes only at the first chunk +/// id found, never at a page inside that chunk (R53). +#[cfg(any(test, feature = "synth"))] +pub(crate) fn drawing_without_recovery(bytes: &[u8], budget: &mut Budget) -> Result { + read_drawing(bytes, budget, false) +} + +fn read_drawing(bytes: &[u8], budget: &mut Budget, recover: bool) -> Result { if !is_cmx(bytes) { return Err(Error::NotCmx); } @@ -76,8 +123,8 @@ pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result {} Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")), @@ -86,15 +133,38 @@ pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT); let unit = meters / 0.0254 * 72.0; let tables = Tables::read(&chunks, unit, budget, &mut warn)?; + // The pages read without the recovery go first, so that recovered pages spend only what the + // limits leave after them; the pages keep the order of the file. let mut pages = Vec::new(); - for c in chunks.iter().filter(|c| c.id == *b"page") { - pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?); + for c in chunks.iter().filter(|c| c.id == *b"page" && !c.recovered) { + pages.push((c.start, PageRead::new(&tables, unit, budget, &mut warn).read(c)?)); } + for c in chunks.iter().filter(|c| c.id == *b"page" && c.recovered) { + // A recovered page is judged however much the recoveries spent. One that a limit stops, + // or leaves without objects, is left out with the warning that says so; one the limits + // cut short is read as far as they allow, as the other pages are. + let read = match judgement(c, budget) { + Ok((true, false, _)) => PageRead::new(&tables, unit, budget, &mut warn).read(c), + Ok((_, _, true)) | Err(Error::Limit(_)) => { + push(&mut warn, Warning::TooDeep); + continue; + } + _ => continue, + }; + match read { + Ok(page) => pages.push((c.start, page)), + Err(Error::Limit(_)) => push(&mut warn, Warning::TooDeep), + Err(e) => return Err(e), + } + } + pages.sort_by_key(|(start, _)| *start); + let pages = pages.into_iter().map(|(_, page)| page).collect(); Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) } -/// The chunks of the file in order, those inside `LIST` chunks in place (R53). -fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Result>, Error> { +/// The chunks of the file in order, those inside `LIST` chunks in place (R53). With `recover`, the +/// reader may resume after stray bytes at a page inside the first chunk id found ([`inner_page`]). +fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec, recover: bool) -> Result>, Error> { let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len()); if declared > b.len() { // The file was cut short of the size its header gives. @@ -102,15 +172,23 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Resu } let end = declared.min(b.len()); let mut out = Vec::new(); - // (position, end, depth) of the lists still to walk; a list's children go before the rest of - // the list that holds it. - let mut stack = vec![(12usize, end, 0usize)]; - while let Some((mut pos, end, depth)) = stack.pop() { + // Where the chunks start that only a recovery reads ([`rejoins`]). + let mut extra = BTreeSet::new(); + // The work the recoveries may still spend ([`PROBE_FLOOR`]). + let mut left = end.saturating_mul(4).max(PROBE_FLOOR); + // (position, end, depth, recovered) of the lists still to walk; a list's children go before + // the rest of the list that holds it. + let mut stack = vec![(12usize, end, 0usize, false)]; + while let Some((mut pos, end, depth, in_recovered)) = stack.pop() { while pos.saturating_add(8) <= end { let Some(id) = Rd::at(b, pos).fourcc() else { break }; if !is_id(&id) { - match resync(b, pos, end) { - Some(next) => { + match resync(b, pos, end, depth, recover.then_some(&*budget), &mut left) { + Some((next, damaged, found)) => { + if damaged { + push(warn, Warning::Damaged); + } + extra.extend(found); pos = next; continue; } @@ -126,30 +204,38 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Resu let stop = start.saturating_add(size); if stop > end { // Stray bytes that happen to start with four letters give a length past the list: - // look for the next chunk id after them. A chunk the reader uses is kept, cut at - // the end of the list. - if !READ_IDS.contains(&id) - && let Some(next) = resync(b, pos, end) - { + // look for the next chunk id after them, and report the damage. A chunk the reader + // uses is kept, cut at the end of the list, unless it is a page that holds a page + // the reader resumes at. + push(warn, Warning::Damaged); + let resume = if !READ_IDS.contains(&id) { + resync(b, pos, end, depth, recover.then_some(&*budget), &mut left).map(|(next, _, found)| (next, found)) + } else if recover && id == *b"page" { + inner_page(b, pos, end, depth, budget, &mut left) + } else { + None + }; + if let Some((next, found)) = resume { + extra.extend(found); pos = next; continue; } - push(warn, Warning::Damaged); } let stop = stop.min(end); let next = stop.saturating_add(size & 1); + let recovered = in_recovered || extra.contains(&pos); if id == LIST { if depth >= budget.limits.depth { push(warn, Warning::TooDeep); pos = next; continue; } - stack.push((next, end, depth)); - stack.push((start + 4, stop, depth + 1)); + stack.push((next, end, depth, in_recovered)); + stack.push((start + 4, stop, depth + 1, recovered)); break; } if let Some(body) = b.get(start..stop) { - out.push(Chunk { id, body, start }); + out.push(Chunk { id, body, start, recovered }); } pos = next; } @@ -162,15 +248,199 @@ fn is_id(t: &[u8]) -> bool { matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' ')) } -/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`] -/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list -/// that ends at `end` (R53). -fn resync(b: &[u8], pos: usize, end: usize) -> Option { - let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end); - let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p))); +/// The chunk id at `p`, when the four bytes there read as one. +fn id_at(b: &[u8], p: usize) -> Option<[u8; 4]> { + Rd::at(b, p).fourcc().filter(|id| is_id(id)) +} + +/// Where the body of the chunk at `p` ends by its length, before its pad byte. +fn chunk_stop(b: &[u8], p: usize) -> Option { + u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)) +} + +/// The first chunk id after `pos`, at an even distance of 2 to [`RESYNC`] bytes, that names a +/// chunk the reader uses or another chunk whose length keeps it inside the list that ends at `end` +/// (R53). +fn first_chunk(b: &[u8], pos: usize, end: usize) -> Option { + let fits = |p: usize| chunk_stop(b, p).is_some_and(|stop| stop <= end); + let chunk_at = |p: usize| id_at(b, p).is_some_and(|id| READ_IDS.contains(&id) || fits(p)); (pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p)) } +/// Where the next chunk after stray bytes at `pos` lies, whether the bytes passed over are +/// reported as damage, and where the chunks start that only the recovery reads (R53). It is +/// [`first_chunk`], or, with `judge` (the read's budget), a page inside that chunk ([`inner_page`]), +/// found with at most `left` work ([`PROBE_FLOOR`]). The flag is set when the reader resumes at an +/// inner page, or at a chunk it passes over that is not followed by another chunk id or by the end +/// of the list. `depth` is how many lists hold the one that ends at `end`. +fn resync(b: &[u8], pos: usize, end: usize, depth: usize, judge: Option<&Budget>, left: &mut usize) -> Option<(usize, bool, Vec)> { + let p = first_chunk(b, pos, end)?; + if let Some((k, found)) = judge.and_then(|budget| inner_page(b, p, end, depth, budget, left)) { + return Some((k, true, found)); + } + let known = id_at(b, p).is_some_and(|id| READ_IDS.contains(&id)); + let followed = chunk_stop(b, p).filter(|stop| *stop <= end).is_some_and(|stop| { + let n = stop.saturating_add((stop - p - 8) & 1); + n >= end || (n.saturating_add(8) <= end && id_at(b, n).is_some()) + }); + Some((p, !known && !followed, Vec::new())) +} + +/// A page the reader resumes at instead of the chunk at `p`, the first chunk id after stray bytes +/// or letters spelling `page` whose length runs past the list (R53). It is a page id at an even +/// distance of 8 to [`RESYNC`] bytes after `p`, inside the body of that chunk, whose length is not +/// 0, keeps it inside the list and, when the chunk at `p` ends inside the list, reaches the end of +/// that chunk. A `LIST`, the header and the tables at `p` are always kept. Walking on from `p` and +/// from the page by the reader's rule without this recovery must meet ([`rejoins`]). The first page +/// that meets is taken, with the chunks only the walk from it reads. The walks and the pages judged +/// spend `left` ([`PROBE_FLOOR`]); when it runs out, no page is taken. `depth` is how many lists +/// hold the one that ends at `end`. +fn inner_page(b: &[u8], p: usize, end: usize, depth: usize, budget: &Budget, left: &mut usize) -> Option<(usize, Vec)> { + let id = id_at(b, p)?; + if READ_IDS.contains(&id) && id != *b"page" { + return None; + } + let stop = chunk_stop(b, p).filter(|stop| *stop <= end); + let body_end = stop.unwrap_or(end); + // The chunk at `k` ends, with its pad byte, at or past the end of the chunk at `p`. + let reaches = + |k: usize| chunk_stop(b, k).is_some_and(|s| s > k + 8 && s <= end && stop.is_none_or(|stop| s.saturating_add((s - k - 8) & 1) >= stop)); + let mut found = (p + 8..=p.saturating_add(RESYNC).min(end.saturating_sub(8))) + .step_by(2) + .filter(|&k| k < body_end && id_at(b, k) == Some(*b"page") && reaches(k)) + .peekable(); + found.peek()?; + let lists = budget.limits.depth.saturating_sub(depth); + let first = walk(b, p, end, lists, left)?; + found.find_map(|k| { + let alt = walk(b, k, end, lists, left)?; + rejoins(b, &first, &alt, budget, left).map(|extra| (k, extra)) + }) +} + +/// Positions a walk through a list passes and the chunks it reads, for at most [`LOOKAHEAD`] +/// steps. +struct Walk { + /// Where the walk starts, and its place after each step: the position, and for each `LIST` + /// chunk it is inside, where that list's body ends and where the reader goes on after it. + at: Vec<(usize, Vec<(usize, usize)>)>, + /// Where each chunk the walk read starts, and where its body ends, cut at the end of the list + /// that holds it; a `LIST` chunk it enters counts by the chunks inside. + read: Vec<(usize, usize)>, + /// The walk left the list it started in: at its end, or at stray bytes with no chunk id after + /// them, where [`chunks`] stops reading that list too. + ended: bool, +} + +/// Walk the list that ends at `end` from `from` as [`chunks`] does without recovery, entering at +/// most `lists` nested `LIST` chunks as it does, and spending [`STEP_COST`] of `left` for each step; +/// `None` when `left` runs out first. +fn walk(b: &[u8], from: usize, end: usize, lists: usize, left: &mut usize) -> Option { + let mut w = Walk { at: vec![(from, Vec::new())], read: Vec::new(), ended: false }; + let mut pos = from; + let mut inside: Vec<(usize, usize)> = Vec::new(); + for _ in 0..LOOKAHEAD { + *left = left.checked_sub(STEP_COST)?; + let list_end = inside.last().map_or(end, |&(stop, _)| stop); + match step(b, pos, list_end) { + Some((next, Some(chunk))) if id_at(b, chunk) == Some(LIST) && inside.len() < lists => { + // [`chunks`] reads the list's children before the rest of the list that holds it. + let stop = chunk_stop(b, chunk).map_or(list_end, |stop| stop.min(list_end)); + inside.push((stop, next)); + pos = chunk + 12; + } + Some((next, chunk)) => { + w.read.extend(chunk.map(|c| (c, chunk_stop(b, c).map_or(list_end, |stop| stop.min(list_end))))); + pos = next; + } + None => match inside.pop() { + Some((_, after)) => pos = after, + None => { + w.ended = true; + break; + } + }, + } + w.at.push((pos, inside.clone())); + } + Some(w) +} + +/// One step of [`chunks`] without recovery at `pos`: the position after it, and where the chunk +/// it read starts when it read one; `None` when the walk ends there. +fn step(b: &[u8], pos: usize, end: usize) -> Option<(usize, Option)> { + if pos.saturating_add(8) > end { + return None; + } + let id = Rd::at(b, pos).fourcc()?; + if !is_id(&id) { + return first_chunk(b, pos, end).map(|next| (next, None)); + } + let size = u32_at(b, pos + 4).map_or(0, |s| s as usize); + let stop = (pos + 8).saturating_add(size); + if stop > end + && !READ_IDS.contains(&id) + && let Some(next) = first_chunk(b, pos, end) + { + return Some((next, None)); + } + Some((stop.min(end).saturating_add(size & 1), Some(pos))) +} + +/// Where the chunks start that the walk from an inner page `alt` reads and the walk from the first +/// chunk id `first` does not read with the same body, when the two walks meet at a place both pass (a position inside the +/// same lists) or both end, and `alt` reads at least what `first` reads until then (R53). The page +/// `alt` starts at reads with objects and without damage in its instructions. Each chunk the reader +/// uses that `first` reads before that point, `alt` reads too, with the same body, unless it is a +/// page that reads without objects. The pages judged spend `left`; when it runs out, or when the +/// read of a page judged stops, the walks do not meet. +fn rejoins(b: &[u8], first: &Walk, alt: &Walk, budget: &Budget, left: &mut usize) -> Option> { + let meet = first.at.iter().find(|q| alt.at.contains(q)).map(|(q, _)| *q).or((first.ended && alt.ended).then_some(usize::MAX))?; + let uses = |q: usize| q < meet && id_at(b, q).is_some_and(|id| READ_IDS.contains(&id)); + let used = |w: &Walk| -> Vec<(usize, usize)> { w.read.iter().copied().filter(|&(q, _)| uses(q)).collect() }; + let (kept, taken) = (used(first), used(alt)); + let (start, stop) = *alt.read.first()?; + if page_reads(b, start, stop, budget, left)? != (true, false) { + return None; + } + for &(q, stop) in kept.iter().filter(|q| !taken.contains(q)) { + // A page that reads without objects is the only chunk the walk from `alt` may leave out, + // or read with a body cut shorter by a list. + if id_at(b, q) != Some(*b"page") || page_reads(b, q, stop, budget, left)?.0 { + return None; + } + } + Some(taken.into_iter().filter(|q| !kept.contains(q)).map(|(q, _)| q).collect()) +} + +/// Whether the page chunk at `at` reads with objects, and whether its instructions read with +/// damage ([`judge_page`]); `None` when `left` does not cover its body or the read stops. +fn page_reads(b: &[u8], at: usize, end: usize, budget: &Budget, left: &mut usize) -> Option<(bool, bool)> { + let stop = chunk_stop(b, at).map_or(end, |stop| stop.min(end)); + let Some(body) = b.get(at + 8..stop) else { return Some((false, true)) }; + judge_page(&Chunk { id: *b"page", body, start: at + 8, recovered: true }, budget, left) +} + +/// Whether page `c` reads with objects, and whether its instructions read with damage. It is read +/// with empty tables whose missing entries are not reported, and with a copy of `budget` so that the +/// read's own budget is not spent. The length of its body is taken from `left` first; `None` when +/// `left` holds less, or when the read stops. +fn judge_page(c: &Chunk, budget: &Budget, left: &mut usize) -> Option<(bool, bool)> { + *left = left.checked_sub(c.body.len())?; + judgement(c, budget).ok().map(|(objects, damaged, _)| (objects, damaged)) +} + +/// Whether page `c` reads with objects, whether its instructions read with damage, and whether +/// the read left something out at one of the limits, read as [`judge_page`] reads it; the error +/// when the read stops. +fn judgement(c: &Chunk, budget: &Budget) -> Result<(bool, bool, bool), Error> { + let tables = Tables { quiet: true, ..Tables::default() }; + let mut scratch = budget.clone(); + let mut warn = Vec::new(); + let page = PageRead::new(&tables, 1.0, &mut scratch, &mut warn).read(c)?; + Ok((!page.layers.is_empty(), warn.contains(&Warning::Damaged), warn.contains(&Warning::TooDeep))) +} + /// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs /// past it (R55). fn list_end(b: &[u8], mut pos: usize) -> usize { @@ -224,7 +494,7 @@ fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result, Error> impl Tables { /// The first chunk of each table; a table that is missing is empty. fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec) -> Result { - let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body); + let first = |id: &[u8; 4]| first_of(chunks, id).map_or(&[][..], |c| c.body); // A color record of field 10 holds a property list as a `.cdr` fill does (R56). let record = layout::for_version(1300); let mut t = Tables::default(); @@ -265,26 +535,26 @@ impl Tables { } /// Entry `index` (1-based) of `list`, or `None` with a warning when there is none. - fn get(list: &[Option], index: u16, warn: &mut Vec) -> Option { + fn get(&self, list: &[Option], index: u16, warn: &mut Vec) -> Option { let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten(); - if found.is_none() { + if found.is_none() && !self.quiet { push(warn, Warning::Damaged); } found } fn color(&self, index: u16, warn: &mut Vec) -> Color { - Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3])) + self.get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3])) } /// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58). fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec) -> Option { - let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?; - let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0)); + let [line, _screen, color, arrows, pen, dash] = self.get(&self.outlines, index, warn)?; + let (flags, caps_join) = self.get(&self.line_types, line, warn).unwrap_or((2, 0)); if flags & 1 != 0 { return None; } - let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0); + let width = self.get(&self.pens, pen, warn).unwrap_or(0.0); let mut dashes = Vec::new(); if flags & 4 != 0 { let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i)); diff --git a/crates/cdr/src/cmx_write.rs b/crates/cdr/src/cmx_write.rs new file mode 100644 index 0000000000..53d0ec8664 --- /dev/null +++ b/crates/cdr/src/cmx_write.rs @@ -0,0 +1,1834 @@ +//! Writer for `.cmx` exchange files with 32-bit coordinates, in the layouts [`crate::read_cmx`] +//! reads: the RIFF form `CMX1` (R53), its header (R54), the color, pen, line type, dash, outline and +//! arrowhead tables (R55 to R59), the screen table (R74) and one `page` chunk of instructions for +//! each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills and outlines +//! (R63), and the index that gives where each of them starts (R77). `PROVENANCE.md`'s "Written +//! fields" lists every field the writer sets and where its layout comes from. +//! +//! Rectangles and ellipses are written as curves. A clipping container is written as a group of +//! its fill, the objects it clips, unclipped, and its outline. Hidden layers, groups and shapes, +//! guide and grid layers, guidelines and master layers are left out. Opacity, blend modes, fill +//! rules (a curve fills even-odd) and locked states are not written, and [`Written`] reports each +//! of these that the drawing held. The drawing's version is not written either; the file opens +//! with version 0. + +use std::collections::HashMap; +use std::hash::Hash; + +use crate::Error; +use crate::model::{Blend, Cap, Color, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Path, Pt, Segment, Shape, SubPath}; + +/// The size of a coordinate unit written: 0.1 µm, the unit of every sample file with 32-bit +/// coordinates (R54). +const UNIT_METERS: f64 = 1e-7; +/// Coordinate units per point. +const UNITS_PER_PT: f64 = 0.0254 / 72.0 / UNIT_METERS; +/// The most points one curve holds: its points field is at most 65,535 bytes long with its 3-byte +/// header, and holds a u16 count and 9 bytes for each point (R55, R62). +pub const MAX_CURVE_POINTS: usize = (u16::MAX as usize - 3 - 2) / 9; +/// The most UTF-16 units of a layer name or a color name written, as many as the reader takes in +/// (it keeps the first [`crate::records::MAX_NAME`] and a hash of the rest). +const MAX_NAME_UNITS: usize = 4096; +/// The most 8-bit characters of a layer name written, as many as the reader keeps. +const MAX_NAME_BYTES: usize = crate::records::MAX_NAME; +/// The most entries one table holds: its count is a u16 (R55), and objects name entries by a u16 +/// from 1. +const MAX_ENTRIES: usize = u16::MAX as usize; +/// The screen entry's field 1, as the sample files with 32-bit coordinates write it (R74). +const SCREEN: [u8; 13] = [0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xa5, 0xae, 0x02, 0x00]; + +// Instruction codes (R60). +const BEGIN_PAGE: i16 = 9; +const END_PAGE: i16 = 10; +const BEGIN_LAYER: i16 = 11; +const END_LAYER: i16 = 12; +const BEGIN_GROUP: i16 = 13; +const END_GROUP: i16 = 14; +const CURVE: i16 = 67; + +// Point type bytes (R16): bits 7 and 6 give the operation, bit 3 closes the subpath. Bit 2, which +// the reader does not read, is set on every node and left clear on control points, as the test +// files of `synth_cmx` set it. +const MOVE: u8 = 0x04; +const LINE: u8 = 0x44; +const CURVE_END: u8 = 0x84; +const CONTROL: u8 = 0xC0; +const CLOSES: u8 = 0x08; + +/// A written file and what it changed. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Written { + /// The file. + pub bytes: Vec, + /// A path held more than [`MAX_CURVE_POINTS`] points and was written as several curves in a + /// group, so overlapping parts of its fill may draw differently. + pub split_paths: bool, + /// A filled or outlined shape had a subpath of more than [`MAX_CURVE_POINTS`] points, which was + /// cut into open pieces, so its fill draws differently and its outline gets caps, and starts + /// its dashes again, where the pieces meet. + pub cut_subpaths: bool, + /// A dash or gap length was rounded to a whole number of outline widths, the unit the dash + /// table stores (R57), held to the 65,535 widths a length there holds, or, when it is not a + /// number, stored as 0. + pub rounded_dashes: bool, + /// A layer or spot color name is longer than the 256 UTF-16 units the reader keeps whole, or + /// ends in NUL characters, which the reader drops, so it opens shortened. Past 4,096 units it + /// is also cut when written. Two spot colors whose names differ only in what is cut or dropped + /// open as one. A layer name that holds a NUL opens cut there, and one of only white space + /// opens with no name. + pub long_names: bool, + /// A spot color's tint is too low for its ink's look to open again: the record stores the color + /// with its tint applied in 8-bit values (R14), so at 0 % it is white and at a low tint the + /// look opens changed. + pub zero_tints: bool, + /// A shape filled with the nonzero rule may fill differently with the even-odd rule every + /// curve is written with: one of its cubics loops, one of its subpaths crosses or touches + /// itself or loops over itself, or two turn the same way and their boxes overlap, measured + /// with each cubic flattened to 16 lines, with two lines that are not neighbors taken to cross + /// when they are closer than the cubics may stray from them, and with two neighbors taken to + /// cross when the curves along them may meet away from their shared point. Past 50,000,000 comparisons of edges and boxes in one + /// file, a shape is taken to fill differently. + pub nonzero_fills: bool, + /// A spot color has no name, so it opens as a process color, its look at its tint: the reader + /// takes a color without a name as a process color. + pub unnamed_spots: bool, + /// A spot color's look is unknown in every use of its name (or, for a spot color with no name, + /// in that use), so it is written, and opens, as black at its tint. + pub unknown_looks: bool, + /// A spot color name was used with different looks, and a use was written with the look of + /// the use at the strongest tint among the uses whose look is known, so that it opens more than 2/255 off what its own look would + /// open as, or off its own look where its own look would not. + pub merged_looks: bool, + /// The drawing held what the file does not hold: hidden layers, groups or shapes, guide and + /// grid layers, guidelines and master layers (left out), opacity below 1 or a blend mode + /// (written opaque and normal), clipping (written unclipped), locked layers, groups or shapes + /// (written unlocked), art on a desktop layer (written on a drawing layer), shapes whose paths + /// have no segments (left out) or a layer with nothing on it (written, and left out by the + /// reader). + pub left_out: bool, +} + +/// Write `drawing` as a `.cmx` file that a read within `limits` takes all of, as +/// [`crate::write_cmx`] describes. Coordinates are rounded to 0.1 µm. A page without its own size takes the drawing's; +/// with neither, it opens with no size. An all-zero dash pattern is solid and stores no lengths. +pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result { + let mut w = Writer { + limits, + // The RIFF header, the form type and the `cont` chunk. + file_bytes: 12 + 8 + 180, + looks: spot_looks(drawing), + crossing_budget: CROSSING_BUDGET, + left_out: !drawing.master.is_empty() || !drawing.guides.is_empty(), + ..Writer::default() + }; + // The RIFF chunk's size, counted as each child is made: the form type, then the children, each a + // whole chunk with its pad byte. + let mut size = 4u32; + let mut children = Vec::new(); + let mut add = |c: Vec| -> Result<(), Error> { + size = u32::try_from(c.len()).ok().and_then(|n| size.checked_add(n)).ok_or(Error::Limit("chunk size"))?; + children.push(c); + Ok(()) + }; + // The header's index offset is set once the index is placed. + add(chunk(b"cont", &cont(0))?)?; + // Each page chunk and its reference list, with where they start in the file and the start and + // name of each of the page's layers. + let mut pages = Vec::new(); + let mut page = |w: &mut Writer, n: usize, size: Option<(f64, f64)>, layers: &[Layer]| -> Result<(), Error> { + let at = w.file_bytes; + let (c, written) = w.page(n, size, layers)?; + add(c)?; + let refs = w.file_bytes; + let r = chunk(b"rlst", &reference_list(written.len()))?; + w.check_bytes(r.len())?; + w.file_bytes += r.len(); + add(r)?; + pages.push(PageAt { at, refs, layers: written }); + Ok(()) + }; + for (n, p) in drawing.pages.iter().enumerate() { + page(&mut w, n, p.size.or(drawing.page_size), &p.layers)?; + } + // A drawing with no pages but a page size is written as one empty page of that size. + if drawing.pages.is_empty() && drawing.page_size.is_some() { + page(&mut w, 0, drawing.page_size, &[])?; + } + // The reader leaves out a list as deep as its depth limit, and the index is a list. + if w.limits.depth == 0 { + return Err(Error::Limit("nesting depth")); + } + // The reader also counts every chunk (`cont`, each page and its reference list, the seven + // tables, and the index list with its three chunks and a layer table for each page), every + // table entry and the one arrowhead pair. + let t = &w.tables; + let entries = t.colors.entries.len() + t.pens.entries.len() + t.line_types.entries.len() + t.dashes.entries.len() + t.outlines.entries.len() + 1; + let index_chunks = pages.len().saturating_add(4); + w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + 2 * pages.len() + 7 + entries + index_chunks); + w.read_cost.check(&w.limits)?; + // Where each table chunk starts, by its id. + let mut tables = Vec::new(); + let mut at = w.file_bytes; + for c in w.tables.chunks(w.limits.input.saturating_sub(w.file_bytes))? { + let id: [u8; 4] = c[0..4].try_into().map_err(|_| Error::Limit("chunk size"))?; + tables.push((id, at)); + at = at.saturating_add(c.len()); + add(c)?; + } + let (list, ixmr) = index(at, &pages, &tables)?; + add(list)?; + let total = usize::try_from(size).ok().and_then(|n| n.checked_add(8)).ok_or(Error::Limit("chunk size"))?; + if total > w.limits.input { + return Err(Error::Limit("input size")); + } + children[0] = chunk(b"cont", &cont(ixmr))?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?; + bytes.extend(b"RIFF"); + bytes.extend(size.to_le_bytes()); + bytes.extend(b"CMX1"); + for c in children { + bytes.extend(c); + } + Ok(Written { + bytes, + split_paths: w.split_paths, + cut_subpaths: w.cut_subpaths, + rounded_dashes: w.rounded_dashes, + long_names: w.long_names, + zero_tints: w.zero_tints, + nonzero_fills: w.nonzero_fills, + unnamed_spots: w.unnamed_spots, + unknown_looks: w.unknown_looks, + merged_looks: w.merged_looks, + left_out: w.left_out, + }) +} + +/// A chunk: its id, a u32 size, the body and a pad byte after an odd body (R53). A body past +/// what the size holds is an [`Error::Limit`]. +fn chunk(id: &[u8; 4], body: &[u8]) -> Result, Error> { + let size = u32::try_from(body.len()).map_err(|_| Error::Limit("chunk size"))?; + let mut out = Vec::with_capacity(body.len() + 9); + out.extend(id); + out.extend(size.to_le_bytes()); + out.extend(body); + if body.len() % 2 == 1 { + out.push(0); + } + Ok(out) +} + +/// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64 +/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files. Bytes 84 to 96 hold the file +/// offset of the master index `ixmr`, then 0xFFFFFFFF for the information list and for the +/// picture of the drawing, which the file does not hold (R77); the rest are zeros. +fn cont(ixmr: u32) -> Vec { + let mut c = vec![0u8; 180]; + c[48] = b'2'; + c[52] = b'4'; + c[54] = b'2'; + c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes()); + c[84..88].copy_from_slice(&ixmr.to_le_bytes()); + c[88..96].fill(0xFF); + c +} + +/// Where a layer's begin-layer instruction starts in the file, and the layer's 8-bit name. +type LayerAt = (usize, Vec); + +/// Where a page's chunks start in the file, and its layers. +struct PageAt { + at: usize, + /// The page's reference list `rlst`. + refs: usize, + layers: Vec, +} + +/// A page's reference list (R77): a u16 count of its layers, then for each layer from 1 the u16 +/// values 2 and 9 and its number. +fn reference_list(layers: usize) -> Vec { + let mut r = (layers as u16).to_le_bytes().to_vec(); + for n in 1..=layers { + r.extend([2u16, 9, n as u16].map(u16::to_le_bytes).concat()); + } + r +} + +/// A file offset as the u32 the index stores. +fn offset(at: usize) -> Result { + u32::try_from(at).map_err(|_| Error::Limit("chunk size")) +} + +/// The index list `LIST indx` starting at file offset `at` (R77): a layer table `ixlr` for each +/// page, the table of layer tables `ixtl`, the page index `ixpg` and the master index `ixmr`, with +/// the file offset of `ixmr`. `tables` gives where each table chunk starts, by its id. +fn index(at: usize, pages: &[PageAt], tables: &[([u8; 4], usize)]) -> Result<(Vec, u32), Error> { + let mut body = b"indx".to_vec(); + // Where the next chunk of the list starts. + let next = |body: &Vec| at.saturating_add(8).saturating_add(body.len()); + let mut layer_tables = Vec::with_capacity(pages.len()); + for (n, p) in pages.iter().enumerate() { + layer_tables.push(next(&body)); + // The layer count and the page number, then for each layer the size of its record before + // the 0xFFFFFFFF that ends it, its begin-layer instruction and its name. + let mut t = (p.layers.len() as u16).to_le_bytes().to_vec(); + t.extend(u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?.to_le_bytes()); + for (start, name) in &p.layers { + t.extend(((8 + name.len()) as u16).to_le_bytes()); + t.extend(offset(*start)?.to_le_bytes()); + t.extend((name.len() as u16).to_le_bytes()); + t.extend(name); + t.extend(u32::MAX.to_le_bytes()); + } + body.extend(chunk(b"ixlr", &t)?); + } + // The table of layer tables: their count, the size of each record, the type 3 and the offsets. + let ixtl = next(&body); + let mut t = (pages.len() as u16).to_le_bytes().to_vec(); + t.extend(4u16.to_le_bytes()); + t.extend(3u16.to_le_bytes()); + for l in &layer_tables { + t.extend(offset(*l)?.to_le_bytes()); + } + body.extend(chunk(b"ixtl", &t)?); + // The page index: the page count, then for each page the size of its record, its page chunk, + // its layer table, 0xFFFFFFFF for a picture of the page it does not have and its reference + // list. + let ixpg = next(&body); + let mut t = (pages.len() as u16).to_le_bytes().to_vec(); + for (p, l) in pages.iter().zip(&layer_tables) { + t.extend(16u16.to_le_bytes()); + for v in [offset(p.at)?, offset(*l)?, u32::MAX, offset(p.refs)?] { + t.extend(v.to_le_bytes()); + } + } + body.extend(chunk(b"ixpg", &t)?); + // The master index: the values 1 and 24, the entry count, then an id and an offset for itself, + // the page index, the table of layer tables and each table. + let ixmr = next(&body); + let ids: [(&[u8; 4], u16); 7] = [(b"rotl", 15), (b"rott", 16), (b"rota", 17), (b"rscr", 18), (b"rpen", 19), (b"rdot", 20), (b"rclr", 21)]; + let mut entries = vec![(1u16, ixmr), (2, ixpg), (3, ixtl)]; + for (id, n) in ids { + if let Some((_, start)) = tables.iter().find(|(t, _)| t == id) { + entries.push((n, *start)); + } + } + let mut t = [1u16, 24, entries.len() as u16].map(u16::to_le_bytes).concat(); + for (n, start) in entries { + t.extend(n.to_le_bytes()); + t.extend(offset(start)?.to_le_bytes()); + } + body.extend(chunk(b"ixmr", &t)?); + Ok((chunk(b"LIST", &body)?, offset(ixmr)?)) +} + +/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). `None` when the +/// data does not fit the length. +fn field(tag: u8, data: &[u8]) -> Option> { + let len = u16::try_from(data.len() + 3).ok()?; + let mut f = Vec::with_capacity(data.len() + 3); + f.push(tag); + f.extend(len.to_le_bytes()); + f.extend(data); + Some(f) +} + +/// A field list: the fields, then 0xff (R55). +fn fields(fields: &[Vec]) -> Vec { + let mut l = fields.concat(); + l.push(0xff); + l +} + +/// An instruction: the short form when its size fits a u16 below 0xFFFF, else the long form +/// (R60). +fn instr(code: i16, body: &[u8]) -> Vec { + let mut i = Vec::with_capacity(body.len() + 8); + match u16::try_from(body.len() + 4).ok().filter(|n| *n != u16::MAX) { + Some(n) => i.extend(n.to_le_bytes()), + None => { + i.extend(u16::MAX.to_le_bytes()); + i.extend(((body.len() + 8) as u32).to_le_bytes()); + } + } + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// A length in points as coordinate units. +fn units(v: f64) -> Result { + let u = (v * UNITS_PER_PT).round(); + if u.is_finite() && u >= f64::from(i32::MIN) && u <= f64::from(i32::MAX) { Ok(u as i32) } else { Err(Error::Limit("coordinate range")) } +} + +/// A length that can't be negative (a width) in coordinate units. +fn width_units(v: f64) -> Result { + let u = (v.max(0.0) * UNITS_PER_PT).round(); + if u.is_finite() && u <= f64::from(u32::MAX) { Ok(u as u32) } else { Err(Error::Limit("coordinate range")) } +} + +/// The distinct entries of one table, in the order they were first used, and the 1-based index of +/// each. +struct Table { + entries: Vec, + index: HashMap, +} + +impl Default for Table { + fn default() -> Self { + Table { entries: Vec::new(), index: HashMap::new() } + } +} + +impl Table { + /// The 1-based index of `k`, added when it is new. + fn index(&mut self, k: K) -> Result { + if let Some(i) = self.index.get(&k) { + return Ok(*i); + } + if self.entries.len() >= MAX_ENTRIES { + return Err(Error::Limit("table entries")); + } + let i = u16::try_from(self.entries.len() + 1).map_err(|_| Error::Limit("table entries"))?; + self.entries.push(k.clone()); + self.index.insert(k, i); + Ok(i) + } +} + +/// A color as it is stored, so equal colors share an entry. +#[derive(Clone, PartialEq, Eq, Hash)] +struct ColorKey { + model: u16, + values: [u8; 4], + name: Option, +} + +/// The tables the instructions refer to (R55 to R59). +#[derive(Default)] +struct Tables { + colors: Table, + /// Widths in coordinate units. + pens: Table, + /// Flags, and the caps and join. + line_types: Table<(u8, u8)>, + dashes: Table>, + /// Line type, color, pen and dashes (the screen and the arrowheads are always the first). + outlines: Table<[u16; 4]>, +} + +impl Tables { + /// The table chunks, or an [`Error::Limit`] once they take more than `left` bytes. + fn chunks(&self, left: usize) -> Result>, Error> { + // The bytes taken so far, charged as each entry is made and then for each table's header. + let used = std::cell::Cell::new(0usize); + let charge = |n: usize| { + used.set(used.get().saturating_add(n)); + if used.get() > left { Err(Error::Limit("input size")) } else { Ok(()) } + }; + let table = |id: &[u8; 4], entries: Vec>| -> Result, Error> { + let mut d = (entries.len() as u16).to_le_bytes().to_vec(); + d.extend(entries.concat()); + let c = chunk(id, &d)?; + charge(c.len() + 2 - d.len())?; + Ok(c) + }; + let one = |tag: u8, data: &[u8]| -> Result, Error> { + let e = field(tag, data).map(|f| fields(&[f])).ok_or(Error::Limit("table entry size"))?; + charge(e.len())?; + Ok(e) + }; + let colors = self + .colors + .entries + .iter() + .map(|k| -> Result, Error> { + let e = color_entry(k)?; + charge(e.len())?; + Ok(e) + }) + .collect::, _>>()?; + // A pen: the width, an aspect of 100 percent, an angle of 0 and a matrix of type 1 + // (R57). + let pens = self + .pens + .entries + .iter() + .map(|w| { + let mut d = w.to_le_bytes().to_vec(); + d.extend(100u16.to_le_bytes()); + d.extend(0i32.to_le_bytes()); + d.extend(1u16.to_le_bytes()); + one(1, &d) + }) + .collect::, _>>()?; + let line_types = self.line_types.entries.iter().map(|(f, cj)| one(1, &[*f, *cj])).collect::, _>>()?; + let dashes = self + .dashes + .entries + .iter() + .map(|d| { + let mut b = (d.len() as u16).to_le_bytes().to_vec(); + b.extend(d.iter().flat_map(|x| x.to_le_bytes())); + one(1, &b) + }) + .collect::, _>>()?; + // An outline: line type, screen, color, arrowhead pair, pen and dash pattern (R58). + let outlines = self + .outlines + .entries + .iter() + .map(|[line, color, pen, dash]| one(1, &[*line, 1, *color, 1, *pen, *dash].map(u16::to_le_bytes).concat())) + .collect::, _>>()?; + // One arrowhead pair with no arrowheads, which every outline names (R59). + let mut rota = 1u16.to_le_bytes().to_vec(); + rota.extend([0; 4]); + Ok(vec![ + table(b"rclr", colors)?, + table(b"rpen", pens)?, + table(b"rott", line_types)?, + table(b"rdot", dashes)?, + table(b"rotl", outlines)?, + chunk(b"rota", &rota)?, + // One screen, which every outline names (R74). + table(b"rscr", vec![one(1, &SCREEN)?])?, + ]) + } +} + +/// A color as a color record (R14): the model and four value bytes. A spot color is model 21, its +/// look at its tint in blue, green and red with the tint in percent, and its name; with no look it +/// is black at its tint. +fn color_key(c: &Color) -> ColorKey { + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let pct = |v: f32| (v.clamp(0.0, 1.0) * 100.0).round() as u8; + match c { + Color::Rgb([r, g, b]) => ColorKey { model: 5, values: [byte(*b), byte(*g), byte(*r), 0], name: None }, + Color::Cmyk([c, m, y, k]) => ColorKey { model: 2, values: [pct(*c), pct(*m), pct(*y), pct(*k)], name: None }, + Color::Gray(k) => ColorKey { model: 9, values: [byte(1.0 - k), 0, 0, 0], name: None }, + Color::Registration => ColorKey { model: 20, values: [0; 4], name: None }, + Color::Spot { name, tint, look } => { + // The look is mixed at the whole percent stored, the tint the reader takes it back + // out at. + let stored = pct(*tint); + let t = f32::from(stored) / 100.0; + let [r, g, b] = look.unwrap_or([0.0; 3]).map(|v| 1.0 - (1.0 - v.clamp(0.0, 1.0)) * t); + ColorKey { model: 21, values: [byte(b), byte(g), byte(r), stored], name: Some(name.clone()) } + } + } +} + +/// The color of `k` in the fields 1 and 2 of a color entry (R56): the model and the palette 5, +/// then four value bytes. A spot color is written as its look at its tint in red, green and blue, +/// and the registration color as cyan, magenta, yellow and black at 100 percent, since the +/// models of these fields hold neither. +fn older_fields(k: &ColorKey) -> (u8, [u8; 4]) { + let [v0, v1, v2, v3] = k.values; + match k.model { + 2 => (2, [v0, v1, v2, v3]), + // Red, green and blue, where the color record holds blue, green and red. + 5 | 21 => (5, [v2, v1, v0, 0]), + 9 => (9, [v0, 0, 0, 0]), + _ => (2, [100; 4]), + } +} + +/// A color entry (R56): field 1 the model and the palette, field 2 the values, as +/// [`older_fields`] gives them, then field 10, a property list: a u32 length then parts of a u8 +/// kind, a u32 length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, +/// the values; R14), and for a named color part 3, a u32 count and UTF-16 units. +fn color_entry(k: &ColorKey) -> Result, Error> { + let mut list = vec![1u8]; + list.extend(12u32.to_le_bytes()); + list.extend(k.model.to_le_bytes()); + list.extend(5u16.to_le_bytes()); + list.extend([0; 4]); + list.extend(k.values); + if let Some(name) = &k.name { + let units = utf16_prefix(name); + list.push(3); + list.extend((4 + 2 * units.len() as u32).to_le_bytes()); + list.extend((units.len() as u32).to_le_bytes()); + list.extend(units.iter().flat_map(|u| u.to_le_bytes())); + } + let mut rec = (list.len() as u32).to_le_bytes().to_vec(); + rec.extend(list); + let (model, values) = older_fields(k); + let size = || Error::Limit("table entry size"); + Ok(fields(&[field(1, &[model, 5]).ok_or_else(size)?, field(2, &values).ok_or_else(size)?, field(10, &rec).ok_or_else(size)?])) +} + +/// The counts [`crate::read_cmx`] holds to [`crate::Limits`] while it reads a file. +#[derive(Default)] +struct ReadCost { + chunks: usize, + objects: usize, + coordinates: usize, + dashes: usize, +} + +impl ReadCost { + /// An [`Error::Limit`] when a read within `limits` would refuse the file or leave out part of + /// it. + fn check(&self, limits: &crate::Limits) -> Result<(), Error> { + if self.chunks > limits.chunks { + return Err(Error::Limit("chunk count")); + } + if self.objects > limits.objects { + return Err(Error::Limit("objects")); + } + if self.coordinates > limits.coordinates { + return Err(Error::Limit("coordinates")); + } + if self.dashes > limits.dashes { + return Err(Error::Limit("dashes")); + } + Ok(()) + } +} + +#[derive(Default)] +struct Writer { + /// What the file must open within. + limits: crate::Limits, + /// The bytes of the chunks written so far, with the RIFF header. + file_bytes: usize, + /// At least the bytes the table entries added so far take in the tables written at the end: + /// a dash pattern's lengths and a color's name. + table_bytes: usize, + tables: Tables, + /// The look of each named spot color, from [`spot_looks`]. + looks: HashMap, + /// The comparisons [`may_fill_differently`] may still make. + crossing_budget: u64, + /// The groups open where the next instruction is written, outermost first. + open_groups: Vec, + /// The instructions written on the current page, its begin-page instruction included. + instructions: usize, + /// For each group closed on the current page, where its end offset goes in the page's + /// instructions after the begin-page instruction, and the offset there, both counted from the + /// end of the begin-page instruction. + group_ends: Vec<(usize, usize)>, + /// The smallest and largest x and y the curves written on the current page reach, in + /// coordinate units. + bounds: Option<[i32; 4]>, + /// What [`crate::read_cmx`] counts against [`crate::Limits`] in the instructions written so + /// far: instructions (chunks), groups and curves (objects), curve points (coordinates) and the + /// dash lengths of every curve's outline (dashes). + read_cost: ReadCost, + split_paths: bool, + cut_subpaths: bool, + rounded_dashes: bool, + long_names: bool, + zero_tints: bool, + nonzero_fills: bool, + unnamed_spots: bool, + unknown_looks: bool, + merged_looks: bool, + left_out: bool, +} + +/// Whether a spot color's `name`, as written, reads back as no name: the reader drops trailing NULs. +fn unnamed(name: &str) -> bool { + utf16_prefix(name).iter().all(|u| *u == 0) +} + +/// Whether `name` opens shortened: it is longer than the UTF-16 units the reader keeps whole, or +/// it ends in NULs, which the reader drops. +fn shortened(name: &str) -> bool { + name.ends_with('\0') || name.encode_utf16().nth(crate::records::MAX_NAME).is_some() +} + +/// `name` in UTF-16, cut after its last whole character within [`MAX_NAME_UNITS`] units. +fn utf16_prefix(name: &str) -> Vec { + let mut units = Vec::new(); + let mut buf = [0u16; 2]; + for c in name.chars() { + let enc = c.encode_utf16(&mut buf); + if units.len() + enc.len() > MAX_NAME_UNITS { + break; + } + units.extend_from_slice(enc); + } + units +} + +/// The look of each named spot color in `drawing`, master layers included, from the use at the +/// strongest tint that gives one. +fn spot_looks(drawing: &Drawing) -> HashMap { + let mut looks: HashMap = HashMap::new(); + let layers = drawing.pages.iter().flat_map(|p| &p.layers).chain(&drawing.master); + let mut stack: Vec<&Object> = layers.flat_map(|l| &l.objects).collect(); + while let Some(o) = stack.pop() { + let shape = match o { + Object::Shape(s) => s, + Object::Group { objects, .. } => { + stack.extend(objects); + continue; + } + Object::Clip { container, objects } => { + stack.extend(objects); + container + } + }; + for c in shape.fill.iter().chain(shape.outline.as_ref().map(|o| &o.color)) { + if let Color::Spot { name, tint, look: Some(look) } = c + && !unnamed(name) + { + let known = looks.entry(name.clone()).or_insert((*tint, *look)); + if *tint > known.0 { + *known = (*tint, *look); + } + } + } + } + looks.into_iter().map(|(name, (_, look))| (name, look)).collect() +} + +impl Writer { + /// The 1-based color entry of `c`. A named spot color takes its ink's look: the look of the + /// use of its name at the strongest tint among the uses whose look is known, hidden uses + /// included. + fn color(&mut self, c: &Color) -> Result { + let key = match c { + Color::Spot { name, tint, .. } if self.looks.contains_key(name) => { + color_key(&Color::Spot { name: name.clone(), tint: *tint, look: self.looks.get(name).copied() }) + } + _ => color_key(c), + }; + if let Color::Spot { name, look, .. } = c { + self.unnamed_spots |= unnamed(name); + self.long_names |= shortened(name); + // The reader takes the tint back out of the stored color; at a low tint the 8-bit + // values do not hold enough of the look for that. + let opens = |k: &ColorKey| { + let [b, g, r] = [k.values[0], k.values[1], k.values[2]].map(|v| f32::from(v) / 255.0); + crate::records::untinted([r, g, b], f32::from(k.values[3]) / 100.0) + }; + // More than 2/255 apart in some value, with room for the reader's rounding. + let lost = |opened: &[f32; 3], want: [f32; 3]| opened.iter().zip(want).any(|(a, w)| (a - w.clamp(0.0, 1.0)).abs() > 2.0 / 255.0 + 1e-6); + let back = opens(&key); + let ink = self.looks.get(name).copied().or(*look).unwrap_or([0.0; 3]); + self.zero_tints |= key.values[3] == 0 || lost(&back, ink); + self.unknown_looks |= look.is_none() && !self.looks.contains_key(name); + // A use with a look of its own: the ink's look written in its place changed it when the + // use opens off what its own look would open as, or off its own look where its own + // look would not. Otherwise the tint alone keeps its own look from opening again. + if let Some(own) = look { + let back_own = if self.looks.get(name) == Some(own) { back } else { opens(&color_key(c)) }; + if lost(&back, back_own) || (lost(&back, *own) && !lost(&back_own, *own)) { + self.merged_looks = true; + } else { + self.zero_tints |= lost(&back_own, *own); + } + } + } + if let Some(name) = key.name.as_ref().filter(|_| !self.tables.colors.index.contains_key(&key)) { + self.table_bytes = self.table_bytes.saturating_add(2 * utf16_prefix(name).len()); + self.check_bytes(0)?; + } + self.tables.colors.index(key) + } + + /// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60), + /// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name. + /// The chunk starts at the file offset [`Writer::file_bytes`] gives. + fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec, Vec), Error> { + let mut out = Vec::new(); + self.bounds = None; + self.instructions = 1; + self.group_ends.clear(); + // Where each layer's begin-layer instruction starts in `out`, and its 8-bit name. + let mut starts = Vec::new(); + // The model holds layers and objects front to back; the file lists them back to front. + let mut written = 0; + for layer in layers.iter().rev() { + // A desktop layer is written as a drawing layer, which is how the reader takes it. + self.left_out |= !layer.guides.is_empty() || layer.flags.locked || (layer.kind == LayerKind::Desktop && !layer.objects.is_empty()); + // The reader leaves out a layer that holds nothing. + self.left_out |= layer.objects.is_empty(); + // Guide and grid layers hold construction art, which a reader takes as drawing art. + if layer.flags.hidden || matches!(layer.kind, LayerKind::Guides | LayerKind::Grid) { + self.left_out = true; + continue; + } + // The reader also stops a layer's name at its first NUL and takes a blank name as none. + let name = &layer.name; + self.long_names |= shortened(name) || name.contains('\0') || (!name.is_empty() && name.trim().is_empty()); + let body = layer_fields(n, written, &layer.name)?; + let begin = instr(BEGIN_LAYER, &body); + // The layer's instruction count goes at bytes 8 to 12 of field 1, after the + // instruction's header and the field's tag and length. + let count_at = out.len() + begin.len() - body.len() + 3 + 8; + let first = self.instructions; + starts.push((out.len(), narrow_name(&layer.name))); + out.extend(begin); + self.instructions += 1; + written += 1; + self.objects(&layer.objects, &mut out)?; + out.extend(instr(END_LAYER, &[])); + self.instructions += 1; + put_u32(&mut out, count_at, self.instructions - first)?; + self.read_cost.chunks += 2; + self.read_cost.check(&self.limits)?; + self.check_bytes(out.len())?; + } + let end = out.len(); + out.extend(instr(END_PAGE, &[])); + self.instructions += 1; + // The begin and end page instructions. + self.read_cost.chunks += 2; + self.read_cost.check(&self.limits)?; + let bounds = self.bounds.take(); + let begin_len = begin_page(n, size, bounds, PageTail::default())?.len(); + // The page's instructions after the begin-page instruction start here in the file. + let base = self.file_bytes.saturating_add(8).saturating_add(begin_len); + let tail = PageTail { + end: offset(base.saturating_add(end))?, + layers: u16::try_from(written).map_err(|_| Error::Limit("layers"))?, + instructions: u32::try_from(self.instructions).map_err(|_| Error::Limit("chunk count"))?, + }; + for (at, end) in std::mem::take(&mut self.group_ends) { + put_u32(&mut out, at, base.saturating_add(end))?; + } + let begin = begin_page(n, size, bounds, tail)?; + if u32::try_from(begin.len() + out.len()).is_err() { + return Err(Error::Limit("chunk size")); + } + let mut page = begin; + page.extend(out); + let c = chunk(b"page", &page)?; + self.check_bytes(c.len())?; + let layers = starts.into_iter().map(|(at, name)| (base.saturating_add(at), name)).collect(); + self.file_bytes += c.len(); + Ok((c, layers)) + } + + /// An [`Error::Limit`] when the file would be longer than the input size of the limits with + /// `pending` more bytes. + fn check_bytes(&self, pending: usize) -> Result<(), Error> { + if self.file_bytes.saturating_add(self.table_bytes).saturating_add(pending) > self.limits.input { + Err(Error::Limit("input size")) + } else { + Ok(()) + } + } + + /// The shown `objects` (front to back) in the order they are drawn. Groups are walked with a + /// stack, not by recursion. + fn objects(&mut self, objects: &[Object], out: &mut Vec) -> Result<(), Error> { + // Each entry: the objects of a list still to write, back to front, whether a group ends + // after them, and a clipping container's outline drawn over them. + type Level<'a> = (std::iter::Rev>, bool, Option); + let mut stack: Vec> = vec![(objects.iter().rev(), false, None)]; + while let Some((iter, _, _)) = stack.last_mut() { + // A page chunk holds at most what its 32-bit size counts. + if u32::try_from(out.len()).is_err() { + return Err(Error::Limit("chunk size")); + } + self.check_bytes(out.len())?; + let Some(o) = iter.next() else { + if let Some((_, ends, over)) = stack.pop() { + if let Some(s) = over { + self.shape(&s, out)?; + } + if ends { + self.end_group(out)?; + } + } + continue; + }; + match o { + // A hidden clipping container hides what it clips too. + Object::Shape(s) | Object::Clip { container: s, .. } if s.flags.hidden => self.left_out = true, + Object::Group { flags, .. } if flags.hidden => self.left_out = true, + Object::Shape(s) => self.shape(s, out)?, + Object::Group { objects, flags } => { + self.left_out |= flags.locked; + self.begin_group(out)?; + stack.push((objects.iter().rev(), true, None)); + } + Object::Clip { container, objects } => { + self.left_out = true; + self.begin_group(out)?; + // The container's fill is drawn behind the objects it clips and its outline + // over them; an outline behind a fill is drawn behind them too, and an + // outline with no fill to be behind is drawn over them. A container with + // neither draws nothing and is not written. + let mut over = None; + match (&container.fill, &container.outline) { + (None, None) => {} + (None, Some(_)) => over = Some((**container).clone()), + (Some(_), Some(o)) if !o.behind_fill => { + self.shape(&Shape { outline: None, ..(**container).clone() }, out)?; + over = Some(Shape { fill: None, ..(**container).clone() }); + } + _ => self.shape(container, out)?, + } + stack.push((objects.iter().rev(), true, over)); + } + } + } + Ok(()) + } + + /// Begin a group. A group inside as many groups as the reader opens (the depth of the + /// [`crate::Limits`] written for) is an [`Error::Limit`]: the reader leaves out what it holds. + fn begin_group(&mut self, out: &mut Vec) -> Result<(), Error> { + if self.open_groups.len() >= self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + if let Some(parent) = self.open_groups.last_mut() { + parent.groups = parent.groups.checked_add(1).ok_or(Error::Limit("groups"))?; + } + self.open_groups.push(OpenGroup { at: out.len(), first: self.instructions, groups: 0, bounds: None }); + out.extend(group()); + self.instructions += 1; + self.read_cost.chunks += 1; + self.read_cost.objects += 1; + self.read_cost.check(&self.limits) + } + + /// End the innermost open group, and fill in its begin-group record (R77): the edges of its + /// curves (all 0 when it has none), the groups directly inside it, its instructions from begin + /// to end, and where the instruction after its end starts, which [`Writer::page`] places in + /// the file. + fn end_group(&mut self, out: &mut Vec) -> Result<(), Error> { + out.extend(instr(END_GROUP, &[])); + self.instructions += 1; + self.read_cost.chunks += 1; + let Some(g) = self.open_groups.pop() else { return Ok(()) }; + if let (Some(parent), Some(b)) = (self.open_groups.last_mut(), g.bounds) { + parent.bounds = Some(match parent.bounds { + Some(p) => [p[0].min(b[0]), p[1].min(b[1]), p[2].max(b[2]), p[3].max(b[3])], + None => b, + }); + } + // Field 1's data starts after the instruction's 4-byte header and the field's tag and + // length. + let data = g.at + 4 + 3; + let [x0, y0, x1, y1] = g.bounds.unwrap_or_default(); + for (i, v) in [x0, y1, x1, y0].into_iter().enumerate() { + out[data + 4 * i..data + 4 * i + 4].copy_from_slice(&v.to_le_bytes()); + } + out[data + 16..data + 18].copy_from_slice(&g.groups.to_le_bytes()); + put_u32(out, data + 18, self.instructions - g.first)?; + self.group_ends.push((data + 22, out.len())); + Ok(()) + } + + /// Take in `[x0, y0, x1, y1]`, the edges of a written curve, in the page's and the innermost + /// open group's edges. + fn reach(&mut self, e: [i32; 4]) { + for b in [Some(&mut self.bounds), self.open_groups.last_mut().map(|g| &mut g.bounds)].into_iter().flatten() { + let b = b.get_or_insert(e); + *b = [b[0].min(e[0]), b[1].min(e[1]), b[2].max(e[2]), b[3].max(e[3])]; + } + } + + /// A shape as one curve, or as a group of curves when its path holds more than + /// [`MAX_CURVE_POINTS`] points. + fn shape(&mut self, s: &Shape, out: &mut Vec) -> Result<(), Error> { + self.left_out |= s.opacity < 1.0 || s.blend != Blend::Normal || s.flags.locked; + // A path's nodes are at least as many as its segments and starts; a path past what the + // limits leave is refused before its points are made. + if let Geometry::Path(p) = &s.geometry { + let nodes = p.subpaths.iter().filter(|sp| !sp.segments.is_empty()).fold(0usize, |n, sp| { + sp.segments.iter().fold(n.saturating_add(1), |n, seg| n.saturating_add(if matches!(seg, Segment::Line(_)) { 1 } else { 3 })) + }); + // A path split into several curves is written once for its fill and once for its + // outline. + let passes = if s.fill.is_some() && s.outline.is_some() && nodes > MAX_CURVE_POINTS { 2 } else { 1 }; + let nodes = nodes.saturating_mul(passes); + if self.read_cost.coordinates.saturating_add(nodes) > self.limits.coordinates { + return Err(Error::Limit("coordinates")); + } + // A path with segments takes at least one object and one instruction. + if nodes > 0 { + let cost = ReadCost { chunks: self.read_cost.chunks + 1, objects: self.read_cost.objects + 1, ..ReadCost::default() }; + cost.check(&self.limits)?; + } + self.check_bytes(out.len().saturating_add(nodes.saturating_mul(9)))?; + } + let points = points_of(&s.geometry, &s.matrix)?; + let curves = split(&points); + // A path with no segments draws nothing, and the file has no curve for it. + if curves.is_empty() { + self.left_out = true; + return Ok(()); + } + // A shape written as several curves paints all its fill and then all its outline (the + // other way round for an outline behind the fill); one curve carries both. + let passes: Vec<(Option<&Color>, Option<&Outline>)> = match (&s.fill, &s.outline) { + (Some(f), Some(o)) if curves.len() > 1 && o.behind_fill => vec![(None, Some(o)), (Some(f), None)], + (Some(f), Some(o)) if curves.len() > 1 => vec![(Some(f), None), (None, Some(o))], + (f, o) => vec![(f.as_ref(), o.as_ref())], + }; + let mut attrs = Vec::with_capacity(passes.len()); + for (f, o) in passes { + attrs.push(self.attributes(f, o, &s.matrix)?); + } + if !self.nonzero_fills + && s.nonzero + && s.fill.is_some() + && let Geometry::Path(p) = &s.geometry + { + self.nonzero_fills = may_fill_differently(p, &mut self.crossing_budget); + } + self.cut_subpaths |= (s.fill.is_some() || s.outline.is_some()) && points.iter().any(|sp| sp.len() > MAX_CURVE_POINTS); + if curves.len() > 1 { + self.split_paths = true; + self.begin_group(out)?; + } + // Each pass writes every curve, and the reader takes the outline's dashes again for every + // curve that names it. + let points_count = curves.iter().fold(0usize, |n, c| n.saturating_add(c.len())); + for (_, dashes) in &attrs { + let cost = &mut self.read_cost; + cost.chunks = cost.chunks.saturating_add(curves.len()); + cost.objects = cost.objects.saturating_add(curves.len()); + cost.coordinates = cost.coordinates.saturating_add(points_count); + cost.dashes = cost.dashes.saturating_add(dashes.saturating_mul(curves.len())); + } + self.read_cost.check(&self.limits)?; + // Each curve instruction holds at least 9 bytes for each point. + self.check_bytes(out.len().saturating_add(points_count.saturating_mul(9).saturating_mul(attrs.len())))?; + let mut bodies = Vec::with_capacity(curves.len()); + for c in &curves { + let mut g = (c.len() as u16).to_le_bytes().to_vec(); + // The points as written, in coordinate units. + let mut written = Vec::with_capacity(c.len()); + for (p, t) in c.iter() { + let (x, y) = (units(p.x)?, units(p.y)?); + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + written.push((Pt { x: f64::from(x), y: f64::from(y) }, *t)); + } + // The page's art edges take in the written curve itself: its anchors and each cubic's + // extremes, rounded outward. + for (i, (p, t)) in written.iter().enumerate() { + let [x0, y0, x1, y1] = match (t >> 6, i.checked_sub(3).and_then(|s| written.get(s..i))) { + (2, Some([(a, _), (b, _), (d, _)])) => cubic_extent(*a, *b, *d, *p), + (3, _) => continue, + _ => [p.x, p.y, p.x, p.y], + }; + // Within the anchors and control points, which are i32, so the casts keep them. + self.reach([x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32]); + } + g.extend(c.iter().map(|(_, t)| *t)); + bodies.push(field(2, &g).ok_or(Error::Limit("curve size"))?); + } + for (a, _) in &attrs { + let f1 = field(1, a).ok_or(Error::Limit("rendering attributes size"))?; + for f2 in &bodies { + let i = instr(CURVE, &fields(&[f1.clone(), f2.clone()])); + self.check_bytes(out.len().saturating_add(i.len()))?; + out.extend(i); + self.instructions += 1; + } + } + if curves.len() > 1 { + self.end_group(out)?; + } + Ok(()) + } + + /// Rendering attributes (R63): the mask, then the uniform fill's field list (fill type 1 and a + /// field 1 of the color entry and screen entry 1, R74) and the outline's (its `rotl` entry), + /// with the number of dash lengths the outline names. + fn attributes(&mut self, fill: Option<&Color>, outline: Option<&Outline>, matrix: &Matrix) -> Result<(Vec, usize), Error> { + let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1); + let mut a = vec![mask]; + let mut dashes = 0; + if let Some(c) = fill { + let index = self.color(c)?; + let mut v = 1u16.to_le_bytes().to_vec(); + v.extend(fields(&[field(1, &[index.to_le_bytes(), 1u16.to_le_bytes()].concat()).ok_or(Error::Limit("fill size"))?])); + a.extend(fields(&[field(1, &v).ok_or(Error::Limit("fill size"))?])); + } + if let Some(o) = outline { + // The points are written placed by the matrix, so an outline that scales with the + // shape takes the matrix's scale into its width, as the engine applies it (R50). + let [m0, m1, m2, m3, _, _] = matrix.0; + let scale = if o.scale_with { (m0 * m3 - m1 * m2).abs().sqrt() } else { 1.0 }; + let (index, n) = self.outline(o, scale)?; + dashes = n; + a.extend(fields(&[field(1, &index.to_le_bytes()).ok_or(Error::Limit("outline size"))?])); + } + Ok((a, dashes)) + } + + /// The `rotl` entry of an outline (R57, R58): its line type (2 solid, 4 dashed, 8 behind the + /// fill, 16 scaled with the object; the caps in the low 4 bits and the join in the high 4 + /// bits), color, pen and dash pattern, and the number of dash lengths stored. `scale` + /// multiplies the width. + fn outline(&mut self, o: &Outline, scale: f64) -> Result<(u16, usize), Error> { + // A pattern with no positive length draws a solid line (R57). + let lengths: &[f64] = if !o.dashes.iter().any(|d| *d > 0.0) { &[] } else { &o.dashes }; + // A length that is not a number is stored as 0. + self.rounded_dashes |= o.dashes.iter().any(|d| d.is_nan()); + // One table entry holds a u16 count and the lengths in a field of at most 65,535 bytes. + if lengths.len() > (usize::from(u16::MAX) - 3 - 2) / 2 { + return Err(Error::Limit("table entry size")); + } + let mut dashes: Vec = lengths.iter().map(|d| d.max(0.0).round().min(f64::from(u16::MAX)) as u16).collect(); + if lengths.iter().zip(&dashes).any(|(d, r)| *d != f64::from(*r)) { + self.rounded_dashes = true; + } + // Marks (the even entries) that all round to nothing would draw nothing, and lengths that + // all round to nothing would draw a solid line: the positive ones are kept as short as the + // table allows (gaps only in the second case). + let all_zero = dashes.iter().all(|d| *d == 0); + let marks_gone = dashes.iter().step_by(2).all(|d| *d == 0) && lengths.iter().step_by(2).any(|d| *d > 0.0); + if !dashes.is_empty() && (all_zero || marks_gone) { + for (i, (r, d)) in dashes.iter_mut().zip(lengths).enumerate() { + if *r == 0 && *d > 0.0 && (all_zero || i % 2 == 0) { + *r = 1; + } + } + self.rounded_dashes = true; + } + let dashed = !dashes.is_empty(); + let flags = 2 | if dashed { 4 } else { 0 } | if o.behind_fill { 8 } else { 0 } | if o.scale_with { 16 } else { 0 }; + let cap = match o.cap { + Cap::Butt => 0, + Cap::Round => 1, + Cap::Square => 2, + }; + let join = match o.join { + Join::Miter => 0, + Join::Round => 1, + Join::Bevel => 2, + }; + let line = self.tables.line_types.index((flags, cap | (join << 4)))?; + let color = self.color(&o.color)?; + // A pen of width 0 reads as a hairline, so a thinner positive width is written as one unit. + if o.width.is_nan() || o.width < 0.0 { + return Err(Error::Limit("outline width")); + } + let width = o.width * scale; + if width.is_nan() { + return Err(Error::Limit("outline width")); + } + let pen = self.tables.pens.index(if width > 0.0 { width_units(width)?.max(1) } else { 0 })?; + // A solid outline names an empty pattern, as the sample files' solid outlines do (R58). + let stored = dashes.len(); + if !self.tables.dashes.index.contains_key(&dashes) { + self.table_bytes = self.table_bytes.saturating_add(2 * stored); + self.check_bytes(0)?; + } + let dash = self.tables.dashes.index(dashes)?; + Ok((self.tables.outlines.index([line, color, pen, dash])?, stored)) + } +} + +/// A group open where the next instruction is written. +struct OpenGroup { + /// Where its begin-group instruction starts in the page's instructions after the begin-page + /// instruction. + at: usize, + /// The page's instructions written before it. + first: usize, + /// The groups directly inside it so far. + groups: u16, + /// The smallest and largest x and y its curves reach so far, in coordinate units. + bounds: Option<[i32; 4]>, +} + +/// What begin page keeps of the rest of the page (R77). +#[derive(Clone, Copy, Default)] +struct PageTail { + /// The file offset of the end-page instruction. + end: u32, + /// The layers on the page. + layers: u16, + /// The page's instructions, begin and end page included. + instructions: u32, +} + +/// Write `v` as a u32 at `at` of `out`. +fn put_u32(out: &mut [u8], at: usize, v: usize) -> Result<(), Error> { + let v = u32::try_from(v).map_err(|_| Error::Limit("chunk size"))?; + out.get_mut(at..at + 4).ok_or(Error::Limit("chunk size"))?.copy_from_slice(&v.to_le_bytes()); + Ok(()) +} + +/// Begin page `n` (from 0; R61): field 1 the page number from 1, a u32 of flags and the left, +/// top, right and bottom edges of `bounds`, the page's art (smallest x and y, largest x and y), +/// or of the page around its center when it has no art, then `tail` (R77); field 4 its width and +/// height. Without a size the edges are all 0, which the reader takes as no size. +fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail: PageTail) -> Result, Error> { + let number = u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?; + let mut d = number.to_le_bytes().to_vec(); + d.extend(0u32.to_le_bytes()); + let mut list = Vec::new(); + let mut size_field = None; + let mut edges = [0i32; 4]; + if let Some((w, h)) = size { + // A negative or NaN side counts as 0. + let (wu, hu) = (width_units(w)?, width_units(h)?); + // A side that rounds to nothing would make the reader drop the page's whole size. + if wu == 0 || hu == 0 { + return Err(Error::Limit("page size")); + } + edges = match bounds { + Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], + None => { + // The page around its center; an odd size keeps its extra unit on the left and + // bottom, where the edge reaches -2^31. + let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); + let (w, h) = (i64::from(wu), i64::from(hu)); + [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] + } + }; + let mut s = wu.to_le_bytes().to_vec(); + s.extend(hu.to_le_bytes()); + size_field = Some(s); + } + for v in edges { + d.extend(v.to_le_bytes()); + } + d.extend(tail.end.to_le_bytes()); + d.extend(tail.layers.to_le_bytes()); + d.extend(tail.instructions.to_le_bytes()); + list.push(field(1, &d).ok_or(Error::Limit("page size"))?); + if let Some(s) = size_field { + list.push(field(4, &s).ok_or(Error::Limit("page size"))?); + } + Ok(instr(BEGIN_PAGE, &fields(&list))) +} + +/// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it. +fn windows_1252_byte(c: char) -> u8 { + match u8::try_from(u32::from(c)) { + Ok(b) if !(0x80..0xa0).contains(&b) => b, + _ => crate::records::CP1252_HIGH.iter().position(|h| *h == c && c != '\u{FFFD}').and_then(|i| u8::try_from(0x80 + i).ok()).unwrap_or(b'?'), + } +} + +/// Whether a layer's `name`, up to the first NUL where the reader stops, is blank: it is written +/// empty, so it opens with no name. +fn blank_name(name: &str) -> bool { + name.split('\0').next().unwrap_or_default().trim().is_empty() +} + +/// A layer's name as written in 8-bit characters (Windows-1252: characters the code page has no +/// byte for are written as `?`). +fn narrow_name(name: &str) -> Vec { + if blank_name(name) { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() } +} + +/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 4 zero +/// bytes, the layer's instruction count, which [`Writer::page`] fills in (R77), then the name as a +/// u16 count and 8-bit characters ([`narrow_name`]); field 4 the name as a u32 count and UTF-16 +/// units. `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers +/// is an [`Error::Limit`]. +fn layer_fields(page: usize, n: usize, name: &str) -> Result, Error> { + let blank = blank_name(name); + let narrow = narrow_name(name); + let page = u16::try_from(page + 1).map_err(|_| Error::Limit("pages"))?; + let number = u16::try_from(n + 1).map_err(|_| Error::Limit("layers"))?; + let mut d = page.to_le_bytes().to_vec(); + d.extend(number.to_le_bytes()); + d.extend([0; 8]); + d.extend((narrow.len() as u16).to_le_bytes()); + d.extend(&narrow); + let units = if blank { Vec::new() } else { utf16_prefix(name) }; + let mut wide = (units.len() as u32).to_le_bytes().to_vec(); + wide.extend(units.iter().flat_map(|u| u.to_le_bytes())); + let f1 = field(1, &d).ok_or(Error::Limit("layer name"))?; + let f4 = field(4, &wide).ok_or(Error::Limit("layer name"))?; + Ok(fields(&[f1, f4])) +} + +/// Begin a group: field 1 of 26 bytes, which [`Writer::end_group`] fills in (R77). +fn group() -> Vec { + instr(BEGIN_GROUP, &fields(&[field(1, &[0; 26]).unwrap_or_default()])) +} + +/// A subpath's points and their type bytes (R16), placed by `m`. +type Points = Vec<(Pt, u8)>; + +/// The subpaths of a geometry as points and type bytes, one list for each subpath. A closed +/// subpath ends back at its start, on a node that carries the closing bit. +fn points_of(g: &Geometry, m: &Matrix) -> Result, Error> { + let (path, m) = match g { + Geometry::Path(p) => (std::borrow::Cow::Borrowed(p), Matrix(m.0)), + Geometry::Rect { w, h, radii } => { + let (w, h, radii, m) = fold_scale(*w, *h, *radii, m); + (std::borrow::Cow::Owned(rect_path(w, h, radii)), m) + } + Geometry::Ellipse { w, h } => (std::borrow::Cow::Owned(ellipse_path(*w, *h)), Matrix(m.0)), + }; + path.subpaths.iter().filter(|s| !s.segments.is_empty()).map(|s| subpath_points(s, &m)).collect() +} + +/// A rectangle placed by `m` with the scale of `m` taken into its size, when the matrix keeps right +/// angles: the width and height times the matrix's scale along each, the radii times the square +/// root of its area scale, and the matrix left with its rotation, mirroring and offset. The +/// corners then stay round. Other matrices are kept whole. +fn fold_scale(w: f64, h: f64, radii: [f64; 4], m: &Matrix) -> (f64, f64, [f64; 4], Matrix) { + let [m0, m1, m2, m3, m4, m5] = m.0; + let (sx, sy) = (m0.hypot(m1), m2.hypot(m3)); + let square = sx > 1e-12 && sy > 1e-12 && (m0 * m2 + m1 * m3).abs() <= 1e-9 * sx * sy; + if !square || !m.0.iter().all(|c| c.is_finite()) { + return (w, h, radii, Matrix(m.0)); + } + let k = (sx * sy).sqrt(); + (w * sx, h * sy, radii.map(|r| r * k), Matrix([m0 / sx, m1 / sx, m2 / sy, m3 / sy, m4, m5])) +} + +/// A subpath's points; more than memory holds is an [`Error::Limit`]. +fn subpath_points(s: &SubPath, m: &Matrix) -> Result { + let size = |segs: &[Segment]| segs.iter().fold(1usize, |n, seg| n.saturating_add(if matches!(seg, Segment::Line(_)) { 1 } else { 3 })); + // The closing bit on the last node closes a subpath that fits in one curve. One that is cut + // into open pieces ends with a line back to its start instead. + let open_end = s.closed && last_point(&s.segments).is_some_and(|p| p != s.start); + let closing = (open_end && size(&s.segments) > MAX_CURVE_POINTS).then_some(Segment::Line(s.start)); + let count = size(&s.segments).saturating_add(usize::from(closing.is_some())); + let mut out = Vec::new(); + out.try_reserve_exact(count).map_err(|_| Error::Limit("path size"))?; + out.push((m.apply(s.start), if s.closed { MOVE | CLOSES } else { MOVE })); + for seg in s.segments.iter().chain(closing.as_ref()) { + match seg { + Segment::Line(p) => out.push((m.apply(*p), LINE)), + Segment::Cubic(c1, c2, p) => { + out.push((m.apply(*c1), CONTROL)); + out.push((m.apply(*c2), CONTROL)); + out.push((m.apply(*p), CURVE_END)); + } + } + } + if s.closed + && let Some(end) = out.last_mut() + { + end.1 |= CLOSES; + } + Ok(out) +} + +fn last_point(segments: &[Segment]) -> Option { + segments.last().map(|s| match s { + Segment::Line(p) | Segment::Cubic(_, _, p) => *p, + }) +} + +/// The subpaths gathered into curves of at most [`MAX_CURVE_POINTS`] points, whole subpaths kept +/// together where they fit. A subpath longer than that is cut into open pieces that meet end to +/// start, each piece cut after a node. +fn split(subpaths: &[Points]) -> Vec { + let mut curves: Vec = vec![Vec::new()]; + for sp in subpaths { + if sp.len() > MAX_CURVE_POINTS { + let mut rest: &[(Pt, u8)] = sp; + while rest.len() > 1 { + // Cut after a node, never between a curve's control points and its end. + let mut take = rest.len().min(MAX_CURVE_POINTS); + while take > 1 && rest.get(take - 1).is_some_and(|(_, t)| *t == CONTROL) { + take -= 1; + } + if take < 2 { + break; + } + let piece: Points = rest[..take].iter().enumerate().map(|(i, (p, t))| if i == 0 { (*p, MOVE) } else { (*p, *t & !CLOSES) }).collect(); + if curves.last().is_some_and(|c| !c.is_empty()) { + curves.push(Vec::new()); + } + curves.push(piece); + rest = &rest[take - 1..]; + } + continue; + } + if curves.last().is_some_and(|c| c.len() + sp.len() > MAX_CURVE_POINTS) { + curves.push(Vec::new()); + } + if let Some(c) = curves.last_mut() { + c.extend_from_slice(sp); + } + } + curves.retain(|c| !c.is_empty()); + curves +} + +/// The lines each cubic is flattened to for [`may_fill_differently`]. +const CURVE_STEPS: u32 = 16; + +/// The pairs of edges and of subpath boxes [`may_fill_differently`] may compare in one export; +/// past it a shape is taken to fill differently. +const CROSSING_BUDGET: u64 = 50_000_000; + +/// The pairs among `n` items, saturating. +fn pairs(n: u64) -> u64 { + n.saturating_mul(n.saturating_sub(1)) / 2 +} + +/// Take `cost` comparisons off `budget`; false, and the budget emptied, when it does not cover +/// them. +fn charge(budget: &mut u64, cost: u64) -> bool { + match budget.checked_sub(cost) { + Some(left) => { + *budget = left; + true + } + None => { + *budget = 0; + false + } + } +} + +/// The closed polygon of a subpath with each cubic flattened to [`CURVE_STEPS`] lines, without +/// repeated points, and for each edge (from a point to the next, and from the last point to the +/// first) how far the subpath may stray from that edge: 0 along a line, and along a piece of a +/// cubic `h² / 8` times the cubic's largest second derivative, `h` being the piece's share of the +/// cubic's parameter. +fn flatten(s: &SubPath) -> (Vec, Vec) { + // Each point with how far the subpath may stray from the edge that ends at it. + let mut pts = vec![(s.start, 0.0)]; + let mut last = s.start; + for seg in &s.segments { + match *seg { + Segment::Line(p) => { + pts.push((p, 0.0)); + last = p; + } + Segment::Cubic(c1, c2, p) => { + // The second derivative, 6 ((1 − t) (p0 − 2 c1 + c2) + t (c1 − 2 c2 + p3)), is at its + // largest at an end. + let second = |a: Pt, b: Pt, c: Pt| (a.x - 2.0 * b.x + c.x).hypot(a.y - 2.0 * b.y + c.y); + let steps = f64::from(CURVE_STEPS); + let stray = 6.0 * second(last, c1, c2).max(second(c1, c2, p)) / (8.0 * steps * steps); + for i in 1..=CURVE_STEPS { + let t = f64::from(i) / steps; + let u = 1.0 - t; + let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + let q = Pt { x: a * last.x + b * c1.x + c * c2.x + d * p.x, y: a * last.y + b * c1.y + c * c2.y + d * p.y }; + pts.push((q, stray)); + } + last = p; + } + } + } + // A repeated point is dropped; the subpath strays no further than that from the point, which + // is on the edge that ends at it. + let mut kept: Vec<(Pt, f64)> = Vec::with_capacity(pts.len()); + for (q, stray) in pts { + match kept.last_mut() { + Some((prev, e)) if *prev == q => *e = e.max(stray), + _ => kept.push((q, stray)), + } + } + // A last point back on the first is dropped, and its edge becomes the edge back to the first. + if kept.len() > 1 && kept.first().map(|f| f.0) == kept.last().map(|l| l.0) { + let back = kept.pop().map_or(0.0, |(_, e)| e); + if let Some(first) = kept.first_mut() { + first.1 = first.1.max(back); + } + } + let (points, ends): (Vec, Vec) = kept.into_iter().unzip(); + // Edge k runs from point k to point k + 1. + let n = ends.len(); + let strays = (0..n).map(|k| ends[(k + 1) % n]).collect(); + (points, strays) +} + +/// Whether `p` may fill differently even-odd than nonzero: one of its cubics loops, a subpath +/// crosses itself or turns around other than once, measured with the cubics flattened (two edges +/// that are not neighbors count as crossing when they are closer than the cubics may stray from +/// their lines, and two neighbors when the curves along them may meet away from their shared +/// point), or two of its subpaths turn the same way and their boxes, control points +/// included, overlap. Subpaths +/// that turn opposite ways, such as a letter's counter inside the letter, and subpaths apart from +/// each other, fill the same either way. `budget` counts down the comparisons, and is charged for +/// a subpath's edges before the subpath is flattened. +fn may_fill_differently(p: &Path, budget: &mut u64) -> bool { + let n = p.subpaths.len(); + // The boxes of every two subpaths are compared. + if !charge(budget, pairs(n as u64)) { + return true; + } + let mut polygons = Vec::with_capacity(n); + for s in &p.subpaths { + let points = + s.segments.iter().fold(1u64, |k, seg| k.saturating_add(if matches!(seg, Segment::Line(_)) { 1 } else { u64::from(CURVE_STEPS) })); + if !charge(budget, pairs(points)) { + return true; + } + let mut last = s.start; + for seg in &s.segments { + match *seg { + Segment::Line(p) => last = p, + Segment::Cubic(c1, c2, p) => { + if cubic_loops(last, c1, c2, p) { + return true; + } + last = p; + } + } + } + let (pts, strays) = flatten(s); + if loops(&pts) || crosses(&pts, &strays) || joints_meet(s, budget) { + return true; + } + polygons.push(pts); + } + if n < 2 { + return false; + } + // Each subpath's turn (`None` when its area sums to 0, which matches either way) and box. + let shapes: Vec<(Option, [f64; 4])> = polygons + .iter() + .zip(&p.subpaths) + .map(|(pts, s)| { + // The area is summed from the first point, so far-off coordinates keep their precision. + let o = pts.first().copied().unwrap_or(s.start); + let area: f64 = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y)).sum(); + // The box holds every point, control points included, so it holds the curves too. + let controls = std::iter::once(s.start).chain(s.segments.iter().flat_map(|seg| match *seg { + Segment::Line(a) => vec![a], + Segment::Cubic(a, b, c) => vec![a, b, c], + })); + let bounds = controls.fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, q| [b[0].min(q.x), b[1].min(q.y), b[2].max(q.x), b[3].max(q.y)]); + ((area != 0.0).then_some(area > 0.0), bounds) + }) + .collect(); + shapes.iter().enumerate().any(|(i, (turn, a))| { + shapes[i + 1..] + .iter() + .any(|(other, b)| (turn.is_none() || other.is_none() || turn == other) && a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3]) + }) +} + +/// The smallest x and y and the largest x and y the cubic from `p0` through `c1` and `c2` to `p3` +/// reaches: its ends and the points where it turns along either axis. +fn cubic_extent(p0: Pt, c1: Pt, c2: Pt, p3: Pt) -> [f64; 4] { + let at = |t: f64, a: f64, b: f64, c: f64, d: f64| { + let u = 1.0 - t; + u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d + }; + // The parameters in 0 to 1 where one coordinate's derivative is 0. + let turns = |a: f64, b: f64, c: f64, d: f64| -> Vec { + let (qa, qb, qc) = (-a + 3.0 * b - 3.0 * c + d, 2.0 * (a - 2.0 * b + c), b - a); + let mut ts = Vec::new(); + if qa.abs() < 1e-12 { + if qb.abs() > 1e-12 { + ts.push(-qc / qb); + } + } else { + let disc = qb * qb - 4.0 * qa * qc; + if disc >= 0.0 { + // Each root from the form that adds numbers of one sign, so neither cancels. + let q = -0.5 * (qb + qb.signum() * disc.sqrt()); + ts.push(q / qa); + if q != 0.0 { + ts.push(qc / q); + } + } + } + ts.retain(|t| (0.0..=1.0).contains(t)); + ts + }; + // An extreme between the ends is evaluated with rounding, so it is widened by a little more + // than that rounding: the edges then hold the curve. + let slack = |v: f64| v.abs() * 4.0 * f64::EPSILON + 1e-12; + let mut e = [p0.x.min(p3.x), p0.y.min(p3.y), p0.x.max(p3.x), p0.y.max(p3.y)]; + for t in turns(p0.x, c1.x, c2.x, p3.x) { + let x = at(t, p0.x, c1.x, c2.x, p3.x); + e = [e[0].min(x - slack(x)), e[1], e[2].max(x + slack(x)), e[3]]; + } + for t in turns(p0.y, c1.y, c2.y, p3.y) { + let y = at(t, p0.y, c1.y, c2.y, p3.y); + e = [e[0], e[1].min(y - slack(y)), e[2], e[3].max(y + slack(y))]; + } + e +} + +/// Whether the cubic from `p0` through `c1` and `c2` to `p3` crosses itself. With the cubic as +/// `a t³ + b t² + c t + p0`, two parameters `s` and `t` meet where `a (σ² − π) + b σ + c = 0`, with +/// `σ = s + t` and `π = s t`; the cubic loops when `s` and `t` are distinct and both in 0 to 1. +fn cubic_loops(p0: Pt, c1: Pt, c2: Pt, p3: Pt) -> bool { + let cross = |u: (f64, f64), v: (f64, f64)| u.0 * v.1 - u.1 * v.0; + let a = (-p0.x + 3.0 * c1.x - 3.0 * c2.x + p3.x, -p0.y + 3.0 * c1.y - 3.0 * c2.y + p3.y); + let b = (3.0 * p0.x - 6.0 * c1.x + 3.0 * c2.x, 3.0 * p0.y - 6.0 * c1.y + 3.0 * c2.y); + let r = (3.0 * p0.x - 3.0 * c1.x, 3.0 * p0.y - 3.0 * c1.y); + let det = cross(a, b); + if det == 0.0 || !det.is_finite() { + return false; + } + // u = σ² − π. + let (u, sum) = (cross(r, b) / det, cross(a, r) / det); + let disc = 4.0 * u - 3.0 * sum * sum; + if disc.is_nan() || disc <= 0.0 { + return false; + } + let q = disc.sqrt(); + let (s, t) = ((sum - q) / 2.0, (sum + q) / 2.0); + // The start meeting the end closes the curve; that is no crossing. + let closes = s.abs() < 1e-9 && (t - 1.0).abs() < 1e-9; + // Rounding can put a parameter of 0 or 1 just outside the range. + let inside = |v: f64| (-1e-9..=1.0 + 1e-9).contains(&v); + inside(s) && inside(t) && !closes +} + +/// Whether the closed polygon through `pts` turns around other than once: the sum of its turning +/// angles is not one full turn either way. +fn loops(pts: &[Pt]) -> bool { + let edges: Vec<(f64, f64)> = + pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| (b.x - a.x, b.y - a.y)).filter(|(x, y)| x.hypot(*y) > 1e-9).collect(); + if edges.len() < 3 { + return false; + } + let turning: f64 = edges.iter().zip(edges.iter().cycle().skip(1)).map(|(a, b)| (a.0 * b.1 - a.1 * b.0).atan2(a.0 * b.0 + a.1 * b.1)).sum(); + (turning / std::f64::consts::TAU).round().abs() != 1.0 +} + +/// Whether two edges of the closed polygon through `pts` that are not neighbors cross, touch or run +/// along each other: the subpath comes back to a place it has been. `strays` holds, for each edge +/// from a point to the next, how far the subpath may stray from it; two edges closer than their +/// subpath may stray from them count as crossing. +fn crosses(pts: &[Pt], strays: &[f64]) -> bool { + let n = pts.len(); + if n < 4 { + return false; + } + // Which side of the line from `a` to `b` the point `c` is on: 1, -1, or 0 on the line. + let side = |a: Pt, b: Pt, c: Pt| { + let v = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); + i8::from(v > 0.0) - i8::from(v < 0.0) + }; + let edge = |i: usize| (pts[i], pts[(i + 1) % n]); + (0..n).any(|i| { + let (a, b) = edge(i); + // Edge i shares a point with edges i - 1 and i + 1, and edge 0 with edge n - 1. + (i + 2..n).filter(|j| !(i == 0 && *j == n - 1)).any(|j| { + let (c, d) = edge(j); + let (sc, sd) = (side(a, b, c), side(a, b, d)); + if sc == 0 && sd == 0 { + // On one line: they meet when their spans along it meet. + let along = |q: Pt| (q.x - a.x) * (b.x - a.x) + (q.y - a.y) * (b.y - a.y); + let (tc, td, tb) = (along(c), along(d), along(b)); + if tc.min(td).max(0.0) <= tc.max(td).min(tb) { + return true; + } + } else if sc * sd <= 0 && side(c, d, a) * side(c, d, b) <= 0 { + return true; + } + // A cubic's piece may cross an edge that its line passes close to. + let stray = strays.get(i).copied().unwrap_or(0.0) + strays.get(j).copied().unwrap_or(0.0); + stray > 0.0 && gap(a, b, c, d) <= stray * (1.0 + 1e-9) + }) + }) +} + +/// The distance between the segment from `a` to `b` and the segment from `c` to `d`, which do not +/// cross: the shortest distance from an end of one to the other. +fn gap(a: Pt, b: Pt, c: Pt, d: Pt) -> f64 { + let to = |p: Pt, a: Pt, b: Pt| { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let len = dx * dx + dy * dy; + let t = if len > 0.0 { (((p.x - a.x) * dx + (p.y - a.y) * dy) / len).clamp(0.0, 1.0) } else { 0.0 }; + (p.x - a.x - t * dx).hypot(p.y - a.y - t * dy) + }; + to(a, c, d).min(to(b, c, d)).min(to(c, a, b)).min(to(d, a, b)) +} + +/// A segment as the start, the two control points and the end of a cubic; a line as the cubic +/// along it. +type Bez = [Pt; 4]; + +/// How many times [`meet_away_from_start`] halves two cubics around their shared start before +/// taking what is left beside it not to meet, and [`boxes_meet`] halves two cubics before taking +/// them to meet. +const NEAR_HALVINGS: u32 = 32; +const APART_HALVINGS: u32 = 24; + +/// The point a share `t` of the way from `a` to `b`. +fn lerp(a: Pt, b: Pt, t: f64) -> Pt { + Pt { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t } +} + +/// The cubic `c` cut at `t` into the part before and the part after. +fn cut(c: Bez, t: f64) -> (Bez, Bez) { + let (ab, bc, cd) = (lerp(c[0], c[1], t), lerp(c[1], c[2], t), lerp(c[2], c[3], t)); + let (abc, bcd) = (lerp(ab, bc, t), lerp(bc, cd, t)); + let m = lerp(abc, bcd, t); + ([c[0], ab, abc, m], [m, bcd, cd, c[3]]) +} + +/// The directions from `c[0]` that the cubic `c` stays within away from that point, which its +/// control points and end bound: the angle halfway between the outermost two, and half the angle +/// between them. `None` when they span half a turn or more, or all lie on `c[0]`. +fn directions(c: &Bez) -> Option<(f64, f64)> { + let o = c[0]; + let vs: Vec<(f64, f64)> = c[1..].iter().map(|q| (q.x - o.x, q.y - o.y)).filter(|v| v.0 != 0.0 || v.1 != 0.0).collect(); + let first = *vs.first()?; + let angle = |v: &(f64, f64)| (first.0 * v.1 - first.1 * v.0).atan2(first.0 * v.0 + first.1 * v.1); + let (lo, hi) = vs.iter().map(angle).fold((0.0_f64, 0.0_f64), |(lo, hi), a| (lo.min(a), hi.max(a))); + (hi - lo < std::f64::consts::PI).then(|| (first.1.atan2(first.0) + (lo + hi) / 2.0, (hi - lo) / 2.0)) +} + +/// Whether the cubics `a` and `b`, which start at the same point, may meet away from it. Near that +/// point they stay within the directions their control points bound, so where those do not overlap +/// they do not meet there; the parts away from it are compared by their boxes. `halvings` counts +/// down how often the two are halved again. Two cubics that leave the point along the same tangent +/// keep overlapping directions however often they are halved; the parts left at the last halving +/// span 2⁻³² of each given cubic's parameter from the point, and are taken not to meet. `budget` counts +/// down the comparisons. +fn meet_away_from_start(a: Bez, b: Bez, halvings: u32, budget: &mut u64) -> bool { + if !charge(budget, 1) { + return true; + } + if let (Some((ca, wa)), Some((cb, wb))) = (directions(&a), directions(&b)) { + let apart = (ca - cb).sin().atan2((ca - cb).cos()).abs(); + if apart - (wa + wb) > 1e-9 { + return false; + } + // Each runs straight out along the same direction: one runs along the other. + if wa == 0.0 && wb == 0.0 { + return true; + } + } + if halvings == 0 { + return false; + } + let ((an, af), (bn, bf)) = (cut(a, 0.5), cut(b, 0.5)); + meet_away_from_start(an, bn, halvings - 1, budget) + || [(an, bf), (af, bn), (af, bf)].into_iter().any(|(x, y)| boxes_meet(x, y, APART_HALVINGS, budget)) +} + +/// Whether the cubics `a` and `b` may meet: their boxes, control points included, overlap or touch +/// after `halvings` halvings of both. `budget` counts down the comparisons. +fn boxes_meet(a: Bez, b: Bez, halvings: u32, budget: &mut u64) -> bool { + if !charge(budget, 1) { + return true; + } + let bounds = + |c: &Bez| c.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |e, q| [e[0].min(q.x), e[1].min(q.y), e[2].max(q.x), e[3].max(q.y)]); + let (p, q) = (bounds(&a), bounds(&b)); + if p[0] > q[2] || q[0] > p[2] || p[1] > q[3] || q[1] > p[3] { + return false; + } + if halvings == 0 { + return true; + } + let ((a0, a1), (b0, b1)) = (cut(a, 0.5), cut(b, 0.5)); + [(a0, b0), (a0, b1), (a1, b0), (a1, b1)].into_iter().any(|(x, y)| boxes_meet(x, y, halvings - 1, budget)) +} + +/// Whether, at a point where two segments of the subpath `s` meet (the last and the first +/// included, closing it), the subpath's pieces beside that point may meet away from it: a line +/// whole, and the first or last of a cubic's [`CURVE_STEPS`] pieces. These are the curves along +/// the neighboring edges of the flattened polygon, which [`crosses`] does not compare. Segments +/// that do not leave their start are skipped, and two lines are not compared. `budget` counts down +/// the comparisons. +fn joints_meet(s: &SubPath, budget: &mut u64) -> bool { + let line = |a: Pt, b: Pt| [a, lerp(a, b, 1.0 / 3.0), lerp(a, b, 2.0 / 3.0), b]; + // Each segment as a cubic, and whether it is a cubic. + let mut curves: Vec<(Bez, bool)> = Vec::with_capacity(s.segments.len() + 1); + let mut last = s.start; + for seg in &s.segments { + let c = match *seg { + Segment::Line(p) => (line(last, p), false), + Segment::Cubic(c1, c2, p) => ([last, c1, c2, p], true), + }; + last = c.0[3]; + if c.0.iter().any(|q| *q != c.0[0]) { + curves.push(c); + } + } + if last != s.start { + curves.push((line(last, s.start), false)); + } + let n = curves.len(); + if n < 2 { + return false; + } + let piece = 1.0 / f64::from(CURVE_STEPS); + (0..n).any(|k| { + let ((a, a_cubic), (b, b_cubic)) = (curves[k], curves[(k + 1) % n]); + // Two lines meet away from their shared point only by one running back along the other, + // which wraps no area, so the rules fill the same. + if !a_cubic && !b_cubic { + return false; + } + // Both from the point they share. + let a = if a_cubic { cut(a, 1.0 - piece).1 } else { a }; + let a = [a[3], a[2], a[1], a[0]]; + let b = if b_cubic { cut(b, piece).0 } else { b }; + // Turned about the shared point so that `b` leaves it along x: two cubics leaving it along + // one tangent then have boxes thin across it, which part as soon as the cubics do. + let o = b[0]; + let lead = b[1..].iter().map(|q| (q.x - o.x, q.y - o.y)).find(|v| v.0 != 0.0 || v.1 != 0.0).unwrap_or((1.0, 0.0)); + let (sin, cos) = lead.1.atan2(lead.0).sin_cos(); + let turn = |c: Bez| c.map(|q| Pt { x: (q.x - o.x) * cos + (q.y - o.y) * sin, y: (q.y - o.y) * cos - (q.x - o.x) * sin }); + meet_away_from_start(turn(a), turn(b), NEAR_HALVINGS, budget) + }) +} + +/// A rectangle from the origin to (`w`, `h`) with its corners rounded by `radii`, counterclockwise +/// from the corner at (`w`, 0), as [`Geometry::Rect`] gives them. On each edge a corner's radius +/// reaches no further than where its neighbor's begins, unless that leaves it less than half the +/// edge. +fn rect_path(w: f64, h: f64, radii: [f64; 4]) -> Path { + // A quarter circle as a cubic: the control points lie this share of the radius from the ends. + const K: f64 = 0.552_284_749_830_793_6; + // A negative or NaN radius leaves its corner square. + let radii = radii.map(|r| if r.is_finite() { r.max(0.0) } else { 0.0 }); + // Edge i runs from corner i to corner i + 1: the height, the width, the height, the width. + let len = |i: usize| if i.is_multiple_of(2) { h.abs() } else { w.abs() }; + // On each of its edges a corner reaches up to where its neighbor's corner begins, and at + // least halfway. + let room = |len: f64, other: f64| (len - other).max(len / 2.0); + let radii: [f64; 4] = std::array::from_fn(|i| { + let (next, prev) = ((i + 1) % 4, (i + 3) % 4); + radii[i].min(room(len(i), radii[next])).min(room(len(prev), radii[prev])) + }); + let corners = [Pt { x: w, y: 0.0 }, Pt { x: w, y: h }, Pt { x: 0.0, y: h }, Pt { x: 0.0, y: 0.0 }]; + // `r` along the edge from `c` toward `to`. + let sign = |d: f64| { + if d > 0.0 { + 1.0 + } else if d < 0.0 { + -1.0 + } else { + 0.0 + } + }; + let toward = |c: Pt, to: Pt, r: f64| Pt { x: c.x + sign(to.x - c.x) * r, y: c.y + sign(to.y - c.y) * r }; + let mut segments = Vec::new(); + let mut start = None; + for (i, (&c, r)) in corners.iter().zip(radii).enumerate() { + let (prev, next) = (corners[(i + 3) % 4], corners[(i + 1) % 4]); + // The corner is entered along the edge from the previous corner and left toward the next. + let (a, b) = (toward(c, prev, r), toward(c, next, r)); + match start { + None => start = Some(a), + Some(_) => segments.push(Segment::Line(a)), + } + if r > 0.0 { + let c1 = Pt { x: a.x + (c.x - a.x) * K, y: a.y + (c.y - a.y) * K }; + let c2 = Pt { x: b.x + (c.x - b.x) * K, y: b.y + (c.y - b.y) * K }; + segments.push(Segment::Cubic(c1, c2, b)); + } + } + let start = start.unwrap_or(corners[0]); + segments.push(Segment::Line(start)); + Path { subpaths: vec![SubPath { start, segments, closed: true }] } +} + +/// The ellipse in the box from the origin to (`w`, `h`) as four cubics. +fn ellipse_path(w: f64, h: f64) -> Path { + const K: f64 = 0.552_284_749_830_793_6; + let (cx, cy, rx, ry) = (w / 2.0, h / 2.0, w / 2.0, h / 2.0); + let p = |x: f64, y: f64| Pt { x: cx + x, y: cy + y }; + let start = p(rx, 0.0); + let segments = vec![ + Segment::Cubic(p(rx, ry * K), p(rx * K, ry), p(0.0, ry)), + Segment::Cubic(p(-rx * K, ry), p(-rx, ry * K), p(-rx, 0.0)), + Segment::Cubic(p(-rx, -ry * K), p(-rx * K, -ry), p(0.0, -ry)), + Segment::Cubic(p(rx * K, -ry), p(rx, -ry * K), start), + ]; + Path { subpaths: vec![SubPath { start, segments, closed: true }] } +} diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 8eb2d48125..4c9ee11bb7 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -8,7 +8,10 @@ //! //! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source //! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not -//! panic. Nothing here writes `.cdr` or `.cmx` files. +//! panic. +//! +//! [`write()`] writes a [`Drawing`] as a `.cdr` file of version 15, laying out each record as the +//! reader reads it. [`write_cmx`] writes `.cmx` files in the layouts the reader reads. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -17,6 +20,7 @@ use std::fmt; mod build; mod bytes; mod cmx; +mod cmx_write; mod geometry; mod inline; mod layout; @@ -32,11 +36,14 @@ pub mod synth; #[cfg(any(test, feature = "synth"))] pub mod synth_cmx; mod wl; +mod write; mod zip; +pub use cmx_write::{MAX_CURVE_POINTS, Written}; pub use limits::Limits; pub use model::{Drawing, Warning}; pub use preview::{Preview, PreviewFormat, preview}; +pub use write::{WRITTEN_VERSION, WriteError, write}; /// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file /// of version 1 or 2 whose header offsets fit the file? @@ -61,7 +68,8 @@ pub enum Error { Version(u16), /// A container structure that doesn't parse. Damaged(&'static str), - /// Past one of the [`Limits`]. + /// Past one of the [`Limits`]; from [`write_cmx`], also past what a `.cmx` file holds, or an + /// outline width that is negative or NaN. Limit(&'static str), /// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that /// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates; a @@ -113,3 +121,40 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { let mut budget = limits::Budget::new(limits); cmx::drawing(bytes, &mut budget) } + +/// Write `drawing` as a `.cmx` exchange file with 32-bit coordinates, in the layouts +/// [`read_cmx`] reads: its pages, layers, groups and shapes (as curves) with uniform fills and +/// outlines. [`read_cmx`] reading the file within `limits` leaves nothing out because of them; +/// what the file holds differently from the drawing, such as a name the reader shortens, is +/// reported in [`Written`]. +/// +/// It fails with [`Error::Limit`], and writes nothing, for: +/// - a coordinate, page side or outline width past the 32-bit range, a negative or NaN outline +/// width, or a page side that rounds to 0; +/// - more than 65,535 pages, layers on a page, or different colors, pens, line types, dash +/// patterns or outlines, or a dash pattern of more than 32,765 lengths; +/// - groups nested deeper than the depth of `limits`, a depth of 0, at which the reader leaves out +/// the index list, more than 65,535 groups directly inside one group, or more chunks, objects, +/// coordinates or dashes than a read within `limits` takes; +/// - a file longer than the input size of `limits`, or a chunk past what its 32-bit size holds. +/// +/// [`Written`] reports what the file holds differently from the drawing; its fields name each +/// case. A rounded rectangle under a scale that keeps right angles but differs along its sides is +/// written with round corners of its radii times the square root of the scales' product, not with +/// stretched corners, and is not reported. +/// +/// Each color entry holds the color twice: as the property list [`read_cmx`] reads, and as the +/// model and value fields that other readers read. In those fields a spot color is written as its +/// look at its tint, and the registration color as 100 percent cyan, magenta, yellow and black. +/// +/// The file holds an index, so that a reader that finds the tables and pages through it, rather +/// than by their chunk ids, opens it: the header gives where the master index starts, the index +/// list (`LIST indx`) gives where each table, page, page reference list and layer starts, and the +/// page, layer and group records give their instruction counts. A page's record also gives where +/// its end-page instruction starts, and a group's record gives where the instruction after its +/// end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of +/// its curves, or of the page when it has none. The header's bounds and instruction count are not +/// written. +pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result { + cmx_write::write(drawing, limits) +} diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs index bb9804557f..5ceceea8ec 100644 --- a/crates/cdr/src/limits.rs +++ b/crates/cdr/src/limits.rs @@ -74,7 +74,7 @@ impl Default for Limits { } /// The running counters of one read against its [`Limits`]. -#[derive(Debug)] +#[derive(Clone, Debug)] pub(crate) struct Budget { pub(crate) limits: Limits, inflated: usize, diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs index 49adcedc7e..49000468c9 100644 --- a/crates/cdr/src/records.rs +++ b/crates/cdr/src/records.rs @@ -15,7 +15,7 @@ const MAX_SKIPPED: usize = 4; const MAX_OUTLINE_RECORDS: usize = 16; /// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of /// a layer's. -const MAX_NAME: usize = 256; +pub(crate) const MAX_NAME: usize = 256; /// A header field: u16 in short files, u32 otherwise. fn word(r: &mut Rd, p: &Profile) -> Option { @@ -260,7 +260,7 @@ fn b_tint(b: &[u8]) -> Option { } /// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white). -fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] { +pub(crate) fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] { if tint <= 0.0 { return rgb; } @@ -486,7 +486,7 @@ fn with_hash(name: String, hash: Option) -> String { /// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes /// are Latin-1. -const CP1252_HIGH: [char; 32] = [ +pub(crate) const CP1252_HIGH: [char; 32] = [ '€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ', ]; diff --git a/crates/cdr/src/synth_cmx.rs b/crates/cdr/src/synth_cmx.rs index c70fd8545c..309840e57f 100644 --- a/crates/cdr/src/synth_cmx.rs +++ b/crates/cdr/src/synth_cmx.rs @@ -285,3 +285,12 @@ pub fn sample() -> Vec { children.extend(tables()); riff(&children) } + +/// Read `bytes` as [`crate::read_cmx`] does, except that after stray bytes the reader resumes only +/// at the first chunk id found, never at a page inside that chunk (R53). Tests compare the two. +pub fn read_cmx_without_recovery(bytes: &[u8], limits: crate::Limits) -> Result { + if bytes.len() > limits.input { + return Err(crate::Error::Limit("input size")); + } + crate::cmx::drawing_without_recovery(bytes, &mut crate::limits::Budget::new(limits)) +} diff --git a/crates/cdr/src/write.rs b/crates/cdr/src/write.rs new file mode 100644 index 0000000000..99c834a25d --- /dev/null +++ b/crates/cdr/src/write.rs @@ -0,0 +1,1486 @@ +//! Writer of `.cdr` drawings of version 15: a ZIP package (R24, R25, R64) whose member +//! `content/riffData.cdr` is the RIFF file. Each record is laid out as the reader in this crate +//! reads it, by the `PROVENANCE.md` rows the code cites, so a written file reads back as the +//! drawing it was written from. Records the reader does not read are not written. +//! +//! Writing is bounded by [`Limits`]: a drawing the reader would not read whole within the same +//! limits is refused. It never recurses and does not panic. + +use std::cell::Cell; +use std::collections::HashMap; +use std::io::Write as _; +use std::rc::Rc; + +use self::WriteError as Error; +use crate::Limits; +use crate::model::{ + Blend, Cap, Color, Drawing, Flags, Geometry, Guideline, Join, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath, +}; + +/// Why a drawing can't be written. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WriteError { + /// The reader would not read the file whole within the [`Limits`] it was written for. + Limit(&'static str), + /// What the file can't hold, or what the reader would read back changed. + Unwritable(&'static str), +} + +impl std::fmt::Display for WriteError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + WriteError::Limit(what) => write!(f, "past the {what} limit"), + WriteError::Unwritable(what) => write!(f, "{what} can't be written"), + } + } +} + +impl std::error::Error for WriteError {} + +/// The version written, in hundreds, as its `vrsn` chunk names it (R2). +pub const WRITTEN_VERSION: u16 = 1500; +/// The form type of version 15: `CDR` and the letter `F` (R1). +const FORM: [u8; 4] = *b"CDRF"; +/// The package member that holds the RIFF file (R25). +const MEMBER: &[u8] = b"content/riffData.cdr"; +/// The package's first member and what it holds (R64). +const MIMETYPE_NAME: &[u8] = b"mimetype"; +const MIMETYPE: &[u8] = b"application/x-vnd.corel.draw.document+zip"; +/// Coordinate units (1/254000 inch) in a point (R5). +const UNITS_PER_PT: f64 = 254_000.0 / 72.0; +/// The tag of the record layout from version 13 (R11, R12, R47). +const TAG_1300: u32 = 1300; + +/// Object types (R6, R23). +const RECTANGLE: u32 = 1; +const ELLIPSE: u32 = 2; +const CURVE: u32 = 3; +const GUIDELINE: u32 = 0x16; +/// Argument types (R6, R20, R21, R23, R46, R47, R52, R70). +const ARG_OUTLINE: u32 = 10; +const ARG_FILL: u32 = 20; +const ARG_COORDS: u32 = 30; +const ARG_NAME: u32 = 1000; +const ARG_TRANSPARENCY: u32 = 8000; +const ARG_CONTAINER: u32 = 8005; +const ARG_WINDING: u32 = 14001; +const ARG_GUIDE: u32 = 16000; +const ARG_PAGE_SIZE: u32 = 19130; +const ARG_LAYER_ID: u32 = 40050; + +/// The most clipped groups the reader reads one inside another (`build.rs`). +const MAX_CLIP_DEPTH: usize = 64; +/// Chunks the reader counts for one object list of a clipped group, as [`Writer::shape`] lays it +/// out: the list itself, then its searches (`build.rs`, `find_own`) for its `loda` (`flgs`, `lgob`, +/// `loda`), its `flgs` (`flgs`) and its `trfd` (`flgs`, `lgob`, `loda`, `trfl`, `trfd`). +const OBJECT_WALK: usize = 1 + 3 + 1 + 5; +/// Dash and gap lengths an outline record has room for: the arrowhead ids follow 20 bytes after +/// the first dash (R12). +const MAX_DASHES: usize = 10; +/// The most UTF-16 units of a name the reader keeps whole (`records.rs`). +const MAX_NAME: usize = 256; +/// Where a guideline's second point lies along it, in points: the writer's own value. +const GUIDE_REACH: f64 = 100.0; +/// How far, in degrees, the line through a guideline's two points, once rounded, may turn from +/// its stored angle: the writer's own value. +const GUIDE_TURN: f64 = 1.0; +/// How many units along the longer axis a guideline's second point is looked for in when no +/// farther point lies along its angle: past 82 units, a rounded point turns less than +/// `GUIDE_TURN`. +const GUIDE_STEPS: i32 = 128; + +/// The `.cdr` file of `drawing`, version 15, within `limits`. +/// +/// Pages, the master page's layers and the drawing's guidelines, layers with their kinds, names +/// and flags, groups, clipping containers with the objects they clip, curves, rectangles with +/// their corners, ellipses, uniform fills, outlines, the nonzero fill rule and uniform +/// transparency with its blend mode are written. Every other page names the master page's guides, +/// desktop and grid layers by their layer ids, and not its drawing layers. The drawing's `version` +/// and `warnings` are not written, and the written file reads back with these changes: +/// +/// - Groups that hold no shape or container are left out, and a container whose objects hold none +/// is written as a plain shape. A subpath without segments is left out. A drawing without pages +/// gets one empty page. +/// - A closed subpath whose last segment ends away from its start gets a closing line to its +/// start, as the file closes subpaths with an explicit point. +/// - Guidelines on the master page's layers read back as the drawing's guidelines. An empty layer +/// of the master page, and an empty layer of a page other than a drawing layer, read back left +/// out, as the reader leaves out such layers in any file. +/// - A guideline on a hidden layer reads back hidden, as the reader marks every guideline of a +/// hidden layer. A guideline angle past the field's range is written as the same angle within +/// one turn. +/// - Dash lengths are rounded to whole outline widths and spot color tints to whole percent, as +/// the file stores them. A spot color without a look is written with a black look. +/// +/// Hidden groups and objects carry the same hide bit as hidden layers (R19). The specification's +/// notes date that bit on groups and objects to a later program release than version 15 files, so +/// a program of that version may show them. +/// +/// Fails with [`WriteError::Limit`] when the reader would not read the file whole within `limits` +/// or groups nest deeper than its nesting depth, groups that hold nothing included, and with +/// [`WriteError::Unwritable`] for what the file can't hold or the reader would read back otherwise +/// changed: a coordinate past 32 bits of 1/254000 inch; a size, matrix or angle that is +/// not finite; a page width or height that rounds to less than one coordinate unit; a negative +/// outline width, or a positive one that rounds to 0; a corner radius below 0 or more than a billionth past half the rectangle's +/// shorter side (a radius within that is written as half); a color value, tint or opacity outside +/// 0 to 1; more than 10 dash lengths, one that is negative, not finite or rounds past 65,535, or a +/// pattern whose lengths all round to 0; a name longer than 256 UTF-16 units or holding a NUL; a +/// spot color without a name, at a tint that rounds to 0 percent or at a tint too low for its look +/// to read back within one step of 1/255; objects on the master page's grid layer; a guideline at +/// the edge of the coordinate range with no room for a second point on it whose rounded +/// coordinates lie within 1 degree of its angle. +pub fn write(drawing: &Drawing, limits: Limits) -> Result, Error> { + // Every package holds two members (R64). + if limits.members < 2 { + return Err(Error::Limit("package member count")); + } + let mut w = Writer::new(limits); + // The chunks the `doc` list always holds count from the start: `vrsn`, `doc `, `filt` and + // `otlt`, and `mcfg` with a page size. + w.counted.set(4 + usize::from(drawing.page_size.is_some())); + let mut pages = Out::new(0, limits, w.total.clone(), w.counted.clone()); + w.master_page(&mut pages, drawing)?; + if drawing.pages.is_empty() { + // A drawing has at least one page, with one layer. + pages.open(b"page")?; + pages.chunk(b"flgs", &PAGE_FLAGS)?; + pages.open(b"gobj")?; + w.master_refs(&mut pages, false)?; + let id = w.layer_id()?; + w.layer(&mut pages, &LayerParts { name: "Layer 1", kind: LayerKind::Drawing, flags: Flags::default(), master: false, id }, &[], [&[], &[]])?; + w.master_refs(&mut pages, true)?; + pages.close()?; + pages.close()?; + } + for page in &drawing.pages { + w.page(&mut pages, page)?; + } + let clips = w.clipped_groups()?; + // The bytes of each layer id after its count come from hashes of what is written, so + // different drawings get different ids and the same drawing the same ones (R70). + // A CRC-32 and a 64-bit FNV-1a hash of the same bytes. + let config = drawing.page_size.map(mcfg).transpose()?; + let (mut crc, mut fnv) = (crc32fast::Hasher::new(), 0xcbf2_9ce4_8422_2325_u64); + let mut hash = |part: &[u8]| { + crc.update(part); + for b in part { + fnv = (fnv ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3); + } + }; + for part in [&pages.buf[..], clips.as_ref().map_or(&[][..], |c| &c.buf), config.as_deref().unwrap_or_default()] { + hash(part); + } + // Each record as its chunk holds it: the id, then the body. + for (id, body) in w.fills.bodies.iter().chain(&w.outlines.bodies) { + hash(&id.to_le_bytes()); + hash(body); + } + let mut salt = [0u8; 12]; + for (slot, b) in salt.iter_mut().zip(crc.finalize().to_le_bytes().into_iter().chain(fnv.to_le_bytes())) { + *slot = b; + } + for &at in &w.id_at { + if let Some(slot) = pages.buf.get_mut(at + 4..at + 16) { + slot.copy_from_slice(&salt); + } + } + // The `doc` list's count starts with the RIFF header and the pages, which follow it. + // Its chunk count starts with the chunks of the pages and the clipped groups. + let streams = pages.chunks.saturating_add(clips.as_ref().map_or(0, |c| c.chunks)); + let mut doc = Out::new(0, limits, Rc::new(Cell::new(pages.buf.len().saturating_add(12))), Rc::new(Cell::new(streams))); + // The version chunk comes first (R2). + doc.chunk(b"vrsn", &WRITTEN_VERSION.to_le_bytes())?; + doc.open(b"doc ")?; + if let Some(config) = &config { + doc.chunk(b"mcfg", config)?; + } + // Each fill record in a `LIST filc` of its own (R72). + doc.open(b"filt")?; + for (id, body) in &w.fills.bodies { + doc.open(b"filc")?; + doc.chunk_of(b"fild", &[&id.to_le_bytes(), body])?; + doc.close()?; + } + doc.close()?; + doc.open(b"otlt")?; + for (id, body) in &w.outlines.bodies { + doc.chunk_of(b"outl", &[&id.to_le_bytes(), body])?; + } + doc.close()?; + // The clipped groups end the `doc` list; their bytes follow its stream in the file. + let clipped = clips.as_ref().map_or(&[][..], |c| &c.buf); + if clips.is_some() { + doc.tail(b"clpt", clipped.len())?; + } + doc.close()?; + // The reader takes the RIFF file within the input size too, once it is out of the package. + let len = 12usize.saturating_add(doc.buf.len()).saturating_add(clipped.len()).saturating_add(pages.buf.len()); + fits_stream(&limits, len)?; + let mut head = b"RIFF".to_vec(); + head.extend(len32(len - 8)?.to_le_bytes()); + head.extend(FORM); + let file = package(&[&head, &doc.buf, clipped, &pages.buf])?; + if file.len() > limits.input { + return Err(Error::Limit("input size")); + } + Ok(file) +} + +/// Checks that `n` bytes of the RIFF file fit what a read takes: it takes the file as input, as an +/// inflated package member and within the inflated bytes of the whole file. The error names the +/// smallest of those limits. +fn fits_stream(limits: &Limits, n: usize) -> Result<(), Error> { + let (max, what) = [(limits.input, "input size"), (limits.member, "member size"), (limits.inflated, "inflated size")] + .into_iter() + .min_by_key(|(max, _)| *max) + .unwrap_or((0, "input size")); + if n > max { Err(Error::Limit(what)) } else { Ok(()) } +} + +/// A u32 length field, or the size limit. +fn len32(n: usize) -> Result { + u32::try_from(n).map_err(|_| Error::Limit("output size")) +} + +/// A chunk stream being written: chunks and lists, with each list's size filled in when it closes +/// (R4). +struct Out { + buf: Vec, + /// Where each open list's size field lies. + open: Vec, + /// Lists around this stream's own in the file. + base: usize, + /// Chunks written, lists included. + chunks: usize, + limits: Limits, + /// Bytes of the RIFF file written so far, by every stream that shares the count. + total: Rc>, + /// Chunks of the RIFF file counted so far, lists included, by every stream that shares the + /// count. + counted: Rc>, + /// Bytes that follow the stream in the file and belong to its open lists (see `tail`). + after: usize, +} + +impl Out { + fn new(base: usize, limits: Limits, total: Rc>, counted: Rc>) -> Out { + Out { buf: Vec::new(), open: Vec::new(), base, chunks: 0, limits, total, counted, after: 0 } + } + + fn count(&mut self) -> Result<(), Error> { + self.chunks = self.chunks.saturating_add(1); + self.counted.set(self.counted.get().saturating_add(1)); + self.room_for_chunks(0) + } + + fn room_for_chunks(&self, more: usize) -> Result<(), Error> { + if self.counted.get().saturating_add(more) > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) } + } + + /// Checks that `lists` more lists nested in the open ones and `chunks` more chunks, lists + /// included, fit what a read takes, before anything is written. + fn fits(&self, lists: usize, chunks: usize) -> Result<(), Error> { + if self.base + self.open.len() + lists > self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + self.room_for_chunks(chunks) + } + + /// Checks that `n` more bytes keep the file within what a read takes. + fn room(&self, n: usize) -> Result<(), Error> { + fits_stream(&self.limits, self.total.get().saturating_add(n)) + } + + fn put(&mut self, bytes: &[u8]) { + self.buf.extend(bytes); + self.total.set(self.total.get().saturating_add(bytes.len())); + } + + fn chunk(&mut self, id: &[u8; 4], body: &[u8]) -> Result<(), Error> { + self.chunk_of(id, &[body]) + } + + /// A chunk whose body is `parts`, one after another. + fn chunk_of(&mut self, id: &[u8; 4], parts: &[&[u8]]) -> Result<(), Error> { + let len = parts.iter().fold(0usize, |n, p| n.saturating_add(p.len())); + self.count()?; + self.room(len.saturating_add(8 + len % 2))?; + self.put(id); + self.put(&len32(len)?.to_le_bytes()); + for p in parts { + self.put(p); + } + if len % 2 == 1 { + self.put(&[0]); + } + Ok(()) + } + + /// A `loda` chunk of a record of object type `kind` (R6): length, argument count, where the + /// offsets and the types lie, the type; the arguments; the offsets with one more for the end; + /// the types in reverse. The arguments are copied straight into the stream. + fn loda(&mut self, kind: u32, args: &[(u32, Vec)]) -> Result<(), Error> { + const HEAD: usize = 20; + let body = args.iter().fold(0usize, |n, (_, a)| n.saturating_add(a.len())); + let offsets_at = HEAD.saturating_add(body); + let types_at = offsets_at.saturating_add((args.len() + 1).saturating_mul(4)); + let len = types_at.saturating_add(args.len().saturating_mul(4)); + self.count()?; + self.room(len.saturating_add(8 + len % 2))?; + self.put(b"loda"); + self.put(&len32(len)?.to_le_bytes()); + for v in [len, args.len(), offsets_at, types_at] { + self.put(&len32(v)?.to_le_bytes()); + } + self.put(&kind.to_le_bytes()); + for (_, a) in args { + self.put(a); + } + let mut at = HEAD; + for (_, a) in args { + self.put(&len32(at)?.to_le_bytes()); + at += a.len(); + } + self.put(&len32(at)?.to_le_bytes()); + for (t, _) in args.iter().rev() { + self.put(&t.to_le_bytes()); + } + if len % 2 == 1 { + self.put(&[0]); + } + Ok(()) + } + + /// Opens a list of `form`. The reader reads the chunks of a list nested at most `depth` deep. + fn open(&mut self, form: &[u8; 4]) -> Result<(), Error> { + self.count()?; + if self.base + self.open.len() + 1 > self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + self.room(12)?; + self.put(b"LIST"); + self.open.push(self.buf.len()); + self.put(&[0; 4]); + self.put(form); + Ok(()) + } + + fn close(&mut self) -> Result<(), Error> { + let at = self.open.pop().ok_or(Error::Limit("output size"))?; + let len = (self.buf.len() + self.after) - at - 4; + let field = len32(len)?.to_le_bytes(); + if let Some(slot) = self.buf.get_mut(at..at + 4) { + slot.copy_from_slice(&field); + } + if len % 2 == 1 { + // A pad byte would go after the bytes kept outside the stream. + if self.after > 0 { + return Err(Error::Limit("output size")); + } + self.put(&[0]); + } + Ok(()) + } + + /// Opens a list of `form` whose chunks, `len` bytes already laid out, follow the stream in + /// the file instead of being copied into it. Nothing more is written to the stream; only the + /// lists open around it close. + fn tail(&mut self, form: &[u8; 4], len: usize) -> Result<(), Error> { + self.open(form)?; + self.room(len)?; + self.after = len; + self.total.set(self.total.get().saturating_add(len)); + self.close() + } +} + +/// Fill or outline records by their body, numbered as they are first used. +#[derive(Default)] +struct Records { + ids: HashMap, u32>, + /// Each record's id and body, in the order they were numbered; the chunk holds the id, then + /// the body. + bodies: Vec<(u32, Rc<[u8]>)>, +} + +/// What the read of the written file will count, against the limits. +struct Writer<'d> { + limits: Limits, + /// Bytes of the RIFF file written so far: the pages, the clipped groups and the fill and + /// outline tables, held together to what a read takes. + total: Rc>, + /// Chunks of the RIFF file counted so far, held to the chunk limit: the `doc` list's own, the + /// pages', the clipped groups' and the records'. + counted: Rc>, + fills: Records, + outlines: Records, + /// The next fill or outline id. + next_id: u32, + /// The objects each container clips, by the id of its `LIST clpt` group (R46), with how many + /// clipped groups the reader has open when it reads them. + clips: Vec<(u32, &'d [Object], usize)>, + /// The clipped groups open around the objects being written. + clip_depth: usize, + objects: usize, + coordinates: usize, + dashes: usize, + /// Chunks the reader steps through inside clipped groups: each group's `spnd` and flags, each + /// object or group list, each nested group's flags, and the chunks it looks at to find each + /// object's `loda`, `flgs` and `trfd`. + clip_walked: usize, + /// Layer ids given out so far, and where each layer's id lies in the pages' stream. + layer_ids: u32, + id_at: Vec, + /// The master page's guides, desktop and grid layers, which the other pages name (R70). + master_refs: Vec<(&'d str, LayerKind, Flags, [u8; 16])>, +} + +/// What a layer list carries besides its objects and guidelines. +struct LayerParts<'a> { + name: &'a str, + kind: LayerKind, + flags: Flags, + /// On the master page, or an entry that names one of its layers. + master: bool, + /// The layer id (R70). + id: [u8; 16], +} + +/// A layer of the master page as it is written. +struct MasterLayer<'a> { + name: &'a str, + kind: LayerKind, + flags: Flags, + objects: &'a [Object], + guides: [&'a [Guideline]; 2], +} + +/// A layer id before its last 12 bytes are set for the drawing: the first four count the layers +/// (R70). +const LAYER_ID: [u8; 16] = [0; 16]; + +/// The flags of a page other than the master page (R19). +const PAGE_FLAGS: [u8; 4] = [0, 0, 0, 0x90]; + +impl<'d> Writer<'d> { + fn new(limits: Limits) -> Self { + Writer { + limits, + total: Rc::new(Cell::new(0)), + counted: Rc::new(Cell::new(0)), + fills: Records::default(), + outlines: Records::default(), + next_id: 1, + clips: Vec::new(), + clip_depth: 0, + objects: 0, + coordinates: 0, + dashes: 0, + clip_walked: 0, + layer_ids: 0, + id_at: Vec::new(), + master_refs: Vec::new(), + } + } + + /// A new layer id (R70), different from every other id in the file. + fn layer_id(&mut self) -> Result<[u8; 16], Error> { + self.layer_ids = self.layer_ids.checked_add(1).ok_or(Error::Limit("output size"))?; + let mut id = LAYER_ID; + for (slot, b) in id.iter_mut().zip(self.layer_ids.to_le_bytes()) { + *slot = b; + } + Ok(id) + } + + /// The entries that name the master page's guides, desktop and grid layers on another page + /// (R70): the grid layers' when `grids`, the others' otherwise. + fn master_refs(&mut self, out: &mut Out, grids: bool) -> Result<(), Error> { + let refs: Vec<_> = self.master_refs.iter().filter(|r| (r.1 == LayerKind::Grid) == grids).copied().collect(); + for (name, kind, flags, id) in refs { + self.layer(out, &LayerParts { name, kind, flags, master: true, id }, &[], [&[], &[]])?; + } + Ok(()) + } + + /// A `loda` record, within the arguments a read takes from one. + fn loda(&self, out: &mut Out, kind: u32, args: &[(u32, Vec)]) -> Result<(), Error> { + if args.len() > self.limits.arguments { + return Err(Error::Limit("argument count")); + } + out.loda(kind, args) + } + + /// `n` more chunks the reader steps through, counted against the clipped chunks while inside + /// a clipped group. + fn walk(&mut self, n: usize) -> Result<(), Error> { + if self.clip_depth == 0 { + return Ok(()); + } + self.clip_walked = self.clip_walked.saturating_add(n); + if self.clip_walked > self.limits.clipped_chunks { Err(Error::Limit("clipped chunk count")) } else { Ok(()) } + } + + fn take_object(&mut self) -> Result<(), Error> { + self.objects += 1; + if self.objects > self.limits.objects { Err(Error::Limit("object count")) } else { Ok(()) } + } + + /// The master page (R19, R70). + fn master_page(&mut self, out: &mut Out, drawing: &'d Drawing) -> Result<(), Error> { + out.open(b"page")?; + // Byte 2 marks the master page (R19). + out.chunk(b"flgs", &[0, 0, 1, 0x90])?; + out.open(b"gobj")?; + // The reader leaves out the master page's grid layers. + for l in drawing.master.iter().filter(|l| l.kind == LayerKind::Grid) { + if draws(&l.objects, &self.limits)? { + return Err(Error::Unwritable("objects on the master page's grid layer")); + } + } + // The drawing's master layers, with a guides, a desktop and a grid layer when they have + // none. The drawing's guidelines go in the first guides layer that is shown and unlocked, + // and in a guides layer of their own when there is none. + let made = |name, kind, flags, guides| MasterLayer { name, kind, flags, objects: &[], guides: [guides, &[]] }; + let first_guides = drawing.master.iter().position(|l| l.kind == LayerKind::Guides && l.flags == Flags::default()); + let has_guides = drawing.master.iter().any(|l| l.kind == LayerKind::Guides); + let own_guides = first_guides.is_none() && (!has_guides || !drawing.guides.is_empty()); + let guides_layer = own_guides.then(|| made("Guides", LayerKind::Guides, Flags::default(), &drawing.guides[..])); + let layers = drawing.master.iter().enumerate().map(|(i, l)| MasterLayer { + name: &l.name, + kind: l.kind, + flags: l.flags, + objects: &l.objects, + guides: [&l.guides, if Some(i) == first_guides { &drawing.guides } else { &[] }], + }); + let has_desktop = drawing.master.iter().any(|l| l.kind == LayerKind::Desktop); + let desktop = (!has_desktop).then(|| made("Desktop", LayerKind::Desktop, Flags::default(), &[])); + // A grid layer, hidden and locked as sample files hold it, when they have none; the reader + // leaves out the master page's grid layers (R70). + let has_grid = drawing.master.iter().any(|l| l.kind == LayerKind::Grid); + let grid = (!has_grid).then(|| made("Grid", LayerKind::Grid, Flags { hidden: true, locked: true }, &[])); + for l in guides_layer.into_iter().chain(layers).chain(desktop).chain(grid) { + let id = self.layer_id()?; + if l.kind != LayerKind::Drawing { + self.master_refs.push((l.name, l.kind, l.flags, id)); + } + self.layer(out, &LayerParts { name: l.name, kind: l.kind, flags: l.flags, master: true, id }, l.objects, l.guides)?; + } + out.close()?; + out.close() + } + + /// A page (R19, R21, R22): its flags, its size in its own `loda`, then its layers in a `gobj` + /// list. + fn page(&mut self, out: &mut Out, page: &'d Page) -> Result<(), Error> { + out.open(b"page")?; + out.chunk(b"flgs", &PAGE_FLAGS)?; + if let Some(size) = page.size { + let size = page_size(size)?; + out.open(b"lgob")?; + self.loda(out, 0, &[(ARG_PAGE_SIZE, size)])?; + out.close()?; + } + out.open(b"gobj")?; + // The entries for the master page's layers go around the page's own, as sample files + // place them (R70). + self.master_refs(out, false)?; + for l in &page.layers { + let id = self.layer_id()?; + self.layer(out, &LayerParts { name: &l.name, kind: l.kind, flags: l.flags, master: false, id }, &l.objects, [&l.guides, &[]])?; + } + self.master_refs(out, true)?; + out.close()?; + out.close() + } + + /// A layer (R19, R9): flags, its `loda` with its kind as the object type and its name, then + /// its objects and guidelines. + fn layer(&mut self, out: &mut Out, layer: &LayerParts, objects: &'d [Object], guides: [&[Guideline]; 2]) -> Result<(), Error> { + // The kind's low bits; bit 0x10, which also marks a grid, is the lock bit here, and the + // object type names the kind. + let (kind, byte0) = match layer.kind { + LayerKind::Drawing => (0, 0), + LayerKind::Grid => (11, 0x0a), + LayerKind::Guides => (12, 0x0a), + LayerKind::Desktop => (17, 0x08), + }; + out.open(b"layr")?; + // Byte 2 is set on the master page's layers and on the entries that name them. + out.chunk(b"flgs", &flags(layer.flags, byte0, u8::from(layer.master), 0x98))?; + out.open(b"lgob")?; + // The id is the first argument: after the chunk's header and the record's 20 bytes. + self.id_at.push(out.buf.len() + 8 + 20); + self.loda(out, kind, &[(ARG_LAYER_ID, layer.id.to_vec()), (ARG_NAME, name(layer.name)?)])?; + out.close()?; + self.objects(out, objects)?; + for g in guides.into_iter().flatten() { + self.guideline(out, g)?; + } + out.close() + } + + /// A guideline object (R23). + fn guideline(&mut self, out: &mut Out, g: &Guideline) -> Result<(), Error> { + self.take_object()?; + // The points lie along the angle as stored. + let stored = angle(g.angle)?; + let (s, c) = (f64::from(i32::from_le_bytes(stored)) / 1_000_000.0).to_radians().sin_cos(); + let along = |k: f64| -> Result, Error> { Ok([coord(g.at.x + k * c)?, coord(g.at.y + k * s)?].concat()) }; + let first = along(0.0)?; + // Whether a rounded second point lies apart from the first along the stored angle, on + // either side, within `GUIDE_TURN`. + let units = |p: &[u8], i: usize| p.get(4 * i..4 * i + 4).and_then(|b| b.try_into().ok()).map_or(0.0, |b| f64::from(i32::from_le_bytes(b))); + let along_angle = |p: &Vec| { + let (dx, dy) = (units(p, 0) - units(&first, 0), units(p, 1) - units(&first, 1)); + // With room for the floating-point error of a turn of exactly `GUIDE_TURN`. + (dx != 0.0 || dy != 0.0) && (dx * s - dy * c).abs().atan2((dx * c + dy * s).abs()) <= GUIDE_TURN.to_radians() + 1e-12 + }; + // A second point on the line: the point at the full reach, on the positive side first. + // When neither side has one in the file's range, the farthest point on each side whose + // coordinates round within the range, and of the two the one farther away. Rounding moves + // monotonically along the line, so the points that round within the range form one span + // around the first point; halving the step finds its end to the last representable + // value. Short of a farthest point along the angle, which only happens within + // `GUIDE_STEPS` units of the range's edge, the farthest rounded point of the line within + // that distance that lies along the angle, on either side. + let full = [GUIDE_REACH, -GUIDE_REACH].into_iter().find_map(|k| along(k).ok().filter(along_angle)); + let stepped = || { + // Each side's run of rounded points, walked outward from the start with `along` + // itself: a step of one unit's length at a time, and a halving search for where the + // rounded point changes, so every rounded point the line passes through is reached. + let reach = f64::from(GUIDE_STEPS) / (UNITS_PER_PT * c.abs().max(s.abs())); + let unit = 1.0 / UNITS_PER_PT; + let mut best: Option<(f64, Vec)> = None; + for side in [1.0, -1.0] { + let (mut k, mut current) = (0.0, first.clone()); + loop { + let next = |k: f64| side * (k.abs() + unit).min(reach); + let mut far = next(k); + while along(far).ok().as_ref() == Some(¤t) && far.abs() < reach { + k = far; + far = next(k); + } + if along(far).ok().as_ref() == Some(¤t) { + break; + } + let (mut same, mut changed) = (k, far); + loop { + let mid = same + (changed - same) / 2.0; + if mid == same || mid == changed { + break; + } + if along(mid).ok().as_ref() == Some(¤t) { same = mid } else { changed = mid } + } + let Ok(p) = along(changed) else { break }; + if along_angle(&p) && best.as_ref().is_none_or(|b| changed.abs() > b.0.abs()) { + best = Some((changed, p.clone())); + } + (k, current) = (changed, p); + } + } + best.map(|(_, p)| p) + }; + let farthest = |end: f64| -> Option<(f64, Vec)> { + let (mut ok, mut bad) = (0.0, end); + loop { + let mid = ok + (bad - ok) / 2.0; + if mid == ok || mid == bad { + break; + } + if along(mid).is_ok() { ok = mid } else { bad = mid } + } + along(ok).ok().map(|p| (ok, p)) + }; + let second = full + .or_else(|| { + [farthest(GUIDE_REACH), farthest(-GUIDE_REACH)] + .into_iter() + .flatten() + .filter(|(_, p)| along_angle(p)) + .reduce(|a, b| if b.0.abs() > a.0.abs() { b } else { a }) + .map(|(_, p)| p) + }) + .or_else(stepped) + .ok_or(Error::Unwritable("guidelines with no room for a second point along their angle"))?; + let mut arg = vec![0; 12]; + arg.extend(stored); + arg.extend(&first); + arg.extend(second); + arg.extend(first); + out.open(b"obj ")?; + out.chunk(b"flgs", &flags(Flags { hidden: g.hidden, locked: false }, 0, 0, 0x08))?; + out.open(b"lgob")?; + self.loda(out, GUIDELINE, &[(ARG_GUIDE, arg)])?; + out.close()?; + out.close() + } + + /// `objects`, front to back, groups nested, without recursion. + fn objects(&mut self, out: &mut Out, objects: &'d [Object]) -> Result<(), Error> { + // The objects left at each level, the layer's and then each group's, with the group's + // flags. The reader leaves out a group that holds no shape or container, so a group's list + // is written only when the first one is reached: the first `written` levels have theirs. + let mut levels = vec![(objects.iter(), Flags::default())]; + let mut written = 1; + loop { + let Some((level, _)) = levels.last_mut() else { return Ok(()) }; + let Some(object) = level.next() else { + levels.pop(); + if levels.is_empty() { + return Ok(()); + } + if written > levels.len() { + written = levels.len(); + // The reader counts a group once its objects are read. + self.take_object()?; + out.close()?; + } + continue; + }; + if let Object::Group { objects, flags } = object { + // Groups nested past the depth are refused even when they hold nothing, so the + // walk holds no more levels than that. This group is `levels.len()` deep. + if levels.len() > self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + if !objects.is_empty() { + levels.push((objects.iter(), *flags)); + } + continue; + } + for (_, f) in levels.get(written..).unwrap_or_default() { + self.walk(2)?; + out.open(b"grp ")?; + out.chunk(b"flgs", &flags(*f, 0, 0, 0x10))?; + } + written = levels.len(); + match object { + Object::Shape(s) => { + self.walk(OBJECT_WALK)?; + self.shape(out, s, None)?; + } + Object::Group { .. } => {} + Object::Clip { container, objects } => { + self.walk(OBJECT_WALK)?; + // The reader reads a container whose objects hold no shape as a plain shape. + if !draws(objects, &self.limits)? { + self.shape(out, container, None)?; + continue; + } + let depth = self.clip_depth + 1; + if depth > MAX_CLIP_DEPTH { + return Err(Error::Limit("clip nesting")); + } + // Ids 1, 2, 3 ..., the same in the container and its group's `spnd` (R46, R73). + let id = len32(self.clips.len() + 1)?; + if self.clips.is_empty() { + // The `doc` list's `LIST clpt`, which holds the clipped groups. + self.counted.set(self.counted.get().saturating_add(1)); + } + self.clips.push((id, objects, depth)); + self.shape(out, container, Some(id))?; + } + } + } + } + + /// The `LIST clpt` body: one group for each container, holding the objects it clips (R46); + /// `None` without containers. The groups' own objects may name more groups. + fn clipped_groups(&mut self) -> Result, Error> { + if self.clips.is_empty() { + return Ok(None); + } + // `doc` and `clpt` are around the groups. + let mut out = Out::new(2, self.limits, self.total.clone(), self.counted.clone()); + let mut i = 0; + // The reader steps through a clipped group's `spnd` and flags, then the lists of its + // objects, each time a container names the group; each container names its own. + while let Some(&(id, objects, depth)) = self.clips.get(i) { + i += 1; + self.clip_depth = depth; + self.walk(2)?; + out.open(b"grp ")?; + out.chunk(b"spnd", &id.to_le_bytes())?; + // Byte 2 marks the group a container clips (R67). + out.chunk(b"flgs", &flags(Flags::default(), 0, 0x80, 0x10))?; + self.objects(&mut out, objects)?; + out.close()?; + } + Ok(Some(out)) + } + + /// One shape's object list (R19, R22): flags, then its `loda` and its transform in a `lgob` + /// list. `clip` names the group it clips. + fn shape(&mut self, out: &mut Out, s: &Shape, clip: Option) -> Result<(), Error> { + self.take_object()?; + // The arguments the shape's `loda` takes, counted before its points are encoded: the + // outline, the fill and the coordinates, and the winding, transparency and container + // arguments it carries. + let opacity = share(s.opacity)?; + let seen_through = opacity < 1.0 || s.blend != Blend::Normal; + let arguments = 3 + usize::from(s.nonzero) + usize::from(seen_through) + usize::from(clip.is_some()); + if arguments > self.limits.arguments { + return Err(Error::Limit("argument count")); + } + // The fill and outline records the shape names, added before its points are encoded so + // that they count toward the limits first. + let outline = self.outline(s.outline.as_ref())?; + let fill = self.fill(s.fill.as_ref())?; + // The transparency record names a white uniform fill as the sample files do (R69). + let white = if seen_through { Some(self.fill(Some(&Color::Rgb([1.0; 3])))?) } else { None }; + // The object's lists, `obj `, `lgob` and `trfl`, and its chunks, those three with `flgs`, + // `loda` and `trfd`. + out.fits(3, 6)?; + let (kind, coords) = self.geometry(&s.geometry, &s.matrix)?; + let mut args = vec![(ARG_OUTLINE, outline.to_le_bytes().to_vec()), (ARG_FILL, fill.to_le_bytes().to_vec()), (ARG_COORDS, coords)]; + if s.nonzero { + args.push((ARG_WINDING, vec![1, 0, 0, 0])); + } + // Byte 2 of the flags marks an object seen through (0x08) and a clipping container (0x10) + // (R67). + let mut byte2 = 0; + if let Some(white) = white { + args.push((ARG_TRANSPARENCY, transparency(opacity, s.blend, white))); + byte2 |= 0x08; + } + if clip.is_some() { + byte2 |= 0x10; + } + if let Some(id) = clip { + // As sample files lay it out (R46). + args.push((ARG_CONTAINER, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect())); + } + out.open(b"obj ")?; + out.chunk(b"flgs", &flags(s.flags, 0, byte2, 0x08))?; + out.open(b"lgob")?; + self.loda(out, kind, &args)?; + out.open(b"trfl")?; + out.chunk(b"trfd", &trfd(&s.matrix)?)?; + out.close()?; + out.close()?; + out.close() + } + + /// The object type and coordinates argument of `g`, drawn through `m`. + fn geometry(&mut self, g: &Geometry, m: &Matrix) -> Result<(u32, Vec), Error> { + Ok(match g { + Geometry::Rect { w, h, radii } => (RECTANGLE, rect(*w, *h, radii, m)?), + Geometry::Ellipse { w, h } => { + // Equal start and end angles: a whole ellipse (R17). + let mut b = [coord(*w)?, coord(*h)?].concat(); + b.extend([0; 12]); + (ELLIPSE, b) + } + Geometry::Path(p) => (CURVE, self.points(p)?), + }) + } + + /// A curve's point list (R16): the count, the points, then their type bytes. + fn points(&mut self, path: &Path) -> Result, Error> { + // A subpath without segments draws nothing, and the reader leaves it out. + let drawn = || path.subpaths.iter().filter(|s| !s.segments.is_empty()); + // A closed subpath ends with a point at its start (R68): a closing line is added when its + // last segment ends elsewhere. + let adds_close = |sp: &SubPath| -> Result { + let end = match sp.segments.last() { + Some(Segment::Line(p) | Segment::Cubic(_, _, p)) => *p, + None => return Ok(false), + }; + Ok(sp.closed && [coord(end.x)?, coord(end.y)?] != [coord(sp.start.x)?, coord(sp.start.y)?]) + }; + // `n` points within the coordinate count and, at two coordinates and a type byte each, on + // top of what the file holds so far, within its size. + let fits = |n: usize| -> Result<(), Error> { + if self.coordinates.saturating_add(n) > self.limits.coordinates { + return Err(Error::Limit("coordinate count")); + } + fits_stream(&self.limits, self.total.get().saturating_add(n.saturating_mul(9)).saturating_add(4)) + }; + // A subpath takes at least a point for its start and one for each segment, so a path past + // either limit stops before its segments are looked at one by one, and the count stops + // at the segment that takes it past. + let mut n = 0usize; + for sp in drawn() { + fits(n.saturating_add(sp.segments.len()).saturating_add(1))?; + n = n.saturating_add(1); + for s in &sp.segments { + n = n.saturating_add(if matches!(s, Segment::Line(_)) { 1 } else { 3 }); + fits(n)?; + } + n = n.saturating_add(usize::from(adds_close(sp)?)); + fits(n)?; + } + fits(n)?; + self.coordinates = self.coordinates.saturating_add(n); + // The record: the count, the points, then the type bytes, which go in their own buffer. + let mut b = Vec::with_capacity(4 + n * 9); + b.extend(len32(n)?.to_le_bytes()); + let mut types: Vec = Vec::with_capacity(n); + let mut put = |p: Pt, t: u8| -> Result<(), Error> { + b.extend(coord(p.x)?); + b.extend(coord(p.y)?); + types.push(t); + Ok(()) + }; + for sp in drawn() { + let added = adds_close(sp)?; + put(sp.start, EDITABLE | if sp.closed { CLOSES } else { 0 })?; + let last = sp.segments.len().saturating_sub(1); + for (i, seg) in sp.segments.iter().enumerate() { + // The end that closes the subpath is not editable; every other end is (R68). + let end = if sp.closed && !added && i == last { CLOSES } else { EDITABLE }; + match *seg { + Segment::Line(p) => put(p, LINE | end)?, + Segment::Cubic(c1, c2, p) => { + put(c1, CONTROL)?; + put(c2, CONTROL)?; + put(p, CURVE_END | end)?; + } + } + } + if added { + put(sp.start, LINE | CLOSES)?; + } + } + b.extend(types); + Ok(b) + } + + /// The id of the fill record of `color` (R11): a uniform fill, or a fill of type 0 for none. + fn fill(&mut self, color: Option<&Color>) -> Result { + let mut body = Vec::new(); + match color { + None => body.extend(0u16.to_le_bytes()), + Some(c) => { + let props = properties(c, true)?; + body.extend(1u16.to_le_bytes()); + body.extend(TAG_1300.to_le_bytes()); + body.extend(len32(props.len())?.to_le_bytes()); + body.extend(props); + // The 8 bytes that end a uniform fill (R66). + body.extend([0; 8]); + } + } + let mut record = TAG_1300.to_le_bytes().to_vec(); + record.extend(len32(body.len())?.to_le_bytes()); + record.extend(body); + // Each fill record sits in a `LIST filc` of its own (R72). + Self::record(&mut self.fills, &mut self.next_id, record, true, &self.limits, [&self.total, &self.counted]) + } + + /// The id of the outline record of `outline` (R12, R13, R48, R49, R50); without one, an + /// outline whose line type says none. + fn outline(&mut self, outline: Option<&Outline>) -> Result { + let none = Outline { + width: 0.0, + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let o = outline.unwrap_or(&none); + // Dash and gap lengths in whole outline widths, as u16, in the room before the arrowhead + // ids (R12). + if o.dashes.len() > MAX_DASHES { + return Err(Error::Unwritable("dash patterns of more than 10 lengths")); + } + if o.dashes.iter().any(|d| !(d.is_finite() && *d >= 0.0)) { + return Err(Error::Unwritable("dash lengths that are negative or not finite")); + } + if o.dashes.iter().any(|d| d.round() > f64::from(u16::MAX)) { + return Err(Error::Unwritable("dash lengths past 65,535 outline widths")); + } + let dashes: Vec = o.dashes.iter().map(|d| d.round() as u16).collect(); + let dashed = outline.is_some() && dashes.iter().any(|d| *d > 0); + // A pattern whose lengths all round to 0 reads back as a solid line, without its lengths + // (R48). + if outline.is_some() && !dashed && !o.dashes.is_empty() { + return Err(Error::Unwritable("dash patterns whose lengths all round to 0 outline widths")); + } + if dashed { + // The reader counts an outline's dashes for every shape that uses it. + self.dashes = self.dashes.saturating_add(dashes.len()); + if self.dashes > self.limits.dashes { + return Err(Error::Limit("dash count")); + } + } + // Bit 0 no outline (R13), 1 as in the plain outlines of sample files (R49), 2 dashed (R48), + // 4 behind the fill (R49), 5 scaled with the shape (R50). + let line_type: u16 = match outline { + None => 1, + Some(o) => 0x02 | if dashed { 0x04 } else { 0 } | if o.behind_fill { 0x10 } else { 0 } | if o.scale_with { 0x20 } else { 0 }, + }; + let color = color_record(&o.color)?; + let mut body = Vec::new(); + // A library color is named in a record of type 2 (R12). + if matches!(o.color, Color::Spot { .. }) { + // An outline's list ends at its empty property (R71). + let props = properties(&o.color, false)?; + body.extend(2u32.to_le_bytes()); + body.extend(len32(props.len())?.to_le_bytes()); + body.extend(props); + } + let mut fields = Vec::new(); + for v in [line_type, cap(o.cap), join(o.join)] { + fields.extend(v.to_le_bytes()); + } + if o.width < 0.0 { + return Err(Error::Unwritable("negative outline widths")); + } + let width = coord(o.width)?; + // A width of 0 reads back as no width, which a positive width must not become. + if o.width > 0.0 && width == [0; 4] { + return Err(Error::Unwritable("outline widths that round to 0")); + } + fields.extend(width); + // The stretch, 100 percent, and 2 bytes; the nib angle and 46 bytes. + fields.extend(100u16.to_le_bytes()); + fields.extend([0; 2]); + fields.extend(angle(0.0)?); + fields.extend([0; 46]); + fields.extend(color); + fields.extend([0; 16]); + fields.extend((dashes.len() as u16).to_le_bytes()); + let mut slots = [0u8; 2 * MAX_DASHES]; + for (slot, b) in slots.iter_mut().zip(dashes.iter().flat_map(|d| d.to_le_bytes())) { + *slot = b; + } + fields.extend(slots); + // The start and end arrowhead ids (none), and the rest of the record. + fields.extend([0; 16]); + // As sample files hold them (R71): an f64 1 at bytes 16 and 48, and 45 degrees and 60 at + // bytes 84 and 88. + let one = 1f64.to_le_bytes(); + let patches: [(usize, &[u8]); 4] = [(16, &one), (48, &one), (84, &45_000_000i32.to_le_bytes()), (88, &60u32.to_le_bytes())]; + for (at, bytes) in patches { + for (slot, b) in fields.iter_mut().skip(at).zip(bytes) { + *slot = *b; + } + } + body.extend(1u32.to_le_bytes()); + body.extend(len32(fields.len())?.to_le_bytes()); + body.extend(fields); + // 8 bytes follow the record (R71). + body.extend([0; 8]); + Self::record(&mut self.outlines, &mut self.next_id, body, false, &self.limits, [&self.total, &self.counted]) + } + + /// The id of the record with `body`, adding it when it is new. Its chunk, with its header, + /// its id and its pad byte, and the list around it when `wrapped`, count toward the file's + /// bytes and chunks. + fn record( + records: &mut Records, + next_id: &mut u32, + body: Vec, + wrapped: bool, + limits: &Limits, + spent: [&Cell; 2], + ) -> Result { + if let Some(id) = records.ids.get(body.as_slice()) { + return Ok(*id); + } + let [total, counted] = spent; + let chunk = body.len().saturating_add(4); + let n = total.get().saturating_add(8).saturating_add(chunk).saturating_add(chunk % 2).saturating_add(if wrapped { 12 } else { 0 }); + fits_stream(limits, n)?; + let chunks = counted.get().saturating_add(1 + usize::from(wrapped)); + if chunks > limits.chunks { + return Err(Error::Limit("chunk count")); + } + total.set(n); + counted.set(chunks); + let id = *next_id; + *next_id = next_id.checked_add(1).ok_or(Error::Limit("output size"))?; + let body: Rc<[u8]> = body.into(); + records.bodies.push((id, body.clone())); + records.ids.insert(body, id); + Ok(id) + } +} + +/// Whether `objects` hold a shape or a container. Groups that hold only empty groups draw nothing, +/// and the reader leaves them out. Groups nested past the depth are refused, as +/// [`Writer::objects`] refuses them. +fn draws(objects: &[Object], limits: &Limits) -> Result { + let mut open = vec![objects.iter()]; + while let Some(level) = open.last_mut() { + match level.next() { + None => { + open.pop(); + } + Some(Object::Group { objects, .. }) => { + if open.len() > limits.depth { + return Err(Error::Limit("nesting depth")); + } + open.push(objects.iter()); + } + Some(_) => return Ok(true), + } + } + Ok(false) +} + +/// Point type bytes (R16): a line end, a control point, a curve end, and bit 3, which closes the +/// subpath; bit 2 marks a node that can be edited (R68). +const LINE: u8 = 0x40; +const CONTROL: u8 = 0xC0; +const CURVE_END: u8 = 0x80; +const CLOSES: u8 = 0x08; +const EDITABLE: u8 = 0x04; + +/// A `flgs` chunk (R19): bit 0x10 of byte 0 locks, bit 0x01 of byte 1 hides; byte 3 the record +/// type. +fn flags(f: Flags, byte0: u8, byte2: u8, kind: u8) -> [u8; 4] { + [byte0 | if f.locked { 0x10 } else { 0 }, u8::from(f.hidden), byte2, kind] +} + +/// A length in points as an i32 coordinate (R5). +fn coord(pt: f64) -> Result<[u8; 4], Error> { + let units = (pt * UNITS_PER_PT).round(); + if !(units.is_finite() && (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&units)) { + return Err(Error::Unwritable("coordinates past the file's range")); + } + Ok((units as i32).to_le_bytes()) +} + +/// A page's width and height as coordinates (R10, R21); the reader takes a size only when both +/// are above 0. +fn page_size((w, h): (f64, f64)) -> Result, Error> { + if !((w * UNITS_PER_PT).round() >= 1.0 && (h * UNITS_PER_PT).round() >= 1.0) { + return Err(Error::Unwritable("page sizes that are not above 0")); + } + Ok([coord(w)?, coord(h)?].concat()) +} + +/// An angle in degrees as i32 millionths (R7). +fn angle(deg: f64) -> Result<[u8; 4], Error> { + let fits = |v: f64| (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&v); + let v = (deg * 1_000_000.0).round(); + // An angle past the field's range is written as the same angle within one turn. + let v = if fits(v) { v } else { (deg.rem_euclid(360.0) * 1_000_000.0).round() }; + if !v.is_finite() { + return Err(Error::Unwritable("angles that are not finite")); + } + Ok((v as i32).to_le_bytes()) +} + +/// A finite f64, or [`WriteError::Unwritable`]. +fn finite(v: f64, what: &'static str) -> Result<[u8; 8], Error> { + if v.is_finite() { Ok(v.to_le_bytes()) } else { Err(Error::Unwritable(what)) } +} + +/// The `mcfg` chunk (R10, R72): the tag 1300, the length of the rest and 4 bytes, the page width +/// and height, then 16 bytes. +fn mcfg(size: (f64, f64)) -> Result, Error> { + let mut b = TAG_1300.to_le_bytes().to_vec(); + b.extend([0; 8]); + b.extend(page_size(size)?); + b.extend([0; 16]); + let rest = len32(b.len() - 8)?.to_le_bytes(); + if let Some(slot) = b.get_mut(4..8) { + slot.copy_from_slice(&rest); + } + Ok(b) +} + +/// A `trfd` record of one matrix (R8, R51, R65): length, count, where the offsets lie and 0xFFFF; +/// the offsets with one more for the end; then the entry: the tag 1300 and a u32 0, type 8, 6 +/// bytes, `a c tx b d ty` as f64 with the offsets in coordinate units, and 8 bytes. +fn trfd(m: &Matrix) -> Result, Error> { + const ENTRY_AT: u32 = 24; + const ENTRY_LEN: u32 = 8 + 2 + 6 + 48 + 8; + let [a, b, c, d, e, f] = m.0; + let mut out = Vec::with_capacity((ENTRY_AT + ENTRY_LEN) as usize); + for v in [ENTRY_AT + ENTRY_LEN, 1, 16, 0xFFFF, ENTRY_AT, ENTRY_AT + ENTRY_LEN] { + out.extend(v.to_le_bytes()); + } + out.extend(TAG_1300.to_le_bytes()); + out.extend([0; 4]); + out.extend(8u16.to_le_bytes()); + out.extend([0; 6]); + for v in [a, c, e * UNITS_PER_PT, b, d, f * UNITS_PER_PT] { + out.extend(finite(v, "transforms that are not finite")?); + } + out.extend([0; 8]); + Ok(out) +} + +/// Rectangle coordinates (R29): width and height in coordinate units as f64, the scale factors +/// 1 and 1, the scale-with flag clear and 7 bytes, then each corner's radius as a share of half the +/// shorter side, 16 bytes apart. +fn rect(w: f64, h: f64, radii: &[f64; 4], m: &Matrix) -> Result, Error> { + // The reader takes sizes within the range of 32-bit coordinates, as stored. + // Within half a unit of the range is the range, as conversion rounding can carry a size the + // reader gave just past it. + let max = f64::from(i32::MAX); + let stored = |v: f64| -> Result { + let u = v * UNITS_PER_PT; + if !(u.is_finite() && u.abs() <= max + 0.5) { + return Err(Error::Unwritable("coordinates past the file's range")); + } + Ok(u.clamp(-max, max)) + }; + let (wu, hu) = (stored(w)?, stored(h)?); + let half = w.abs().min(h.abs()) / 2.0; + // The reader holds a corner to half the shorter side. + if radii.iter().any(|r| !(r.is_finite() && *r >= 0.0 && *r <= half * (1.0 + 1e-9))) { + return Err(Error::Unwritable("corner radii below 0 or past half the shorter side")); + } + // The scale fields repeat the transform's scale (R29): the lengths its x and y axes take, the + // writer's own reading for a transform that also turns or skews. + let [a, b, c, d, ..] = m.0; + let (sx, sy) = (a.hypot(b), c.hypot(d)); + if !(sx.is_finite() && sy.is_finite()) { + return Err(Error::Unwritable("transforms that are not finite")); + } + let mut out = Vec::with_capacity(32 + 8 + 4 * 8 + 3 * 16); + for v in [wu, hu, sx, sy] { + out.extend(v.to_le_bytes()); + } + out.extend([0; 8]); + for (k, r) in radii.iter().enumerate() { + if k > 0 { + out.extend([0; 16]); + } + let share = if half > 0.0 { (r / half).min(1.0) } else { 0.0 }; + out.extend(share.to_le_bytes()); + } + Ok(out) +} + +/// A value from 0 to 1 as a byte from 0 to 255. +fn byte(v: f32) -> Result { + Ok((share(v)? * 255.0).round() as u8) +} + +/// `v` when it is from 0 to 1, as colors, tints and opacity are. +fn share(v: f32) -> Result { + if (0.0..=1.0).contains(&v) { Ok(v) } else { Err(Error::Unwritable("color values, tints or opacity outside 0 to 1")) } +} + +/// A 12-byte color record (R14): model, palette, 4 bytes, four value bytes. RGB is model 5 (blue, +/// green, red), CMYK model 3 (0 to 255), gray model 9, registration model 20; a library color is +/// model 21, its full-strength look mixed toward white by its tint and the tint in percent last. +/// A library color without a look is written black. +fn color_record(c: &Color) -> Result<[u8; 12], Error> { + let (model, v): (u16, [u8; 4]) = match c { + Color::Rgb([r, g, b]) => (5, [byte(*b)?, byte(*g)?, byte(*r)?, 0]), + Color::Cmyk([c, m, y, k]) => (3, [byte(*c)?, byte(*m)?, byte(*y)?, byte(*k)?]), + Color::Gray(ink) => (9, [byte(1.0 - share(*ink)?)?, 0, 0, 0]), + Color::Registration => (20, [0; 4]), + Color::Spot { tint, look, .. } => { + // The tint is stored in whole percent; at 0 the stored color is white whatever the + // look, which the reader can't take off again. + let percent = (share(*tint)? * 100.0).round(); + if percent < 1.0 { + return Err(Error::Unwritable("spot colors at a tint below 0.5 percent")); + } + let t = percent / 100.0; + let [r, g, b] = look.unwrap_or([0.0; 3]); + // The reader takes the tint off again (`records::untinted`); a low tint leaves too few + // steps of the stored byte for the look to come back within one step. + // The nearest byte to the tinted value is written, or the other byte around it when + // only that one reads back within the step. + let tinted = |v: f32| -> Result { + let ideal = (1.0 - (1.0 - share(v)?) * t) * 255.0; + let reads_back = |s: &f32| ((1.0 - (1.0 - s / 255.0) / t).clamp(0.0, 1.0) - v).abs() <= 1.0 / 255.0 + 1e-6; + match [ideal.round(), ideal.floor(), ideal.ceil()].into_iter().find(reads_back) { + Some(s) => Ok(s.clamp(0.0, 255.0) as u8), + None => Err(Error::Unwritable("spot colors at a tint too low to keep their look")), + } + }; + (21, [tinted(b)?, tinted(g)?, tinted(r)?, percent as u8]) + } + }; + let mut out = [0; 12]; + for (slot, b) in out.iter_mut().zip(model.to_le_bytes().into_iter().chain([0; 6]).chain(v)) { + *slot = b; + } + Ok(out) +} + +/// A property list (R11, R12): the color, and for a library color its name in a property of type 8 +/// (16 bytes, then the count of UTF-16 units and the units); an empty property ends it. With +/// `tail`, the fields a fill's list has after that follow (R66). +fn properties(c: &Color, tail: bool) -> Result, Error> { + let mut out = vec![1]; + out.extend(12u32.to_le_bytes()); + out.extend(color_record(c)?); + if let Color::Spot { name, .. } = c { + // A color without a name reads back as a process color. + if name.is_empty() { + return Err(Error::Unwritable("spot colors without a name")); + } + let units = units(name)?; + let mut body = vec![0; 16]; + body.extend(len32(units.len())?.to_le_bytes()); + body.extend(units.iter().flat_map(|u| u.to_le_bytes())); + out.push(8); + out.extend(len32(body.len())?.to_le_bytes()); + out.extend(body); + } + out.extend([0; 5]); + if tail { + // After a fill's list (R66): two u16, the overprint flag (u32), an angle and a u32. The + // first u16, the angle and the last u32 hold the values the specification names as usual + // (0, 45 degrees and 60); the second u16 and the flag hold 0, a value sample files hold + // there. + out.extend([0; 8]); + out.extend(45_000_000i32.to_le_bytes()); + out.extend(60u32.to_le_bytes()); + } + Ok(out) +} + +/// A name argument (R9): UTF-16LE and a closing NUL. +fn name(s: &str) -> Result, Error> { + Ok(units(s)?.into_iter().chain([0]).flat_map(u16::to_le_bytes).collect()) +} + +/// The UTF-16 units of a name the reader reads back whole: at most [`MAX_NAME`] of them, without +/// a NUL, where a name ends. +fn units(s: &str) -> Result, Error> { + let units: Vec = s.encode_utf16().take(MAX_NAME + 1).collect(); + if units.len() > MAX_NAME || units.contains(&0) { + return Err(Error::Unwritable("names longer than 256 UTF-16 units or holding a NUL")); + } + Ok(units) +} + +fn cap(c: Cap) -> u16 { + match c { + Cap::Butt => 0, + Cap::Round => 1, + Cap::Square => 2, + } +} + +fn join(j: Join) -> u16 { + match j { + Join::Miter => 0, + Join::Round => 1, + Join::Bevel => 2, + } +} + +/// Argument 8000 of a uniform transparency (R47): a record tagged 1300 whose 117-byte body holds +/// the transparency in percent (f64) at byte 61, the merge mode at byte 77 and the id of `fill` at +/// byte 105 (R69), with the other fields as the sample files hold them (R69). +fn transparency(opacity: f32, blend: Blend, fill: u32) -> Vec { + let mut body = [0u8; 117]; + let percent = (1.0 - f64::from(opacity)) * 100.0; + let fields: [(usize, &[u8]); 6] = [ + (0, &261u32.to_le_bytes()), + (57, &u32::MAX.to_le_bytes()), + (61, &percent.to_le_bytes()), + (69, &100f64.to_le_bytes()), + (77, &[merge(blend), 0, 0, 0, 2]), + (105, &fill.to_le_bytes()), + ]; + for (at, bytes) in fields { + for (slot, b) in body.iter_mut().skip(at).zip(bytes) { + *slot = *b; + } + } + let mut out = TAG_1300.to_le_bytes().to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + out +} + +/// The merge mode byte of `blend` (R47). +fn merge(blend: Blend) -> u8 { + match blend { + Blend::Normal => 0, + Blend::Multiply => 9, + Blend::Lighten => 11, + Blend::Darken => 12, + Blend::Color => 14, + Blend::Hue => 15, + Blend::Saturation => 16, + Blend::Luminosity => 17, + Blend::Difference => 24, + Blend::Screen => 28, + Blend::Overlay => 29, + Blend::SoftLight => 30, + Blend::HardLight => 31, + Blend::ColorDodge => 33, + Blend::ColorBurn => 34, + Blend::Exclusion => 36, + } +} + +/// A ZIP archive (R24) dated 1980-01-01: the stored `mimetype` member (R64), then the RIFF file +/// made of `riff`'s parts, deflated (R25). The parts are compressed as they are, without being +/// joined first, straight into the archive after the member's header. `craft_zip::Writer` streams +/// an entry only with ZIP64 size fields, which `zip.rs` refuses, and otherwise takes one slice. +fn package(riff: &[&[u8]]) -> Result, Error> { + let size = riff.iter().map(|p| p.len()).fold(0usize, usize::saturating_add); + let mut out = Vec::new(); + let mut dir = Vec::with_capacity(160); + let at = header(&mut out, MIMETYPE_NAME, 0, crc32fast::hash(MIMETYPE), MIMETYPE.len(), MIMETYPE.len())?; + out.extend(MIMETYPE); + entry(&mut dir, &out, at, MIMETYPE_NAME)?; + // The RIFF file's CRC-32 and packed size go in its header once it is compressed. + let at = header(&mut out, MEMBER, 8, 0, 0, size)?; + let start = out.len(); + let mut crc = crc32fast::Hasher::new(); + let mut e = flate2::write::DeflateEncoder::new(out, flate2::Compression::default()); + for part in riff { + crc.update(part); + e.write_all(part).map_err(|_| Error::Limit("output size"))?; + } + let mut out = e.finish().map_err(|_| Error::Limit("output size"))?; + let fields = [crc.finalize(), len32(out.len() - start)?].map(u32::to_le_bytes).concat(); + if let Some(slot) = out.get_mut(at + 14..at + 22) { + slot.copy_from_slice(&fields); + } + entry(&mut dir, &out, at, MEMBER)?; + let dir_at = len32(out.len())?; + let dir_len = len32(dir.len())?; + out.extend(dir); + out.extend(0x0605_4b50u32.to_le_bytes()); + out.extend([0; 4]); + out.extend(2u16.to_le_bytes()); + out.extend(2u16.to_le_bytes()); + out.extend(dir_len.to_le_bytes()); + out.extend(dir_at.to_le_bytes()); + out.extend(0u16.to_le_bytes()); + Ok(out) +} + +/// A member's local header into `out`, stored (`method` 0) or deflated (8), with the CRC-32, the +/// packed size and the full size of its bytes; where the header starts. +fn header(out: &mut Vec, name: &[u8], method: u16, crc: u32, packed: usize, size: usize) -> Result { + let at = out.len(); + out.extend(0x0403_4b50u32.to_le_bytes()); + // Version needed, flags, method, time, date, CRC-32, packed and full sizes, name length. + for v in [20, 0, method, 0, 0x21] { + out.extend(v.to_le_bytes()); + } + for v in [crc, len32(packed)?, len32(size)?] { + out.extend(v.to_le_bytes()); + } + out.extend((name.len() as u16).to_le_bytes()); + // No extra field. + out.extend(0u16.to_le_bytes()); + out.extend(name); + Ok(at) +} + +/// The central directory entry into `dir` of the member whose local header is at `at` in `out`. +fn entry(dir: &mut Vec, out: &[u8], at: usize, name: &[u8]) -> Result<(), Error> { + dir.extend(0x0201_4b50u32.to_le_bytes()); + // Made by version 2.0, then the local header's fields from the version needed to the name + // length. + dir.extend(20u16.to_le_bytes()); + dir.extend(out.get(at + 4..at + 28).ok_or(Error::Limit("output size"))?); + // Extra and comment lengths, disk, internal and external attributes, then the header's offset. + dir.extend([0; 12]); + dir.extend(len32(at)?.to_le_bytes()); + dir.extend(name); + Ok(()) +} diff --git a/crates/cdr/tests/it/cmx.rs b/crates/cdr/tests/it/cmx.rs index 0067d981b7..dab5ddd08e 100644 --- a/crates/cdr/tests/it/cmx.rs +++ b/crates/cdr/tests/it/cmx.rs @@ -1,11 +1,39 @@ //! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and //! hostile ones. -use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape}; +use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Page, Shape}; use craft_cdr::synth_cmx::*; -use craft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx}; +use craft_cdr::{Drawing, Error, Limits, Warning, is_cdr, is_cmx, read_cmx}; use proptest::prelude::*; +/// Read `bytes`, and check that the reader never reads less than it does when it resumes after +/// stray bytes only at the first chunk id found (R53): when that read succeeds, this one does too, +/// and every page that read holds with objects is read here unchanged and in the same order. +fn read_checked(bytes: &[u8], limits: Limits) -> Result { + read_compared(bytes, limits, |p, q| p == q) +} + +/// As [`read_checked`], except that a page only has to keep its layers and the number of objects +/// on each: a header or a table that only the recovery reads may change their colors and sizes +/// (R53). +fn read_kept(bytes: &[u8], limits: Limits) -> Result { + read_compared(bytes, limits, |p, q| { + p.layers.len() == q.layers.len() && p.layers.iter().zip(&q.layers).all(|(a, b)| a.name == b.name && a.objects.len() == b.objects.len()) + }) +} + +fn read_compared(bytes: &[u8], limits: Limits, same: fn(&Page, &Page) -> bool) -> Result { + let d = read_cmx(bytes, limits); + if let Ok(first) = read_cmx_without_recovery(bytes, limits) { + let Ok(read) = &d else { panic!("{d:?} where the first chunk id gives {first:?}") }; + let mut rest = read.pages.iter(); + for p in first.pages.iter().filter(|p| !p.layers.is_empty()) { + assert!(rest.any(|q| same(q, p)), "{p:?} is not read"); + } + } + d +} + fn shape(o: &Object) -> &Shape { match o { Object::Shape(s) => s, @@ -52,7 +80,7 @@ fn a_cmx_file_is_told_from_a_cdr_drawing() { #[test] fn pages_layers_groups_and_curves() { - let d = read_cmx(&sample(), Limits::default()).unwrap(); + let d = read_checked(&sample(), Limits::default()).unwrap(); assert_eq!(d.version, 0); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); @@ -107,7 +135,7 @@ fn layer_names_and_layers_without_objects() { end_layer(), end_page(), ]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); let page = &d.pages[0]; assert_eq!(page.size, None); // The empty layer is left out, and the UTF-16 name wins over the 8-bit one. @@ -118,7 +146,7 @@ fn layer_names_and_layers_without_objects() { #[test] fn objects_before_any_layer_get_one() { let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert_eq!(d.pages[0].layers.len(), 1); // The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place. assert_eq!(d.pages[0].layers[0].name, ""); @@ -134,7 +162,7 @@ fn a_page_without_a_size_takes_the_drawings_bounds() { end_layer(), end_page(), ]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); let page = &d.pages[0]; let side = 100.0 / 25.4 * 72.0; let (w, h) = page.size.unwrap(); @@ -150,7 +178,7 @@ fn curves_and_open_groups() { curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]); // A group the layer leaves open closes with it. let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); let objects = &d.pages[0].layers[0].objects; let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") }; let s = shape(&kids[0]); @@ -164,7 +192,7 @@ fn curves_and_open_groups() { #[test] fn a_curve_without_its_points_is_reported() { let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); } @@ -174,7 +202,7 @@ fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() { d.extend(b"Art"); let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])])); let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert_eq!(d.pages[0].layers[0].name, "Art"); } @@ -192,7 +220,7 @@ fn what_is_not_read_is_reported() { square(&attrs(Some(1), None, true), 0, 0, 1000), end_layer(), ]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] { assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings); } @@ -213,7 +241,7 @@ fn colors_of_other_models_and_missing_entries() { square(&attrs(Some(2), None, false), 0, 0, 1000), ])); children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); let objects = &d.pages[0].layers[0].objects; assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0]))); @@ -231,7 +259,7 @@ fn gray_cmy_and_rgb_colors_of_the_older_fields() { square(&attrs(Some(3), None, false), 0, 0, 1000), ])); children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); let objects = &d.pages[0].layers[0].objects; // The model holds objects front to back: the RGB square, the CMY one, then the gray one. @@ -251,7 +279,7 @@ fn outline_arrowheads_are_reported() { children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota"))); children.push(arrowheads(&[(0, 2)])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert_eq!(d.warnings, vec![Warning::Arrowheads]); } @@ -275,7 +303,7 @@ fn a_long_instruction_and_a_jump_over_image_bytes() { .concat(); let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); // The images jumped over are not read, and the warning says so. assert_eq!(d.warnings, [Warning::UnsupportedObjects]); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -286,7 +314,7 @@ fn bytes_after_a_chunk_that_runs_short_are_passed_over() { let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff]; let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -295,12 +323,12 @@ fn bytes_after_a_chunk_that_runs_short_are_passed_over() { fn other_byte_orders_and_coordinate_sizes_are_refused() { let mut f = sample(); f[..4].copy_from_slice(b"RIFX"); - assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files"))); + assert_eq!(read_checked(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files"))); let mut children = vec![cont(b'2', 1e-3)]; children.extend(tables()); - assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates"))); - assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header"))); - assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header"))); + assert_eq!(read_checked(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates"))); + assert_eq!(read_checked(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header"))); + assert_eq!(read_checked(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header"))); } #[test] @@ -308,7 +336,7 @@ fn a_header_without_a_usable_unit_reads_0_1_micrometers() { for meters in [0.0, -1.0, f64::NAN, 2.0] { let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); let (w, _) = d.pages[0].size.unwrap(); assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}"); } @@ -325,7 +353,7 @@ fn groups_past_the_depth_limit_are_left_out() { ins.push(end_group()); } ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); - let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap(); + let d = read_checked(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap(); assert!(d.warnings.contains(&Warning::TooDeep)); // The square after the groups is still read, beside the three groups kept. let objects = &d.pages[0].layers[0].objects; @@ -346,18 +374,18 @@ fn groups_past_the_depth_limit_are_left_out() { fn counts_past_the_limits_are_bounded() { let ins: Vec> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect(); let f = file(&[page(&ins)]); - let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap(); + let d = read_checked(&f, Limits { objects: 10, ..Limits::default() }).unwrap(); assert_eq!(d.pages[0].layers[0].objects.len(), 10); assert!(d.warnings.contains(&Warning::TooDeep)); - let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap(); + let d = read_checked(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap(); assert_eq!(d.pages[0].layers[0].objects.len(), 2); - assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count"))); - assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size"))); + assert_eq!(read_checked(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read_checked(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size"))); let dashed = |n: u16| { let mut children = vec![cont(b'4', 1e-7)]; children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)])); children.extend(tables()); - read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap() + read_checked(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap() }; let d = dashed(3); let o: Vec = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect(); @@ -372,7 +400,7 @@ fn a_curve_cut_short_keeps_the_points_it_holds() { let at = c.windows(2).position(|w| w == [3, 0]).unwrap(); c[at] = 9; let p = page(&[begin_page(None), c]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged)); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -387,7 +415,7 @@ fn a_curve_that_lost_type_bytes_keeps_its_first_points() { } g.extend([0x0c, 0x44]); let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)])); - let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap(); + let d = read_checked(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() }; let side = 100.0 / 25.4 * 72.0; @@ -403,14 +431,14 @@ fn a_file_cut_short_of_its_declared_size_is_reported() { let mut f = file(&[]); let declared = (f.len() as u32 - 8 + 100).to_le_bytes(); f[4..8].copy_from_slice(&declared); - let d = read_cmx(&f, Limits::default()).unwrap(); + let d = read_checked(&f, Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); } #[test] fn a_page_that_ends_inside_an_instruction_is_reported() { let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -420,7 +448,7 @@ fn a_chunk_64_bytes_past_stray_bytes_is_found() { let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -432,7 +460,687 @@ fn stray_letters_with_a_length_past_the_file_are_passed_over() { let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +/// Stray bytes, then letters whose length covers exactly the page chunk after them, then the page. +fn page_inside_stray_letters(stray: &[u8]) -> Vec { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = stray.to_vec(); + b.extend(b"abcd"); + b.extend((p.len() as u32).to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + riff(&children) +} + +#[test] +fn after_stray_letters_the_page_is_preferred_to_letters_that_hold_it() { + let mut stray = b"wxyz".to_vec(); + stray.extend(0xFFFF_FF00u32.to_le_bytes()); + let d = read_checked(&page_inside_stray_letters(&stray), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_the_page_is_preferred_to_letters_that_hold_it() { + let d = read_checked(&page_inside_stray_letters(&[1, 1]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn letters_64_bytes_past_stray_bytes_do_not_hide_the_page_they_hold() { + let d = read_checked(&page_inside_stray_letters(&[1; 64]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_after_three_page_headers_that_do_not_read_inside_letters_is_read() { + // Stray bytes, then letters whose length covers three page headers that reach its end and + // whose instructions do not fit, then the page. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let len = 24 + p.len(); + let mut body = Vec::new(); + for k in 0..3 { + body.extend(b"page"); + body.extend(((len - 8 * k - 8) as u32).to_le_bytes()); + } + body.extend(p); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((body.len() as u32).to_le_bytes()); + b.extend(body); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_recoveries_stop_once_a_read_has_spent_its_allowance() { + // Many copies of stray bytes followed by a chunk the reader passes over that holds a page: + // the first pages are read, and once the checks have spent the read's allowance the reader + // resumes at the chunk that holds each page, as it does without the recovery. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut unit = vec![1u8; 2]; + unit.extend(chunk(b"inf1", &p)); + let copies = 2000; + let mut children = vec![cont(b'4', 1e-7), unit.repeat(copies)]; + children.extend(tables()); + let f = riff(&children); + let d = read_checked(&f, Limits::default()).unwrap(); + assert!(!d.pages.is_empty() && d.pages.len() < copies, "{} of {copies} pages", d.pages.len()); + assert!(read_cmx_without_recovery(&f, Limits::default()).unwrap().pages.is_empty()); +} + +#[test] +fn after_stray_bytes_a_page_past_a_limit_is_left_out_with_a_warning() { + let f = page_inside_stray_letters(&[1, 1]); + let all = read_cmx(&f, Limits::default()).unwrap().pages.len(); + assert_eq!(all, 1); + let mut cut = 0; + for chunks in 1..200 { + let Ok(d) = read_checked(&f, Limits { chunks, ..Limits::default() }) else { continue }; + if d.pages.len() < all { + cut += 1; + assert!(d.warnings.contains(&Warning::TooDeep), "{chunks}: {:?}", d.warnings); + } + } + assert!(cut > 0); +} + +#[test] +fn a_recovered_page_spends_only_what_the_limits_leave_after_the_other_pages() { + // Stray bytes, letters whose length covers a page, the page, then another page: with room for + // one object, the last page keeps it and the warning tells of the page left out; with room for + // both, the recovered page reads first. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((p.len() as u32).to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b, q]; + children.extend(tables()); + let f = riff(&children); + let d = read_checked(&f, Limits { objects: 1, ..Limits::default() }).unwrap(); + assert_eq!(d.pages.len(), 1, "{:?}", d.pages); + let last = d.pages.last().unwrap(); + assert_eq!((last.layers[0].name.as_str(), last.layers[0].objects.len()), ("M", 1)); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); + let d = read_checked(&f, Limits::default()).unwrap(); + assert_eq!(d.pages.iter().map(|p| p.layers[0].name.as_str()).collect::>(), ["L", "M"]); +} + +#[test] +fn chunks_only_a_recovery_reads_do_not_stop_a_read_that_fits_without_them() { + // A page, then letters spelling `page` whose length runs past the file and that hold another + // page and an empty chunk: at every chunk limit at which the file opens without the recovery, + // it opens with it, and where the recovered page does not fit, the warning tells of it. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = b"page".to_vec(); + b.extend(0xFFFF_FF00u32.to_le_bytes()); + b.extend(q); + b.extend(chunk(b"junk", &[])); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(p); + children.push(b); + let f = riff(&children); + let names = |d: &Drawing| d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.clone()).collect::>(); + assert_eq!(names(&read_checked(&f, Limits::default()).unwrap()), ["L", "M"]); + let mut cut = 0; + for chunks in 1..200 { + let limits = Limits { chunks, ..Limits::default() }; + if read_cmx_without_recovery(&f, limits).is_err() { + continue; + } + let d = read_checked(&f, limits).unwrap(); + if names(&d) != ["L", "M"] { + cut += 1; + assert!(d.warnings.contains(&Warning::TooDeep), "{chunks}: {:?}", d.warnings); + } + } + assert!(cut > 0); +} + +#[test] +fn after_stray_bytes_a_page_is_read_when_the_chunk_found_lands_inside_a_list() { + // Stray bytes, then letters whose length ends on the header of an empty page at the end of the + // page after them. That empty page's length ends on the first page inside the list that + // follows. Walking on from the page reads the same page inside the list, so the page is read. + let (name, q) = ["Q", "Qa"] + .iter() + .map(|n| { + let carried = long_instr(-1, &[b"page".as_slice(), &12u32.to_le_bytes()].concat()); + (*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat()) + }) + .find(|(_, body)| body.len() % 2 == 0) + .unwrap(); + let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32).to_le_bytes()); + b.extend(chunk(b"page", &q)); + b.extend(list(b"pgls", &[r])); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect(); + assert_eq!(names, [name, "R"]); +} + +#[test] +fn after_stray_bytes_a_page_is_not_read_when_a_list_cuts_short_the_page_both_walks_reach() { + // As above, except that the list ends after the header of the page inside it, so walking on + // from the inner page reads that page without its body. Walking on from the letters reads the + // whole page, so the reader resumes at the letters and the page keeps its square. + let (name, q) = ["Q", "Qa"] + .iter() + .map(|n| { + let carried = long_instr(-1, &[b"page".as_slice(), &12u32.to_le_bytes()].concat()); + (*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat()) + }) + .find(|(_, body)| body.len() % 2 == 0) + .unwrap(); + let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32).to_le_bytes()); + b.extend(chunk(b"page", &q)); + b.extend(b"LIST"); + b.extend(12u32.to_le_bytes()); + b.extend(b"pgls"); + b.extend(r); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect(); + assert!(!names.contains(&name), "{names:?}"); + assert_eq!(names, ["R"]); + assert_eq!(d.pages.last().unwrap().layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_a_list_cuts_short_only_without_the_recovery_is_judged_as_recovered() { + // Stray bytes, then letters whose length ends on the header of a list at the end of the page + // after them. The list ends after the header of the next page, so the walk from the letters + // reads that page without its body, and the walk from the page inside the letters reads the + // whole page. Only the recovery reads that whole page, and it ends inside an instruction, so the + // reader leaves it out. + let (name, q) = ["Q", "Qa"] + .iter() + .map(|n| { + let carried = long_instr(-1, &[b"LIST".as_slice(), &12u32.to_le_bytes(), b"pgls"].concat()); + (*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat()) + }) + .find(|(_, body)| body.len() % 2 == 0) + .unwrap(); + let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer(), vec![1, 0]]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32 - 4).to_le_bytes()); + b.extend(chunk(b"page", &q)); + b.extend(r); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect(); + assert_eq!(names, [name]); +} + +#[test] +fn after_stray_bytes_a_page_whose_check_stops_at_a_limit_is_not_replaced_by_a_page_inside_it() { + // Stray bytes, then letters whose body holds the start of a page of one square. That page's last + // instruction carries the page of thirty squares that follows the letters, and ends where it + // ends. At a chunk limit that stops the check of the page of thirty squares while the check of + // the page inside the letters fits, the page inside the letters never takes its place. + let squares = (1..=30).map(|i| square(&attrs(Some(1), None, false), 0, 0, 100 * i)); + let p = page(&[begin_page(None), begin_layer("P", None)].into_iter().chain(squares).chain([end_layer()]).collect::>()); + let carried = long_instr(-1, &p); + let head = &carried[..carried.len() - p.len()]; + let q = ["Q", "Qa"] + .iter() + .map(|n| [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer(), head.to_vec()].concat()) + .find(|body| body.len() % 2 == 0) + .unwrap(); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32 + 8).to_le_bytes()); + b.extend(b"page"); + b.extend(((q.len() + p.len()) as u32).to_le_bytes()); + b.extend(q); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let f = riff(&children); + let names = |d: &Drawing| d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.clone()).collect::>(); + assert_eq!(names(&read_checked(&f, Limits::default()).unwrap()), ["P"]); + for chunks in 1..200 { + if let Ok(d) = read_checked(&f, Limits { chunks, ..Limits::default() }) { + assert_eq!(names(&d), ["P"], "{chunks}: {:?}", d.warnings); + } + } +} + +/// A page that fills with color 1, then, inside a list, letters spelling `page` whose length runs +/// past the list and that hold another page and a color table of one red entry, then `after`. +fn page_and_recovered_red(after: &[Vec]) -> Vec { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = b"page".to_vec(); + b.extend(0xFFFF_FF00u32.to_le_bytes()); + b.extend(q); + b.extend(table(b"rclr", &[color(5, &[255, 0, 0])])); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rclr"))); + children.push(p); + children.push(list(b"pgls", &[b])); + children.extend(after.iter().cloned()); + riff(&children) +} + +/// The fill of the first object of each page. +fn fills(d: &Drawing) -> Vec> { + d.pages.iter().map(|p| shape(&p.layers[0].objects[0]).fill.clone()).collect() +} + +#[test] +fn a_color_table_only_the_recovery_reads_colors_every_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); + let red = fills(&read_checked(&file(&[p]), Limits::default()).unwrap())[0].clone(); + assert!(red.is_some()); + let d = read_kept(&page_and_recovered_red(&[]), Limits::default()).unwrap(); + assert_eq!(fills(&d), [red.clone(), red]); +} + +#[test] +fn a_color_table_read_without_the_recovery_wins_over_one_only_the_recovery_reads() { + let green = table(b"rclr", &[color(5, &[0, 255, 0])]); + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rclr"))); + children.push(green.clone()); + let green_fill = fills(&read_checked(&riff(&children), Limits::default()).unwrap())[0].clone(); + let d = read_checked(&page_and_recovered_red(&[green]), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 2); + assert_eq!(fills(&d), [green_fill.clone(), green_fill]); +} + +#[test] +fn after_stray_bytes_a_page_inside_a_chunk_with_more_after_it_is_not_read() { + // Stray bytes, a chunk the reader passes over that holds a page followed by another chunk, + // then the page: only the last page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &[p.clone(), chunk(b"junk", &[0; 4])].concat())); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); +} + +#[test] +fn a_list_between_stray_bytes_is_read_as_a_list() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let b = [vec![1u8; 2], list(b"pgls", &[p.clone(), p]), vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 2); +} + +#[test] +fn after_stray_bytes_an_empty_page_header_inside_another_chunk_is_not_a_page() { + // Stray bytes, a chunk the reader passes over that holds only an empty page header, then the + // page: only the page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[]))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_an_empty_page_is_kept_before_the_next_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"page", &[])); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 2); + assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers); + assert_eq!(d.pages[1].layers[0].objects.len(), 1); +} + +#[test] +fn a_page_between_stray_bytes_is_preferred_to_letters_that_end_inside_it() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend(8u32.to_le_bytes()); + b.extend(p); + b.extend([1u8; 2]); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_is_preferred_to_page_letters_that_end_inside_it() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"page"); + b.extend(8u32.to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_page_between_stray_bytes_is_kept() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let b = [vec![1u8; 2], p, vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_header_that_ends_inside_another_chunk_is_not_a_page() { + // Stray bytes, a chunk the reader passes over whose body starts with a short page chunk, more + // stray bytes, then the page: only the last page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut inner = b"page".to_vec(); + inner.extend(4u32.to_le_bytes()); + inner.extend([0; 10]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + // The chunk passed over is followed by more stray bytes, and the warning says so. + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_header_too_short_to_read_inside_another_chunk_is_passed_over() { + // Stray bytes, then a chunk the reader passes over that holds a one-byte header, then the + // header: the drawing opens with the header after it. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let first = [vec![1u8; 2], chunk(b"inf1", &chunk(b"cont", &[0]))].concat(); + let mut children = vec![first, cont(b'4', 1e-7), p]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_letters_ending_on_a_layer_name_do_not_hide_the_page() { + // Stray bytes, then letters whose length ends on the letters of a layer name inside the page + // after them, then the page. + let names = ["Background", "aBackground"]; + let (p, at) = names + .iter() + .map(|n| page(&[begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()])) + .find_map(|p| p.windows(4).position(|w| w == b"Back").filter(|at| at % 2 == 0).map(|at| (p, at))) + .unwrap(); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((at as u32).to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_followed_by_a_chunk_inside_another_chunk_is_not_read_before_more_stray_bytes() { + // Stray bytes, a chunk the reader passes over that holds a page and another chunk, more stray + // bytes, then the page: only the last page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &[p.clone(), chunk(b"junk", &[0; 4])].concat())); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); +} + +#[test] +fn after_stray_bytes_a_header_without_a_coordinate_size_inside_another_chunk_is_passed_over() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let first = [vec![1u8; 2], chunk(b"inf1", &chunk(b"cont", &[0; 60]))].concat(); + let mut children = vec![first, cont(b'4', 1e-7), p]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_table_inside_another_chunk_that_ends_inside_the_next_page_is_passed_over() { + // Stray bytes, a chunk the reader passes over that holds the start of a color table whose + // length ends inside the page after more stray bytes: the page is read. + let sq = square(&attrs(Some(1), None, false), 0, 0, 1000); + let p = page(&[begin_page(None), begin_layer("L", None), sq.clone(), sq.clone(), sq, end_layer()]); + let mut inner = b"rclr".to_vec(); + inner.extend(14u32.to_le_bytes()); + inner.extend([0; 2]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 3); +} + +#[test] +fn a_page_between_stray_bytes_is_kept_when_its_body_holds_chunk_letters() { + // A layer name near the start of the page holds a color table chunk and another chunk id. + let mut tail = b"rclr".to_vec(); + tail.extend([4, 0, 0, 0, 0, 0, 0, 0]); + tail.extend(b"junk"); + tail.extend([0; 4]); + let tail = String::from_utf8(tail).unwrap(); + let (p, at) = ["", "x"] + .iter() + .map(|pre| { + page(&[begin_page(None), begin_layer(&format!("{pre}{tail}"), None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]) + }) + .find_map(|p| p.windows(4).position(|w| w == b"rclr").filter(|at| at % 2 == 0).map(|at| (p, at))) + .unwrap(); + assert!((8..=64).contains(&at), "{at}"); + let b = [vec![1u8; 2], p, vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_too_short_for_an_instruction_inside_another_chunk_is_not_a_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[0; 2]))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_short_page_is_not_hidden_by_a_table_inside_the_chunk_before_it() { + // Stray bytes, a chunk the reader passes over that holds the start of a color table whose + // length ends inside the short page after more stray bytes: the page is read. + let p = page(&[begin_page(None)]); + let mut inner = b"rclr".to_vec(); + inner.extend(10u32.to_le_bytes()); + inner.extend([0; 2]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); +} + +#[test] +fn a_last_page_before_stray_bytes_at_the_end_of_the_file_is_preferred_to_letters_that_end_inside_it() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend(8u32.to_le_bytes()); + b.extend(p); + b.extend([1u8; 2]); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_page_between_stray_bytes_is_kept_when_its_body_holds_a_table_that_reaches_its_end() { + // Bytes the page's long instruction carries hold a color table whose length reaches the end + // of the page. + let sq = square(&attrs(Some(1), None, false), 0, 0, 1000); + let mut table = b"rclr".to_vec(); + let rest = [begin_layer("L", None), sq, end_layer()].concat(); + // The table's body: the rest of the long instruction (2 bytes), then the instructions after it. + table.extend(((2 + rest.len()) as u32).to_le_bytes()); + table.extend([0; 2]); + let carried = long_instr(-1, &table); + let p = page(&[begin_page(None), carried, rest]); + let at = p.windows(4).position(|w| w == b"rclr").unwrap(); + assert!(at % 2 == 0 && (8..=64).contains(&at), "{at}"); + let b = [vec![1u8; 2], p, vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_whose_first_instruction_is_empty_inside_another_chunk_is_not_a_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[0; 4]))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_header_between_stray_bytes_is_kept_when_its_body_holds_a_table_that_reaches_its_end() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut c = cont(b'4', 1e-7); + let inner = (c.len() - 24) as u32; + c[16..20].copy_from_slice(b"rclr"); + c[20..24].copy_from_slice(&inner.to_le_bytes()); + let mut children = vec![[vec![1u8; 2], c, vec![1u8; 2]].concat(), p]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_table_whose_entries_do_not_fit_inside_another_chunk_is_passed_over() { + // Stray bytes, then a chunk the reader passes over that holds a color table of one entry with + // no bytes for it, then the real tables: the colors come from the real tables. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let read = |junk: &[u8]| { + let mut children = vec![cont(b'4', 1e-7), junk.to_vec()]; + children.extend(tables()); + children.push(p.clone()); + read_checked(&riff(&children), Limits::default()).unwrap() + }; + let junk = [vec![1u8; 2], chunk(b"inf1", &chunk(b"rclr", &[1, 0]))].concat(); + let d = read(&junk); + let clean = read(&[]); + assert_eq!(format!("{:?}", d.pages), format!("{:?}", clean.pages)); +} + +#[test] +fn after_stray_bytes_a_page_whose_second_instruction_is_empty_inside_another_chunk_is_not_a_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[instr(-1, &[]), vec![0; 4]].concat()))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_page_letters_with_a_length_past_the_list_do_not_hide_the_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"page"); + b.extend(0xFFFF_FF00u32.to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -444,7 +1152,7 @@ fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() { children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl"))); children.push(table(b"rdot", &[dashes(&[0, 0])])); children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap(); assert!(o.dashes.is_empty(), "{:?}", o.dashes); @@ -462,7 +1170,7 @@ fn a_curve_field_that_lost_points_is_left_out() { g.extend(1_000_000i32.to_le_bytes()); g.extend([0x40, 0x42]); let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)])); - let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap(); + let d = read_checked(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers); } @@ -476,7 +1184,7 @@ fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() { b.extend(p); let mut children = vec![cont(b'4', 1e-7), b]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -493,7 +1201,7 @@ fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() { b.extend(p); let mut children = vec![cont(b'4', 1e-7), b]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -513,7 +1221,7 @@ fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() { b.extend(p); let mut children = vec![cont(b'4', 1e-7), b]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -525,7 +1233,7 @@ fn a_canvas_or_a_container_is_reported() { let mut a = attrs(Some(1), None, false); a[0] |= bit; let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}"); assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some()); } @@ -536,7 +1244,7 @@ fn a_library_color_with_its_name_reads_as_a_spot_color() { let mut children = vec![cont(b'4', 1e-7)]; children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)])); children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); match shape(&d.pages[0].layers[0].objects[0]).fill.clone() { Some(Color::Spot { name, tint, look }) => { assert_eq!((name.as_str(), tint), ("Brick 12", 1.0)); @@ -553,7 +1261,7 @@ proptest! { fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { let mut b = b"RIFF\0\0\0\0CMX1".to_vec(); b.extend(bytes); - let _ = read_cmx(&b, Limits::default()); + let _ = read_kept(&b, Limits::default()); } #[test] @@ -563,6 +1271,6 @@ proptest! { for (at, v) in edits { b[at % n] = v; } - let _ = read_cmx(&b, Limits::default()); + let _ = read_kept(&b, Limits::default()); } } diff --git a/crates/cdr/tests/it/cmx_write.rs b/crates/cdr/tests/it/cmx_write.rs new file mode 100644 index 0000000000..f25ed11fe2 --- /dev/null +++ b/crates/cdr/tests/it/cmx_write.rs @@ -0,0 +1,1558 @@ +//! Writing `.cmx` files: what [`write_cmx`] writes reads back through [`read_cmx`] as the same +//! drawing, and what it can't hold is refused or reported. + +use craft_cdr::model::{ + Cap, Color, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath, +}; +use craft_cdr::{Error, Limits, MAX_CURVE_POINTS, Written, is_cmx, read_cmx}; +use proptest::prelude::*; + +/// [`craft_cdr::write_cmx`] within the default limits. +fn write_cmx(d: &Drawing) -> Result { + craft_cdr::write_cmx(d, Limits::default()) +} + +fn layer(name: &str, objects: Vec) -> Layer { + Layer { name: name.into(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() } +} + +fn drawing(pages: Vec) -> Drawing { + Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() } +} + +fn square(x: f64, y: f64, side: f64) -> Geometry { + let p = |x, y| Pt { x, y }; + Geometry::Path(Path { + subpaths: vec![SubPath { + start: p(x, y), + segments: vec![Segment::Line(p(x + side, y)), Segment::Line(p(x + side, y + side)), Segment::Line(p(x, y + side))], + closed: true, + }], + }) +} + +fn outline(color: Color) -> Outline { + Outline { width: 2.0, color, cap: Cap::Round, join: Join::Bevel, dashes: Vec::new(), behind_fill: false, scale_with: false } +} + +fn shape(o: &Object) -> &Shape { + match o { + Object::Shape(s) => s, + other => panic!("not a shape: {other:?}"), + } +} + +/// Every point (anchors and controls) of a geometry that is a path. +fn points(g: &Geometry) -> Vec { + let Geometry::Path(p) = g else { panic!("not a path: {g:?}") }; + let mut out = Vec::new(); + for sp in &p.subpaths { + out.push(sp.start); + for s in &sp.segments { + match s { + Segment::Line(a) => out.push(*a), + Segment::Cubic(a, b, c) => out.extend([*a, *b, *c]), + } + } + } + out +} + +fn bounds(g: &Geometry) -> (f64, f64, f64, f64) { + points(g).iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.x), b.1.min(p.y), b.2.max(p.x), b.3.max(p.y))) +} + +/// Within a coordinate unit of 0.1 µm (0.000283 pt), in points. +fn near(a: f64, b: f64) -> bool { + (a - b).abs() <= 0.0003 +} + +fn near_color(a: &Color, b: &Color) -> bool { + let close = |x: &[f32], y: &[f32], tol: f32| x.len() == y.len() && x.iter().zip(y).all(|(p, q)| (p - q).abs() <= tol); + match (a, b) { + (Color::Rgb(x), Color::Rgb(y)) => close(x, y, 1.0 / 255.0), + (Color::Cmyk(x), Color::Cmyk(y)) => close(x, y, 0.005), + (Color::Gray(x), Color::Gray(y)) => (x - y).abs() <= 1.0 / 255.0, + (Color::Registration, Color::Registration) => true, + (Color::Spot { name: n, tint: t, look: l }, Color::Spot { name: m, tint: u, look: k }) => { + n == m && (t - u).abs() <= 0.005 && close(&l.unwrap_or_default(), &k.unwrap_or_default(), 2.0 / 255.0) + } + _ => false, + } +} + +fn round_trip(d: &Drawing) -> Drawing { + let w = write_cmx(d).unwrap(); + assert!(is_cmx(&w.bytes)); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + back +} + +#[test] +fn a_drawing_reads_back_as_written() { + let red = Color::Rgb([1.0, 0.2, 0.0]); + let cyan = Color::Cmyk([0.6, 0.0, 0.13, 0.05]); + let spot = Color::Spot { name: "Ink 300".into(), tint: 0.4, look: Some([0.0, 0.4, 0.8]) }; + let dashed = + Outline { dashes: vec![3.0, 1.0], behind_fill: true, scale_with: true, cap: Cap::Square, join: Join::Miter, ..outline(Color::Gray(0.75)) }; + let back_layer = layer( + "Art", + vec![ + Object::Shape(Box::new(Shape::new(square(-50.0, -50.0, 100.0), Matrix::IDENTITY, Some(red.clone()), Some(outline(Color::Registration))))), + Object::Group { + objects: vec![ + Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(cyan.clone()), Some(dashed.clone())))), + Object::Shape(Box::new(Shape::new(square(20.0, 0.0, 10.0), Matrix::IDENTITY, Some(spot.clone()), None))), + ], + flags: Flags::default(), + }, + ], + ); + let front_layer = + layer("Über", vec![Object::Shape(Box::new(Shape::new(square(5.0, 5.0, 1.0), Matrix::IDENTITY, None, Some(outline(cyan.clone())))))]); + let d = drawing(vec![ + Page { size: Some((595.0, 842.0)), layers: vec![front_layer, back_layer] }, + Page { + size: Some((200.0, 100.0)), + layers: vec![layer( + "Second", + vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.3)), None)))], + )], + }, + ]); + let back = round_trip(&d); + assert_eq!(back.pages.len(), 2); + let (w, h) = back.pages[0].size.unwrap(); + assert!(near(w, 595.0) && near(h, 842.0)); + let names: Vec<&str> = back.pages[0].layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Über", "Art"], "layers keep their order and names"); + let art = &back.pages[0].layers[1].objects; + let s = shape(&art[0]); + assert!(near_color(s.fill.as_ref().unwrap(), &red)); + assert_eq!(s.outline.as_ref().unwrap().color, Color::Registration); + let (x0, y0, x1, y1) = bounds(&s.geometry); + assert!(near(x0, -50.0) && near(y0, -50.0) && near(x1, 50.0) && near(y1, 50.0)); + let Object::Group { objects, .. } = &art[1] else { panic!("not a group: {:?}", art[1]) }; + let o = shape(&objects[0]).outline.clone().unwrap(); + assert!(near_color(shape(&objects[0]).fill.as_ref().unwrap(), &cyan)); + assert!(near(o.width, 2.0) && near_color(&o.color, &Color::Gray(0.75))); + assert_eq!((o.cap, o.join, o.dashes, o.behind_fill, o.scale_with), (Cap::Square, Join::Miter, vec![3.0, 1.0], true, true)); + assert!(near_color(shape(&objects[1]).fill.as_ref().unwrap(), &spot), "{:?}", shape(&objects[1]).fill); + assert!(shape(&objects[1]).outline.is_none()); + let front = shape(&back.pages[0].layers[0].objects[0]); + assert!(front.fill.is_none() && front.outline.as_ref().is_some_and(|o| o.cap == Cap::Round && o.join == Join::Bevel)); + let (w, h) = back.pages[1].size.unwrap(); + assert!(near(w, 200.0) && near(h, 100.0)); +} + +#[test] +fn rectangles_and_ellipses_are_written_as_curves_in_their_place() { + let m = Matrix([1.0, 0.0, 0.0, 1.0, 10.0, -20.0]); + let rect = Shape::new(Geometry::Rect { w: 40.0, h: -30.0, radii: [5.0, 0.0, 50.0, 2.0] }, m, Some(Color::Gray(1.0)), None); + let ellipse = Shape::new(Geometry::Ellipse { w: 20.0, h: 10.0 }, m, Some(Color::Gray(1.0)), None); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(rect)), Object::Shape(Box::new(ellipse))])] }]); + let back = round_trip(&d); + let objects = &back.pages[0].layers[0].objects; + let (x0, y0, x1, y1) = bounds(&shape(&objects[0]).geometry); + assert!(near(x0, 10.0) && near(y0, -50.0) && near(x1, 50.0) && near(y1, -20.0), "{:?}", (x0, y0, x1, y1)); + let Geometry::Path(p) = &shape(&objects[1]).geometry else { panic!() }; + assert!(p.subpaths[0].closed && p.subpaths[0].segments.iter().all(|s| matches!(s, Segment::Cubic(..)))); + let (x0, y0, x1, y1) = bounds(&shape(&objects[1]).geometry); + assert!(near(x0, 10.0) && near(x1, 30.0) && near(y0, -20.0) && near(y1, -10.0)); +} + +#[test] +fn a_path_past_the_points_a_curve_holds_is_written_as_a_group_of_curves() { + let n = MAX_CURVE_POINTS * 2 + 10; + let segments = (1..n).map(|i| Segment::Line(Pt { x: i as f64 * 0.01, y: (i % 2) as f64 })).collect(); + let long = Shape::new( + Geometry::Path(Path { subpaths: vec![SubPath { start: Pt { x: 0.0, y: 0.0 }, segments, closed: false }] }), + Matrix::IDENTITY, + None, + Some(outline(Color::Gray(1.0))), + ); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(long))])] }]); + let w = write_cmx(&d).unwrap(); + assert!(w.split_paths && w.cut_subpaths, "an outline gets caps where the pieces meet"); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + assert!(objects.len() >= 3); + // The pieces meet end to start, so every point is kept, the joins twice. + let total: usize = objects.iter().map(|o| points(&shape(o).geometry).len()).sum(); + assert_eq!(total, n + objects.len() - 1); + // A filled shape cut into pieces is reported. + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!() }; + let filled = Shape { fill: Some(Color::Gray(0.5)), ..(**s).clone() }; + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(filled))])] }]); + assert!(write_cmx(&d).unwrap().cut_subpaths); +} + +#[test] +fn names_the_reader_shortens_are_reported() { + // A name as long as the reader keeps whole reads back whole. + let kept = "k".repeat(256); + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, None))); + let d = drawing(vec![Page { size: None, layers: vec![layer(&kept, vec![plain])] }]); + let w = write_cmx(&d).unwrap(); + assert!(!w.long_names); + assert_eq!(read_cmx(&w.bytes, Limits::default()).unwrap().pages[0].layers[0].name, kept); + let long = "n".repeat(257); + let spot = |name: &str| Color::Spot { name: name.into(), tint: 1.0, look: None }; + let s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(spot(&long)), None); + let short = drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s.clone()))])] }]); + assert!(write_cmx(&short).unwrap().long_names, "a long spot name"); + let named = drawing(vec![Page { size: None, layers: vec![layer(&long, vec![Object::Shape(Box::new(Shape { fill: None, ..s.clone() }))])] }]); + assert!(write_cmx(&named).unwrap().long_names, "a long layer name"); + // Two long spot names that differ only past what the reader keeps still read back apart. + let other = format!("{}m", "n".repeat(256)); + let t = Shape { fill: Some(spot(&other)), ..s.clone() }; + let both = drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s)), Object::Shape(Box::new(t))])] }]); + let back = read_cmx(&write_cmx(&both).unwrap().bytes, Limits::default()).unwrap(); + let names: Vec = back.pages[0].layers[0] + .objects + .iter() + .filter_map(|o| match shape(o).fill.as_ref() { + Some(Color::Spot { name, .. }) => Some(name.clone()), + _ => None, + }) + .collect(); + assert!(names.len() == 2 && names[0] != names[1], "{names:?}"); +} + +#[test] +fn a_spot_color_at_no_tint_is_reported() { + let spot = |tint| Color::Spot { name: "Ink".into(), tint, look: Some([0.0, 0.0, 1.0]) }; + let file = |c| { + let s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None); + drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]) + }; + assert!(write_cmx(&file(spot(0.0))).unwrap().zero_tints); + assert!(!write_cmx(&file(spot(0.05))).unwrap().zero_tints); +} + +#[test] +fn coordinates_past_the_32_bit_range_are_refused() { + let far = Shape::new(square(1e6, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(1.0)), None); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(far))])] }]); + assert_eq!(write_cmx(&d), Err(Error::Limit("coordinate range"))); +} + +#[test] +fn dash_lengths_are_rounded_to_whole_outline_widths() { + let o = Outline { dashes: vec![2.4, 0.2], ..outline(Color::Gray(1.0)) }; + let s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(s))])] }]); + let w = write_cmx(&d).unwrap(); + assert!(w.rounded_dashes); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert_eq!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes, vec![2.0, 0.0]); +} + +fn one_shape(s: Shape) -> Drawing { + drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]) +} + +#[test] +fn a_page_without_its_own_size_takes_the_drawings() { + let mut d = one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)); + d.page_size = Some((300.0, 200.0)); + let (w, h) = round_trip(&d).pages[0].size.unwrap(); + assert!(near(w, 300.0) && near(h, 200.0), "{w} {h}"); +} + +#[test] +fn pages_are_numbered_in_their_order() { + let page = |side| Page { + size: Some((100.0, 100.0)), + layers: vec![layer("L", vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, side), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))])], + }; + let bytes = write_cmx(&drawing(vec![page(1.0), page(2.0)])).unwrap().bytes; + // Each page chunk starts with its begin-page instruction: a u16 size, the code 9, then field 1 + // (a tag and a u16 length) whose first u16 is the page number. + let numbers: Vec = bytes + .windows(4) + .enumerate() + .filter(|(_, w)| *w == b"page") + .map(|(i, _)| { + let body = &bytes[i + 8..]; + assert_eq!(i16::from_le_bytes([body[2], body[3]]), 9); + u16::from_le_bytes([body[7], body[8]]) + }) + .collect(); + assert_eq!(numbers, [1, 2]); +} + +/// Field 1 of each entry of the table chunk `id`. +fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { + table_fields(bytes, id).into_iter().map(|e| e.into_iter().find(|(tag, ..)| *tag == 1).map(|(.., data)| data).expect("field 1")).collect() +} + +/// The fields of each entry of the table chunk `id`, each its tag, where it starts in the file and +/// its data: a u16 count, then a field list per entry (a tag, a u16 length counting the 3 header +/// bytes, the data; 0xff after the last field). +fn table_fields(bytes: &[u8], id: &[u8; 4]) -> Vec)>> { + let at = bytes.windows(4).position(|w| w == id).unwrap_or_else(|| panic!("no {id:?} chunk")) + 8; + // The chunk's body runs for the size after its id. + let end = at + u32::from_le_bytes(bytes[at - 4..at].try_into().unwrap()) as usize; + assert!(end <= bytes.len(), "{id:?} chunk ends at {end}, past the file"); + let count = usize::from(u16::from_le_bytes([bytes[at], bytes[at + 1]])); + let mut p = at + 2; + let mut out = Vec::new(); + for _ in 0..count { + let mut entry = Vec::new(); + loop { + assert!(p < end, "entry runs past the {id:?} chunk at {p}"); + if bytes[p] == 0xff { + break; + } + assert!(p + 3 <= end, "field header at {p} runs past the {id:?} chunk"); + let len = usize::from(u16::from_le_bytes([bytes[p + 1], bytes[p + 2]])); + // A length shorter than its header, or past the chunk, would stop the walk. + assert!(len >= 3 && p + len <= end, "field at {p} has length {len}"); + entry.push((bytes[p], p, bytes[p + 3..p + len].to_vec())); + p += len; + } + p += 1; + out.push(entry); + } + // The size counts the u16 count and the entries; the pad byte comes after it. + assert_eq!(p, end, "{id:?} chunk has bytes left after its entries"); + out +} + +#[test] +fn every_outline_names_a_screen_and_a_dash_pattern_the_file_holds() { + let solid = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let dashed = Shape::new(square(2.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(Outline { dashes: vec![3.0, 1.0], ..outline(Color::Gray(1.0)) })); + let d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(solid)), Object::Shape(Box::new(dashed))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let (screens, dashes) = (table_entries(&bytes, b"rscr"), table_entries(&bytes, b"rdot")); + let (line_types, outlines) = (table_entries(&bytes, b"rott"), table_entries(&bytes, b"rotl")); + assert_eq!(outlines.len(), 2); + let mut patterns: Vec<(bool, Vec)> = outlines + .iter() + .map(|o| { + let entry = |i: usize| usize::from(u16::from_le_bytes([o[2 * i], o[2 * i + 1]])); + assert!((1..=screens.len()).contains(&entry(1)), "the screen entry exists"); + let line = entry(0); + assert!((1..=line_types.len()).contains(&line), "the line type entry exists"); + let dash = entry(5); + assert!((1..=dashes.len()).contains(&dash), "the dash entry exists"); + let pattern = &dashes[dash - 1]; + let count = usize::from(u16::from_le_bytes([pattern[0], pattern[1]])); + assert_eq!(pattern.len(), 2 + 2 * count); + let lengths = pattern[2..].chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + // The outline's own line type says whether it is dashed. + (line_types[line - 1][0] & 4 != 0, lengths) + }) + .collect(); + patterns.sort(); + // The solid outline names an empty pattern; the dashed one names its two lengths. + assert_eq!(patterns, vec![(false, vec![]), (true, vec![3, 1])]); +} + +#[test] +fn colors_are_also_written_in_the_model_and_value_fields() { + let colors = [ + Color::Rgb([1.0, 0.2, 0.0]), + Color::Cmyk([0.6, 0.0, 0.13, 0.05]), + Color::Gray(0.75), + Color::Spot { name: "Ink 300".into(), tint: 0.4, look: Some([0.0, 0.4, 0.8]) }, + Color::Registration, + ]; + let objects = colors + .iter() + .enumerate() + .map(|(i, c)| Object::Shape(Box::new(Shape::new(square(20.0 * i as f64, 0.0, 10.0), Matrix::IDENTITY, Some(c.clone()), None)))) + .collect(); + let d = drawing(vec![Page { size: Some((200.0, 100.0)), layers: vec![layer("Art", objects)] }]); + let mut bytes = write_cmx(&d).unwrap().bytes; + let entries = table_fields(&bytes, b"rclr"); + // Each entry holds the model and the palette 5 in field 1 and four values in field 2, before + // the property list of field 10. + let mut older: Vec<(Vec, Vec)> = entries + .iter() + .map(|e| { + assert_eq!(e.iter().map(|(tag, ..)| *tag).collect::>(), [1, 2, 10]); + (e[0].2.clone(), e[1].2.clone()) + }) + .collect(); + older.sort(); + let mut want = vec![ + // Red, green and blue. + (vec![5, 5], vec![255, 51, 0, 0]), + // Cyan, magenta, yellow and black in percent. + (vec![2, 5], vec![60, 0, 13, 5]), + // Gray, 255 white. + (vec![9, 5], vec![64, 0, 0, 0]), + // The spot color's look at its tint of 40 percent. + (vec![5, 5], vec![153, 194, 235, 0]), + // The registration color as every ink at 100 percent. + (vec![2, 5], vec![100, 100, 100, 100]), + ]; + want.sort(); + assert_eq!(older, want); + // With field 10 retagged, the reader takes each color from fields 1 and 2. + for e in &entries { + bytes[e[2].1] = 11; + } + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let fills: Vec = back.pages[0].layers[0].objects.iter().map(|o| shape(o).fill.clone().unwrap()).collect(); + let opened = [colors[0].clone(), colors[1].clone(), colors[2].clone(), Color::Rgb([0.6, 0.76, 0.92]), Color::Cmyk([1.0; 4])]; + assert_eq!(fills.len(), opened.len()); + for (got, want) in fills.iter().zip(&opened) { + assert!(near_color(got, want), "{got:?} for {want:?}"); + } +} + +#[test] +fn an_outline_that_scales_with_its_shape_keeps_its_drawn_width() { + let m = Matrix([3.0, 0.0, 0.0, 3.0, 0.0, 0.0]); + let width = |scale_with| { + let o = Outline { scale_with, dashes: vec![2.0, 1.0], ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), m, None, Some(o)))); + let o = shape(&back.pages[0].layers[0].objects[0]).outline.clone().unwrap(); + assert_eq!(o.dashes, vec![2.0, 1.0], "dashes stay in outline widths"); + o.width + }; + assert!(near(width(true), 6.0) && near(width(false), 2.0)); +} + +#[test] +fn a_dash_pattern_of_zero_lengths_stays_solid() { + let o = Outline { dashes: vec![0.0, 0.0], ..outline(Color::Gray(1.0)) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap(); + assert!(!w.rounded_dashes); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes.is_empty()); +} + +#[test] +fn a_spot_color_at_a_low_tint_keeps_its_ink() { + let black = Color::Spot { name: "Ink".into(), tint: 0.0051, look: Some([0.0, 0.0, 0.0]) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(black), None))); + let Some(Color::Spot { look: Some(look), .. }) = shape(&back.pages[0].layers[0].objects[0]).fill.clone() else { panic!("not a spot color") }; + assert!(look.iter().all(|v| *v < 0.1), "{look:?}"); +} + +#[test] +fn hidden_art_is_left_out_and_what_the_file_cant_hold_is_reported() { + let plain = || Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + assert!(!write_cmx(&one_shape(plain())).unwrap().left_out); + let hidden = Shape { flags: Flags { hidden: true, locked: false }, ..plain() }; + let mut hidden_layer = layer("Hidden", vec![Object::Shape(Box::new(plain()))]); + hidden_layer.flags.hidden = true; + let d = drawing(vec![Page { + size: None, + layers: vec![hidden_layer, layer("Shown", vec![Object::Shape(Box::new(hidden)), Object::Shape(Box::new(plain()))])], + }]); + let w = write_cmx(&d).unwrap(); + assert!(w.left_out); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers.len(), 1); + assert_eq!(back.pages[0].layers[0].objects.len(), 1); + assert!(write_cmx(&one_shape(Shape { opacity: 0.5, ..plain() })).unwrap().left_out, "transparency"); + let mut master = one_shape(plain()); + master.master = vec![layer("Master", vec![Object::Shape(Box::new(plain()))])]; + assert!(write_cmx(&master).unwrap().left_out, "a master layer"); +} + +#[test] +fn a_clipping_containers_outline_is_drawn_over_what_it_clips() { + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.2)), Some(outline(Color::Gray(1.0)))); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }]); + let w = write_cmx(&d).unwrap(); + assert!(w.left_out, "the clip itself is not written"); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + // Front to back: the container's outline, the clipped shape, the container's fill. + let kinds: Vec<(bool, bool)> = objects.iter().map(|o| (shape(o).fill.is_some(), shape(o).outline.is_some())).collect(); + assert_eq!(kinds, [(false, true), (true, false), (true, false)]); + assert!(near_color(shape(&objects[2]).fill.as_ref().unwrap(), &Color::Gray(0.2))); +} + +#[test] +fn a_hidden_clipping_container_hides_what_it_clips() { + let mut container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.2)), None); + container.flags.hidden = true; + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let shown = Object::Shape(Box::new(Shape::new(square(20.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip, shown])] }])).unwrap(); + assert!(w.left_out); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers[0].objects.len(), 1); + assert!(matches!(back.pages[0].layers[0].objects[0], Object::Shape(_))); +} + +#[test] +fn guide_and_grid_layers_are_left_out() { + let art = || vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))]; + let kinds = [LayerKind::Guides, LayerKind::Grid]; + let mut layers: Vec = kinds.iter().map(|k| Layer { kind: *k, ..layer("Construction", art()) }).collect(); + layers.push(layer("Art", art())); + let w = write_cmx(&drawing(vec![Page { size: None, layers }])).unwrap(); + assert!(w.left_out); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let names: Vec<&str> = back.pages[0].layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Art"]); +} + +#[test] +fn locked_art_is_reported() { + let mut s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + s.flags.locked = true; + assert!(write_cmx(&one_shape(s)).unwrap().left_out); +} + +#[test] +fn nonzero_fills_that_may_fill_differently_are_reported() { + let p = |x, y| Pt { x, y }; + // Two squares turning the same way, one inside the other: nonzero fills the inner one, + // even-odd leaves it a hole. + let ring = |cw: bool, x: f64, side: f64| { + let corners = [p(x, x), p(x + side, x), p(x + side, x + side), p(x, x + side)]; + let pts: Vec = if cw { corners.into_iter().rev().collect() } else { corners.to_vec() }; + SubPath { start: pts[0], segments: pts[1..].iter().map(|q| Segment::Line(*q)).collect(), closed: true } + }; + let filled = |inner_cw: bool, nonzero: bool| { + let geometry = Geometry::Path(Path { subpaths: vec![ring(false, 0.0, 10.0), ring(inner_cw, 2.0, 5.0)] }); + let s = Shape { nonzero, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + write_cmx(&one_shape(s)).unwrap().nonzero_fills + }; + assert!(filled(false, true), "same turn, nested"); + assert!(!filled(true, true), "a counter turning the other way fills the same"); + assert!(!filled(false, false), "an even-odd fill is written as it is"); +} + +#[test] +fn a_subpath_crossing_itself_with_one_net_turn_is_reported() { + let p = |x, y| Pt { x, y }; + // One net turn, but the inside around (1.25, 2.5) is wound twice. + let pts = [p(4.0, 1.0), p(3.0, 1.0), p(0.0, 4.0), p(0.0, 1.0), p(4.0, 4.0), p(0.0, 3.0)]; + let sub = SubPath { start: pts[0], segments: pts[1..].iter().map(|q| Segment::Line(*q)).collect(), closed: true }; + let s = Shape { nonzero: true, ..Shape::new(Geometry::Path(Path { subpaths: vec![sub] }), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); + // A plain square crosses nothing. + let plain = Shape { nonzero: true, ..Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(plain)).unwrap().nonzero_fills); +} + +#[test] +fn a_curve_crossing_where_its_control_points_dont_is_reported() { + let p = |x, y| Pt { x, y }; + // M0 0 C0 10 10 10 10 0 L12 16 -4 11 -4 -1 12 -6 2 9 Z winds twice around (2.5, 7.5). + let mut segments = vec![Segment::Cubic(p(0.0, 10.0), p(10.0, 10.0), p(10.0, 0.0))]; + segments.extend([p(12.0, 16.0), p(-4.0, 11.0), p(-4.0, -1.0), p(12.0, -6.0), p(2.0, 9.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_closing_line_back_to_the_start_is_no_crossing() { + let p = |x, y| Pt { x, y }; + // Clockwise, with the closing line written out. + let segments = [p(0.0, 10.0), p(10.0, 10.0), p(10.0, 0.0), p(0.0, 0.0)].map(Segment::Line).to_vec(); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn an_ink_takes_its_look_from_its_strongest_tint_and_from_master_layers() { + let ink = |tint, look| Color::Spot { name: "Ink".into(), tint, look }; + let filled = |c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None))); + let red = Some([1.0, 0.0, 0.0]); + // The 0% use, whose look is white, is met first. + let d = drawing(vec![Page { + size: None, + layers: vec![layer("L", vec![filled(ink(1.0, None)), filled(ink(1.0, red)), filled(ink(0.0, Some([1.0; 3])))])], + }]); + let back = round_trip(&d); + assert!(near_color(shape(&back.pages[0].layers[0].objects[0]).fill.as_ref().unwrap(), &ink(1.0, red))); + let mut d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![filled(ink(1.0, None))])] }]); + d.master = vec![layer("Master", vec![filled(ink(1.0, red))])]; + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + assert!(near_color(shape(&back.pages[0].layers[0].objects[0]).fill.as_ref().unwrap(), &ink(1.0, red))); +} + +#[test] +fn an_empty_layer_and_a_name_ending_in_nul_are_reported() { + let plain = || Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let empty = drawing(vec![Page { size: None, layers: vec![layer("Empty", Vec::new()), layer("L", vec![plain()])] }]); + assert!(write_cmx(&empty).unwrap().left_out); + let padded = drawing(vec![Page { size: None, layers: vec![layer("L\0", vec![plain()])] }]); + assert!(write_cmx(&padded).unwrap().long_names); +} + +#[test] +fn a_subpath_going_over_its_edges_again_is_reported() { + let p = |x, y| Pt { x, y }; + // The square right of the start twice counterclockwise, then the square left of it once + // clockwise: one net turn, and the right square wound twice. + let pts = [(1, 0), (1, 1), (0, 1), (0, 0), (1, 0), (1, 1), (0, 1), (0, 0), (-1, 0), (-1, 1), (0, 1)].map(|(x, y)| p(f64::from(x), f64::from(y))); + let sub = SubPath { start: p(0.0, 0.0), segments: pts.map(Segment::Line).to_vec(), closed: true }; + let s = Shape { nonzero: true, ..Shape::new(Geometry::Path(Path { subpaths: vec![sub] }), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_shape_with_no_segments_is_reported() { + let empty = Shape::new(Geometry::Path(Path::default()), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let w = write_cmx(&one_shape(empty)).unwrap(); + assert!(w.left_out); +} + +#[test] +fn a_page_side_that_rounds_to_nothing_is_refused() { + let mut d = one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)); + d.pages[0].size = Some((0.000_01, 720.0)); + assert_eq!(write_cmx(&d), Err(Error::Limit("page size"))); +} + +#[test] +fn layer_names_the_reader_cuts_or_drops_are_reported() { + let plain = || Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let named = |name: &str| write_cmx(&drawing(vec![Page { size: None, layers: vec![layer(name, vec![plain()])] }])).unwrap().long_names; + assert!(named("Art\0backup"), "cut at the NUL"); + assert!(named(" "), "blank"); + assert!(!named("Art")); +} + +#[test] +fn an_unfilled_clipping_containers_outline_keeps_its_place() { + // Front to back, whether the outline comes first: over the clipped shape, as an outline with + // no fill to be behind is drawn over it too. + for behind_fill in [false, true] { + let o = Outline { behind_fill, ..outline(Color::Gray(1.0)) }; + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, None, Some(o)); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }])); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + let outlined: Vec = objects.iter().map(|o| shape(o).outline.is_some()).collect(); + assert_eq!(outlined, vec![true, false], "behind_fill {behind_fill}"); + } +} + +#[test] +fn a_filled_clipping_containers_outline_goes_over_unless_behind_the_fill() { + // Front to back, as (fill, outline) of each curve: the outline alone over the clipped shape + // and the fill alone behind it, or the whole container behind it when the outline is behind + // the fill. + for behind_fill in [false, true] { + let o = Outline { behind_fill, ..outline(Color::Gray(1.0)) }; + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.1)), Some(o)); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }])); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + let parts: Vec<(bool, bool)> = objects.iter().map(|o| (shape(o).fill.is_some(), shape(o).outline.is_some())).collect(); + let want = if behind_fill { vec![(true, false), (true, true)] } else { vec![(false, true), (true, false), (true, false)] }; + assert_eq!(parts, want, "behind_fill {behind_fill}"); + } +} + +#[test] +fn a_page_size_of_nothing_is_refused() { + for size in [(0.0, 720.0), (-10.0, 720.0), (f64::NAN, 720.0)] { + let mut d = one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)); + d.pages[0].size = Some(size); + assert_eq!(write_cmx(&d), Err(Error::Limit("page size")), "{size:?}"); + } +} + +#[test] +fn an_ink_with_no_known_look_is_reported() { + let ink = |look| Color::Spot { name: "Ink".into(), tint: 1.0, look }; + let written = |c| write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None))).unwrap().unknown_looks; + assert!(written(ink(None))); + assert!(!written(ink(Some([1.0, 0.0, 0.0])))); +} + +#[test] +fn loops_meeting_at_one_point_are_reported() { + let p = |x, y| Pt { x, y }; + let o = p(0.0, 0.0); + // Three triangles from the origin; the second, inside the first, is wound twice. + let pts = [p(5.0, 0.0), p(2.0, 5.0), o, p(3.0, 1.0), p(2.0, 3.0), o, p(-5.0, 1.0), p(-2.0, 4.0)]; + let sub = SubPath { start: o, segments: pts.map(Segment::Line).to_vec(), closed: true }; + let s = Shape { nonzero: true, ..Shape::new(Geometry::Path(Path { subpaths: vec![sub] }), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_very_thin_outline_stays_thinner_than_a_hairline() { + let o = Outline { width: 0.000_1, ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))); + let width = shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().width; + assert!(width > 0.0 && width < 0.01, "{width}"); +} + +#[test] +fn nested_contours_far_from_the_origin_are_still_compared() { + let p = |x, y| Pt { x, y }; + let ring = |x: f64, side: f64| SubPath { + start: p(x, x), + segments: [p(x + side, x), p(x + side, x + side), p(x, x + side)].map(Segment::Line).to_vec(), + closed: true, + }; + let far = 1.0e8; + let geometry = Geometry::Path(Path { subpaths: vec![ring(far, 10.0), ring(far + 2.0, 1.0)] }); + let back_home = Matrix([1.0, 0.0, 0.0, 1.0, -far, -far]); + let s = Shape { nonzero: true, ..Shape::new(geometry, back_home, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_page_without_a_size_still_writes_its_four_edges() { + let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + // The begin-page instruction: a u16 size, the code 9, then field 1: a tag and its length. + assert_eq!(i16::from_le_bytes([bytes[at + 2], bytes[at + 3]]), 9); + let len = usize::from(u16::from_le_bytes([bytes[at + 5], bytes[at + 6]])); + assert_eq!(len - 3, 2 + 4 + 16 + 4 + 2 + 4, "the page number, the flags, four edges, the end, the layers and the instructions"); +} + +#[test] +fn spot_colors_with_no_name_share_no_look() { + let unnamed = |look| Color::Spot { name: String::new(), tint: 1.0, look }; + let shapes = [unnamed(None), unnamed(Some([1.0, 0.0, 0.0]))] + .map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])).unwrap(); + assert!(w.unnamed_spots && w.unknown_looks); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let fill = shape(&back.pages[0].layers[0].objects[0]).fill.clone().unwrap(); + assert!(near_color(&fill, &Color::Rgb([0.0, 0.0, 0.0])), "{fill:?}"); +} + +#[test] +fn an_ink_used_with_different_looks_is_reported() { + let ink = |tint, look| Color::Spot { name: "Ink".into(), tint, look: Some(look) }; + let written = |second| { + let shapes = + [ink(1.0, [1.0, 0.0, 0.0]), second].map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])).unwrap().merged_looks + }; + assert!(!written(ink(0.5, [1.0, 0.0, 0.0])), "one look"); + assert!(written(ink(0.5, [0.0, 1.0, 0.0])), "a second look"); + // At 1 % both looks store the same color, and only the tint changes it. + let gray = |tint, v| Color::Spot { name: "Gray".into(), tint, look: Some([v; 3]) }; + let shapes = + [gray(1.0, 0.5), gray(0.01, 0.501)].map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])).unwrap(); + assert!(w.zero_tints && !w.merged_looks); +} + +#[test] +fn a_cubic_looping_between_its_samples_is_reported() { + let p = |x, y| Pt { x, y }; + // (s² − 1, s³ − s) for s from −2 to 30 crosses itself at s = −1 and 1. + let mut segments = vec![Segment::Cubic(p(-119.0 / 3.0, 334.0 / 3.0), p(259.0, -5458.0 / 3.0), p(899.0, 26970.0))]; + segments.extend([p(-10.0, 26970.0), p(-10.0, -6.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(3.0, -6.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_page_gives_the_edges_of_its_art() { + // A small square off the center of a large page. + let d = drawing(vec![Page { + size: Some((600.0, 800.0)), + layers: vec![layer( + "L", + vec![Object::Shape(Box::new(Shape::new(square(100.0, 50.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))], + )], + }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + // Field 1 of the begin-page instruction: the page number, the flags, then the left, top, right + // and bottom edges as i32 in 0.1 µm. + let edge = |i: usize| f64::from(i32::from_le_bytes(bytes[at + 13 + 4 * i..at + 17 + 4 * i].try_into().unwrap())) / (0.0254 / 72.0 / 1e-7); + let (l, t, r, b) = (edge(0), edge(1), edge(2), edge(3)); + assert!(near(l, 100.0) && near(t, 60.0) && near(r, 110.0) && near(b, 50.0), "{l} {t} {r} {b}"); +} + +#[test] +fn an_outline_width_that_is_not_a_width_is_refused() { + for width in [f64::NAN, -1.0] { + let o = Outline { width, ..outline(Color::Gray(1.0)) }; + assert_eq!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))), Err(Error::Limit("outline width"))); + } +} + +#[test] +fn a_dash_rounded_away_is_reported() { + let o = Outline { dashes: vec![0.000_000_5, 1.0], ..outline(Color::Gray(1.0)) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap().rounded_dashes); +} + +#[test] +fn a_cubic_closing_on_its_start_is_no_crossing() { + let p = |x, y| Pt { x, y }; + let segments = vec![Segment::Cubic(p(1.0, 0.0), p(0.0, 1.0), p(0.0, 0.0))]; + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_negative_width_is_refused_whatever_its_scale() { + let o = Outline { width: -1.0, scale_with: true, ..outline(Color::Gray(1.0)) }; + let flat = Matrix([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + assert_eq!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), flat, None, Some(o)))), Err(Error::Limit("outline width"))); +} + +#[test] +fn a_page_as_wide_as_the_size_field_holds_is_written() { + // A width that rounds to u32::MAX coordinate units of 0.1 µm, and whose half rounds past what + // an i32 holds. + let widest = (f64::from(u32::MAX) + 0.4) * 1e-7 / 0.0254 * 72.0; + let art = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + for layers in [vec![layer("L", vec![Object::Shape(Box::new(art))])], Vec::new()] { + let d = drawing(vec![Page { size: Some((widest, 100.0)), layers }]); + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + let (w, _) = back.pages[0].size.unwrap(); + assert!((w - widest).abs() < 0.01, "{w}"); + } +} + +#[test] +fn a_page_gives_the_edges_its_curves_reach() { + let p = |x, y| Pt { x, y }; + // An arch whose control points reach 100 pt and whose curve reaches 75 pt. + let arch = SubPath { start: p(0.0, 0.0), segments: vec![Segment::Cubic(p(0.0, 100.0), p(100.0, 100.0), p(100.0, 0.0))], closed: false }; + let s = Shape::new(Geometry::Path(Path { subpaths: vec![arch] }), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let d = drawing(vec![Page { size: Some((600.0, 800.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + let top = f64::from(i32::from_le_bytes(bytes[at + 17..at + 21].try_into().unwrap())) / (0.0254 / 72.0 / 1e-7); + assert!(near(top, 75.0), "{top}"); +} + +#[test] +fn dashes_too_short_to_store_keep_their_gaps_of_nothing() { + let o = Outline { dashes: vec![0.4, 0.0], ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))); + assert_eq!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes, vec![1.0, 0.0]); +} + +#[test] +fn a_rounded_corner_beside_square_ones_keeps_its_radius() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [75.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + // The corner at (100, 0) is entered from (100 − 75, 0) and left toward (100, 75). + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + assert!(pts.iter().any(|q| near(q.x, 25.0) && near(q.y, 0.0)), "{pts:?}"); + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 75.0)), "{pts:?}"); +} + +#[test] +fn many_contours_apart_fill_the_same_either_way() { + let p = |x, y| Pt { x, y }; + let triangle = |i: u32| { + let x = f64::from(i) * 3.0; + SubPath { start: p(x, 0.0), segments: vec![Segment::Line(p(x + 1.0, 0.0)), Segment::Line(p(x, 1.0))], closed: true } + }; + let geometry = Geometry::Path(Path { subpaths: (0..1001).map(triangle).collect() }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_page_gives_the_top_of_a_nearly_flat_cubic() { + let p = |x, y| Pt { x, y }; + // The end one coordinate unit above the start keeps the y derivative quadratic. + let unit = 1e-7 / 0.0254 * 72.0; + let arch = SubPath { start: p(0.0, 0.0), segments: vec![Segment::Cubic(p(0.0, 10000.0), p(1.0, 10000.0), p(1.0, unit))], closed: false }; + let s = Shape::new(Geometry::Path(Path { subpaths: vec![arch] }), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let d = drawing(vec![Page { size: Some((600.0, 800.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + let top = f64::from(i32::from_le_bytes(bytes[at + 17..at + 21].try_into().unwrap())) / (0.0254 / 72.0 / 1e-7); + assert!(near(top, 7500.0), "{top}"); +} + +#[test] +fn a_rounded_rectangle_scaled_unevenly_keeps_round_corners() { + // 100 pt square, 10 pt corners, stretched 4 times across: 400 by 100 pt with 20 pt corners. + let rect = + Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [10.0; 4] }, Matrix([4.0, 0.0, 0.0, 1.0, 0.0, 0.0]), Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + // The corner at (400, 0) is entered 20 pt along the bottom edge and left 20 pt up the side. + assert!(pts.iter().any(|q| near(q.x, 380.0) && near(q.y, 0.0)), "{pts:?}"); + assert!(pts.iter().any(|q| near(q.x, 400.0) && near(q.y, 20.0)), "{pts:?}"); +} + +#[test] +fn a_dash_length_off_a_whole_width_by_a_little_is_reported() { + let o = Outline { dashes: vec![1.000_000_5, 1.0], ..outline(Color::Gray(1.0)) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap().rounded_dashes); +} + +#[test] +fn only_overlapping_corners_shrink() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [80.0, 80.0, 10.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + // The corner at (0, 100) keeps its 10 pt: it is left toward (0, 90). + assert!(pts.iter().any(|q| near(q.x, 0.0) && near(q.y, 90.0)), "{pts:?}"); + // The two 80 pt corners on the right edge meet at its middle. + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 50.0)), "{pts:?}"); +} + +#[test] +fn a_closed_contour_that_fits_one_curve_stays_one_curve() { + let p = |x, y| Pt { x, y }; + // MAX_CURVE_POINTS anchors, the last away from the start: the closing bit closes it. + let n = MAX_CURVE_POINTS; + let segments = (1..n).map(|i| Segment::Line(p(i as f64 * 0.01, if i % 2 == 0 { 0.0 } else { 1.0 }))).collect(); + let s = Shape::new( + Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }), + Matrix::IDENTITY, + None, + Some(outline(Color::Gray(1.0))), + ); + let w = write_cmx(&one_shape(s)).unwrap(); + assert!(!w.split_paths && !w.cut_subpaths); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let Geometry::Path(path) = &shape(&back.pages[0].layers[0].objects[0]).geometry else { panic!() }; + assert!(path.subpaths.len() == 1 && path.subpaths[0].closed); +} + +#[test] +fn a_page_gives_the_edges_of_the_curve_as_written() { + let p = |x, y| Pt { x, y }; + // Controls 0.6 units up round to 1 unit, so the written curve peaks at 0.75 units. + let unit = 1e-7 / 0.0254 * 72.0; + let arch = SubPath { start: p(0.0, 0.0), segments: vec![Segment::Cubic(p(0.0, 0.6 * unit), p(1.0, 0.6 * unit), p(1.0, 0.0))], closed: false }; + let s = Shape::new(Geometry::Path(Path { subpaths: vec![arch] }), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let d = drawing(vec![Page { size: Some((600.0, 800.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + let top = i32::from_le_bytes(bytes[at + 17..at + 21].try_into().unwrap()); + assert!(top >= 1, "{top}"); +} + +#[test] +fn a_blank_layer_name_opens_with_no_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("\u{2003}", vec![plain])] }])).unwrap().bytes; + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.pages[0].layers[0].name.is_empty(), "{:?}", back.pages[0].layers[0].name); +} + +#[test] +fn a_larger_corner_reaches_where_its_smaller_neighbor_begins() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [80.0, 40.0, 0.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + // On the right edge the 80 pt corner is held to 60 pt and the 40 pt one keeps its radius. + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 60.0)), "{pts:?}"); + assert!(pts.iter().any(|q| near(q.x, 60.0) && near(q.y, 100.0)), "{pts:?}"); +} + +#[test] +fn a_long_blank_layer_name_opens_with_no_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer(&" ".repeat(257), vec![plain])] }])).unwrap().bytes; + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.pages[0].layers[0].name.is_empty(), "{:?}", back.pages[0].layers[0].name); +} + +#[test] +fn a_spot_color_with_no_name_at_no_tint_is_reported() { + let unnamed = Color::Spot { name: String::new(), tint: 0.0, look: Some([0.0, 0.0, 1.0]) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(unnamed), None))).unwrap(); + assert!(w.unnamed_spots && w.zero_tints); +} + +#[test] +fn a_drawing_with_no_pages_keeps_its_page_size() { + let mut d = drawing(Vec::new()); + d.page_size = Some((300.0, 200.0)); + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + let (w, h) = back.pages[0].size.unwrap(); + assert!(near(w, 300.0) && near(h, 200.0)); +} + +#[test] +fn layers_give_their_page_and_their_number() { + let plain = || Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let page = || Page { size: None, layers: vec![layer("A", vec![plain()]), layer("B", vec![plain()])] }; + let bytes = write_cmx(&drawing(vec![page(), page()])).unwrap().bytes; + // Each begin-layer instruction: a u16 size, the code 11, field 1 (a tag and a u16 length), then + // the page number and the layer number. + let mut numbers = Vec::new(); + let mut at = 0; + while let Some(i) = bytes[at..].windows(4).position(|w| w == b"page") { + let start = at + i + 8; + let end = start + u32::from_le_bytes(bytes[at + i + 4..start].try_into().unwrap()) as usize; + let mut p = start; + while p < end { + let size = usize::from(u16::from_le_bytes([bytes[p], bytes[p + 1]])); + assert!(size >= 4 && p + size <= end, "an instruction of {size} bytes at {p}"); + if i16::from_le_bytes([bytes[p + 2], bytes[p + 3]]) == 11 { + numbers.push((u16::from_le_bytes([bytes[p + 7], bytes[p + 8]]), u16::from_le_bytes([bytes[p + 9], bytes[p + 10]]))); + } + p += size; + } + at = end; + } + assert_eq!(numbers, [(1, 1), (1, 2), (2, 1), (2, 2)]); +} + +fn u16_at(b: &[u8], at: usize) -> usize { + usize::from(u16::from_le_bytes([b[at], b[at + 1]])) +} + +fn u32_at(b: &[u8], at: usize) -> usize { + u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize +} + +/// The id of each chunk of a written file by where it starts, those inside lists included. +fn chunk_ids(b: &[u8]) -> std::collections::HashMap { + let mut ids = std::collections::HashMap::new(); + let mut stack = vec![(12, b.len())]; + while let Some((mut at, end)) = stack.pop() { + while at + 8 <= end { + let id: [u8; 4] = b[at..at + 4].try_into().unwrap(); + let size = u32_at(b, at + 4); + ids.insert(at, id); + if id == *b"LIST" { + stack.push((at + 12, at + 8 + size)); + } + at += 8 + size + size % 2; + } + } + ids +} + +/// The field list at `at` of `b`, in an instruction that ends at `end`: each field's tag and where +/// its data starts. A field shorter than its 3 header bytes, or past `end`, fails the test. +fn field_starts(b: &[u8], mut at: usize, end: usize) -> Vec<(u8, usize)> { + let mut out = Vec::new(); + while b[at] != 0xff { + let len = u16_at(b, at + 1); + assert!(len >= 3 && at + len <= end, "a field of length {len} at {at}, in an instruction that ends at {end}"); + out.push((b[at], at + 3)); + at += len; + } + out +} + +#[test] +#[should_panic(expected = "a field of length 0")] +fn a_field_of_length_0_fails_the_check() { + field_starts(&[1, 0, 0, 0xff], 0, 4); +} + +#[test] +#[should_panic(expected = "a field of length 9")] +fn a_field_past_its_instruction_fails_the_check() { + field_starts(&[1, 9, 0, 0, 0xff], 0, 5); +} + +#[test] +fn the_index_and_the_records_give_where_everything_is() { + let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let inner = Object::Group { objects: vec![plain(20.0)], flags: Flags::default() }; + let outer = Object::Group { objects: vec![plain(0.0), inner, plain(50.0)], flags: Flags::default() }; + let pages = vec![ + Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![outer]), layer("Back", vec![plain(5.0)])] }, + Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0), plain(2.0)])] }, + ]; + let b = write_cmx(&drawing(pages)).unwrap().bytes; + let page_entries = page_index(&b); + let layer_starts = layer_tables(&b, &page_entries, &[&["Back", "Front"], &["Only"]]); + let (seen_layers, groups) = page_records(&b, &page_entries); + assert_eq!(seen_layers, layer_starts); + // The inner group: itself and a curve; the outer: two curves and the inner group. + assert_eq!(groups, [(0, 3), (1, 7)]); +} + +/// The page index of a written file of two pages, each entry's page chunk, layer table, picture +/// and reference list, checked through the header and the master index. +fn page_index(b: &[u8]) -> Vec<[usize; 4]> { + let ids = chunk_ids(b); + let id = |at: usize| ids.get(&at).map(|i| String::from_utf8_lossy(i).into_owned()).unwrap_or_default(); + // The header names the master index, and no information list or picture. + let cont = 12 + 8; + let ixmr = u32_at(b, cont + 84); + assert_eq!(id(ixmr), "ixmr"); + assert_eq!((u32_at(b, cont + 88), u32_at(b, cont + 92)), (u32::MAX as usize, u32::MAX as usize)); + // The master index names itself, the page index, the table of layer tables and each table. + let m = ixmr + 8; + assert_eq!((u16_at(b, m), u16_at(b, m + 2)), (1, 24)); + let entries: Vec<(usize, String)> = (0..u16_at(b, m + 4)).map(|i| (u16_at(b, m + 6 + 6 * i), id(u32_at(b, m + 8 + 6 * i)))).collect(); + let want = + [(1, "ixmr"), (2, "ixpg"), (3, "ixtl"), (15, "rotl"), (16, "rott"), (17, "rota"), (18, "rscr"), (19, "rpen"), (20, "rdot"), (21, "rclr")]; + assert_eq!(entries, want.map(|(n, s)| (n, s.to_string()))); + let at_of = |n: usize| u32_at(b, m + 8 + 6 * entries.iter().position(|(k, _)| *k == n).unwrap()); + // The page index: each page chunk, its layer table, no picture and its reference list. + let pg = at_of(2) + 8; + assert_eq!(u16_at(b, pg), 2); + let page_entries: Vec<[usize; 4]> = (0..2) + .map(|i| { + let e = pg + 2 + 18 * i; + assert_eq!(u16_at(b, e), 16); + [0, 1, 2, 3].map(|k| u32_at(b, e + 2 + 4 * k)) + }) + .collect(); + for [page, layers, picture, refs] in &page_entries { + assert_eq!((id(*page), id(*layers), *picture, id(*refs)), ("page".into(), "ixlr".into(), u32::MAX as usize, "rlst".into())); + } + // The table of layer tables lists each page's. + let tl = at_of(3) + 8; + assert_eq!([u16_at(b, tl), u16_at(b, tl + 2), u16_at(b, tl + 4)], [2, 4, 3]); + assert_eq!([u32_at(b, tl + 6), u32_at(b, tl + 10)], [page_entries[0][1], page_entries[1][1]]); + page_entries +} + +/// Where each layer table of `page_entries` says the layers named `names` start, checking each +/// table and each reference list: a layer table holds its count, the page number, then each +/// layer's begin-layer instruction and name, back to front; a reference list a count, and 2, 9 and +/// the number of each layer. +fn layer_tables(b: &[u8], page_entries: &[[usize; 4]], names: &[&[&str]]) -> Vec { + let mut layer_starts = Vec::new(); + for (n, (entry, names)) in page_entries.iter().zip(names).enumerate() { + let t = entry[1] + 8; + assert_eq!((u16_at(b, t), u16_at(b, t + 2)), (names.len(), n + 1)); + let mut at = t + 4; + for name in *names { + let size = u16_at(b, at); + let start = u32_at(b, at + 2); + let len = u16_at(b, at + 6); + assert_eq!((size, &b[at + 8..at + 8 + len]), (8 + name.len(), name.as_bytes())); + assert_eq!(u32_at(b, at + 8 + len), u32::MAX as usize); + assert_eq!(u16_at(b, start + 2), 11, "a begin-layer instruction"); + layer_starts.push(start); + at += size + 4; + } + let r = entry[3] + 8; + let refs: Vec = (0..1 + 3 * names.len()).map(|i| u16_at(b, r + 2 * i)).collect(); + let want: Vec = std::iter::once(names.len()).chain((1..=names.len()).flat_map(|k| [2, 9, k])).collect(); + assert_eq!(refs, want); + } + layer_starts +} + +/// An open begin-page, begin-layer or begin-group record: its code, where its field 1 starts, the +/// instructions before it, the records found directly inside it and the edges of its curves. +type Open = (usize, usize, usize, usize, Option<[i32; 4]>); + +/// Check what the record `open` gives, now closed by the instruction of `code` and `size` at `at` +/// after `count` instructions of its page: begin page where the page ends, its layers and its +/// instructions; begin layer its instructions; begin group the edges of its curves, then its +/// groups and instructions, which are returned, and where the instruction after it starts. +fn closed_record(b: &[u8], open: Open, code: usize, at: usize, size: usize, count: usize) -> Option<(usize, usize)> { + let (opened, f1, before, inside, edges) = open; + assert_eq!(opened + 1, code); + let instructions = count - before; + match code { + 10 => { + assert_eq!(u32_at(b, f1 + 22), at, "where the page ends"); + assert_eq!(u16_at(b, f1 + 26), inside, "the page's layers"); + assert_eq!(u32_at(b, f1 + 28), instructions); + None + } + 12 => { + assert_eq!(u32_at(b, f1 + 8), instructions); + None + } + _ => { + let [x0, y0, x1, y1] = edges.unwrap(); + let stored: Vec = (0..4).map(|k| u32_at(b, f1 + 4 * k) as i32).collect(); + assert_eq!(stored, [x0, y1, x1, y0], "left, top, right and bottom"); + assert_eq!(u32_at(b, f1 + 22), at + size, "where the group ends"); + Some((u16_at(b, f1 + 16), u32_at(b, f1 + 18))) + } + } +} + +/// Walk the instructions of each page of `page_entries`, checking the begin-page, begin-layer and +/// begin-group records, and give where each begin-layer instruction starts and each group's +/// groups and instructions, in the order the groups end. +fn page_records(b: &[u8], page_entries: &[[usize; 4]]) -> (Vec, Vec<(usize, usize)>) { + let mut seen_layers = Vec::new(); + let mut groups = Vec::new(); + for entry in page_entries { + let end = entry[0] + 8 + u32_at(b, entry[0] + 4); + let mut at = entry[0] + 8; + let mut open: Vec = Vec::new(); + let mut count = 0; + while at < end { + let size = instruction_size(b, at, end); + let code = u16_at(b, at + 2); + count += 1; + match code { + 9 | 11 | 13 => { + let f1 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 1).unwrap().1; + if code == 11 { + seen_layers.push(at); + } + // A page counts its layers and a group the groups directly inside it. + if code != 9 { + open.last_mut().unwrap().3 += 1; + } + open.push((code, f1, count - 1, 0, None)); + } + 67 => { + let f2 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 2).unwrap().1; + for i in 0..u16_at(b, f2) { + let p = f2 + 2 + 8 * i; + let (x, y) = (u32_at(b, p) as i32, u32_at(b, p + 4) as i32); + for o in open.iter_mut().filter(|o| o.0 == 13) { + let e = o.4.get_or_insert([x, y, x, y]); + *e = [e[0].min(x), e[1].min(y), e[2].max(x), e[3].max(y)]; + } + } + } + 10 | 12 | 14 => groups.extend(closed_record(b, open.pop().unwrap(), code, at, size, count)), + _ => {} + } + at += size; + } + } + (seen_layers, groups) +} + +/// The size of the instruction at `at` of `b`, in a page that ends at `end`. These files hold +/// only short instructions, so the long form (0xFFFF), a size shorter than the 4-byte header or +/// one past `end` fails the test. +fn instruction_size(b: &[u8], at: usize, end: usize) -> usize { + let size = u16_at(b, at); + assert!(size != 0xFFFF && size >= 4 && at + size <= end, "an instruction of size {size} at {at}, in a page that ends at {end}"); + size +} + +#[test] +#[should_panic(expected = "an instruction of size 0")] +fn an_instruction_of_size_0_fails_the_check() { + instruction_size(&[0, 0, 67, 0], 0, 4); +} + +#[test] +#[should_panic(expected = "an instruction of size 65535")] +fn a_long_instruction_fails_the_check() { + instruction_size(&[0xff, 0xff, 67, 0, 8, 0, 0, 0], 0, 8); +} + +#[test] +#[should_panic(expected = "an instruction of size 8")] +fn an_instruction_past_its_page_fails_the_check() { + instruction_size(&[8, 0, 67, 0], 0, 4); +} + +#[test] +fn a_uniform_fill_names_the_screen_the_file_holds() { + let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes; + // The fill's field 1: a tag, a length of 7, the color entry 1 and the screen entry 1. + assert!(bytes.windows(7).any(|w| w == [1, 7, 0, 1, 0, 1, 0])); + assert_eq!(table_entries(&bytes, b"rscr").len(), 1); +} + +#[test] +fn an_unpainted_clipping_container_is_not_written() { + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, None, None); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }])); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + assert_eq!(objects.len(), 1, "only the clipped shape"); +} + +#[test] +fn groups_nested_deeper_than_the_reader_reads_are_refused() { + let nest = |depth: usize| { + let mut o = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + for _ in 0..depth { + o = Object::Group { objects: vec![o], flags: Flags::default() }; + } + drawing(vec![Page { size: None, layers: vec![layer("L", vec![o])] }]) + }; + let deepest = Limits::default().depth; + assert!(round_trip(&nest(deepest)).pages[0].layers.len() == 1, "as deep as the reader reads"); + assert_eq!(write_cmx(&nest(deepest + 1)), Err(Error::Limit("nesting depth"))); +} + +#[test] +fn a_file_the_reader_would_not_take_whole_within_the_limits_is_refused() { + let dashed = Outline { dashes: vec![2.0, 1.0, 3.0], ..outline(Color::Gray(0.0)) }; + let art = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), Some(dashed.clone())))); + let group = Object::Group { objects: vec![art(0.0), art(20.0)], flags: Flags::default() }; + let d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![group, art(40.0)])] }]); + let whole = write_cmx(&d).unwrap().bytes; + let fields: [fn(&mut Limits) -> &mut usize; 5] = + [|l| &mut l.chunks, |l| &mut l.objects, |l| &mut l.coordinates, |l| &mut l.dashes, |l| &mut l.depth]; + for (i, field) in fields.into_iter().enumerate() { + let (mut written, mut refused) = (false, false); + for v in 0..=80 { + let mut limits = Limits::default(); + *field(&mut limits) = v; + // What the reader takes from the file written within the default limits. + let opens_whole = read_cmx(&whole, limits).is_ok_and(|back| back.warnings.is_empty()); + match craft_cdr::write_cmx(&d, limits) { + Ok(w) => { + written = true; + assert!(opens_whole, "field {i} at {v}: written but not read whole"); + assert_eq!(w.bytes, whole, "field {i} at {v}"); + } + Err(e) => { + refused = true; + assert!(matches!(e, Error::Limit(_)), "field {i} at {v}: {e:?}"); + assert!(!opens_whole, "field {i} at {v}: refused but read whole"); + } + } + } + assert!(written && refused, "field {i}: both outcomes within 0 to 80"); + } + let input = |n: usize| craft_cdr::write_cmx(&d, Limits { input: n, ..Limits::default() }); + assert!(input(whole.len()).is_ok()); + assert_eq!(input(whole.len() - 1), Err(Error::Limit("input size"))); + // A pattern with no positive length is solid, and the reader takes no dashes for it. + let solid = Outline { dashes: vec![f64::NAN, 0.0], ..outline(Color::Gray(0.0)) }; + let one = one_shape(Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, None, Some(solid))); + let w = craft_cdr::write_cmx(&one, Limits { dashes: 0, ..Limits::default() }).unwrap(); + assert!(w.rounded_dashes, "the length that is not a number"); + assert!(read_cmx(&w.bytes, Limits { dashes: 0, ..Limits::default() }).unwrap().warnings.is_empty()); +} + +#[test] +fn a_negative_radius_leaves_its_corner_square() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [-20.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 0.0)), "{pts:?}"); +} + +#[test] +fn every_use_of_an_ink_takes_the_look_of_its_strongest_tint() { + let ink = |tint, look| Color::Spot { name: "Ink".into(), tint, look: Some(look) }; + let filled = |c, hidden| { + let mut s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None); + s.flags.hidden = hidden; + Object::Shape(Box::new(s)) + }; + let d = drawing(vec![Page { + size: None, + layers: vec![layer("L", vec![filled(ink(0.5, [0.0, 1.0, 0.0]), false), filled(ink(1.0, [1.0, 0.0, 0.0]), true)])], + }]); + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + assert!(near_color(shape(&back.pages[0].layers[0].objects[0]).fill.as_ref().unwrap(), &ink(0.5, [1.0, 0.0, 0.0]))); +} + +#[test] +fn a_name_that_is_only_nuls_as_written_is_reported() { + let name = format!("{}Ink", "\0".repeat(4096)); + let c = Color::Spot { name, tint: 1.0, look: Some([1.0, 0.0, 0.0]) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None))).unwrap(); + assert!(w.unnamed_spots && w.long_names); +} + +#[test] +fn a_tint_too_low_to_keep_the_look_is_reported() { + let pale = Color::Spot { name: "Pale".into(), tint: 0.01, look: Some([1.0, 0.85, 0.85]) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(pale), None))).unwrap().zero_tints); +} + +#[test] +fn a_shape_split_into_curves_paints_its_fill_before_its_outline() { + let p = |x, y| Pt { x, y }; + // A long polyline, then a square: two curves. + let segments = (1..MAX_CURVE_POINTS).map(|i| Segment::Line(p(i as f64 * 0.01, 5.0))).collect(); + let long = SubPath { start: p(0.0, 0.0), segments, closed: false }; + let Geometry::Path(sq) = square(2.0, 2.0, 5.0) else { panic!() }; + for behind_fill in [false, true] { + let geometry = Geometry::Path(Path { subpaths: vec![long.clone(), sq.subpaths[0].clone()] }); + let o = Outline { behind_fill, ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.2)), Some(o)))); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + // Each curve carries the fill or the outline, the outlines all on one side of the fills. + let outlines: Vec = objects.iter().map(|o| shape(o).outline.is_some()).collect(); + assert!(objects.iter().all(|o| shape(o).fill.is_some() != shape(o).outline.is_some()), "{outlines:?}"); + assert!(outlines.windows(2).all(|w| w[0] >= w[1]) || outlines.windows(2).all(|w| w[0] <= w[1]), "{outlines:?}"); + // Front to back: the outline is in front unless it is drawn behind the fill. + assert_eq!(outlines[0], !behind_fill, "{outlines:?}"); + } +} + +#[test] +fn a_dash_pattern_past_one_table_entry_is_refused() { + let file = |n: usize| { + let o = Outline { dashes: vec![1.0; n], ..outline(Color::Gray(1.0)) }; + write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))) + }; + assert!(file(32_765).is_ok()); + assert_eq!(file(32_766), Err(Error::Limit("table entry size"))); +} + +#[test] +fn a_contour_whose_area_sums_to_nothing_counts_as_either_turn() { + let p = |x, y| Pt { x, y }; + let tri = |pts: [Pt; 3]| SubPath { start: pts[0], segments: vec![Segment::Line(pts[1]), Segment::Line(pts[2])], closed: true }; + let (a, b, c) = (p(0.0, 0.0), p(100_000_000.0, 99_999_999.0), p(100_000_001.0, 100_000_000.0)); + let geometry = Geometry::Path(Path { subpaths: vec![tri([a, b, c]), tri([b, c, a])] }); + let m = Matrix([16.0, -299_999_997.0, -16.0, 300_000_000.0, 0.0, 0.0]); + let s = Shape { nonzero: true, ..Shape::new(geometry, m, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_cubic_looping_from_its_start_is_reported() { + let p = |x, y| Pt { x, y }; + let mut segments = vec![Segment::Cubic(p(-10.0, 0.0), p(150.0, -10.0), p(480.0, 480.0))]; + segments.extend([p(-1.0, 480.0), p(-1.0, -1.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_cubic_crossing_an_edge_between_its_flattened_points_is_reported() { + let p = |x, y| Pt { x, y }; + // The arch (16 t, 9 t (1 − t)) is flattened at whole x; at x = 7.5 its line is at y = 2.2324 + // and the arch at y = 2.2412. A notch down to `tip` stays clear of the line, and crosses the + // arch when the tip is below it. + let filled = |tip: f64| { + let mut segments = vec![Segment::Cubic(p(16.0 / 3.0, 3.0), p(32.0 / 3.0, 3.0), p(16.0, 0.0))]; + segments.extend([p(16.0, 6.0), p(7.5, tip), p(0.0, 6.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + write_cmx(&one_shape(s)).unwrap().nonzero_fills + }; + assert!(filled(2.237)); + assert!(!filled(2.3)); +} + +#[test] +fn a_cubic_crossing_the_next_edge_near_their_shared_point_is_reported() { + let p = |x: f64, y: f64| Pt { x: x * 1000.0, y: y * 1000.0 }; + // The arch (16 t, 9 t (1 − t)) ends at (16, 0) heading back at a slope of 9/16, and the line + // from there to (0, 8.8) leaves at a slope of 0.55: the arch starts above the line and crosses + // it. The arch's last flattened piece, at a slope of 0.527, stays below the line. + let segments = vec![Segment::Cubic(p(16.0 / 3.0, 3.0), p(32.0 / 3.0, 3.0), p(16.0, 0.0)), Segment::Line(p(0.0, 8.8))]; + let arch = SubPath { start: p(0.0, 0.0), segments, closed: true }; + // A clockwise square apart from it. + let square = SubPath { start: p(20.0, 0.0), segments: [p(20.0, 1.0), p(21.0, 1.0), p(21.0, 0.0)].map(Segment::Line).to_vec(), closed: true }; + let geometry = Geometry::Path(Path { subpaths: vec![arch, square] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); + // A square whose bottom edge is a straight cubic that eases in and out, so its first and last + // flattened pieces are short beside the lines next to them, crosses nothing. + let eased = vec![Segment::Cubic(p(0.0, 0.0), p(10.0, 0.0), p(10.0, 0.0)), Segment::Line(p(10.0, 10.0)), Segment::Line(p(0.0, 10.0))]; + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments: eased, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); + // A crescent: two arcs that leave each tip along the same tangent and part at once. + let arcs = vec![Segment::Cubic(p(2.0, 4.0), p(8.0, 4.0), p(10.0, 0.0)), Segment::Cubic(p(9.0, 2.0), p(1.0, 2.0), p(0.0, 0.0))]; + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments: arcs, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_blank_layer_name_before_a_nul_opens_with_no_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("\u{2003}\0", vec![plain])] }])).unwrap().bytes; + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.pages[0].layers[0].name.is_empty(), "{:?}", back.pages[0].layers[0].name); +} + +#[test] +fn marks_too_short_to_store_stay_visible() { + let o = Outline { dashes: vec![0.4, 2.0], ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))); + assert_eq!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes, vec![1.0, 2.0]); +} + +#[test] +fn a_spot_color_without_a_look_takes_the_look_of_its_ink() { + let ink = |look| Color::Spot { name: "Ink".into(), tint: 1.0, look }; + let shapes = + [ink(None), ink(Some([1.0, 0.0, 0.0]))].map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])); + for o in &back.pages[0].layers[0].objects { + assert!(near_color(shape(o).fill.as_ref().unwrap(), &ink(Some([1.0, 0.0, 0.0]))), "{:?}", shape(o).fill); + } +} + +#[test] +fn art_on_a_desktop_layer_is_reported() { + let art = vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))]; + let desktop = Layer { kind: LayerKind::Desktop, ..layer("Desktop", art) }; + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![desktop] }])).unwrap(); + assert!(w.left_out); + assert_eq!(read_cmx(&w.bytes, Limits::default()).unwrap().pages[0].layers[0].objects.len(), 1, "the art is kept"); +} + +#[test] +fn dashes_too_short_to_store_are_reported() { + let o = Outline { dashes: vec![0.0, 0.000_000_5], ..outline(Color::Gray(1.0)) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap().rounded_dashes); +} + +#[test] +fn a_spot_color_with_no_name_is_reported() { + let unnamed = Color::Spot { name: String::new(), tint: 0.5, look: Some([0.0, 0.0, 1.0]) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(unnamed), None))).unwrap(); + assert!(w.unnamed_spots && !w.zero_tints); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let fill = shape(&back.pages[0].layers[0].objects[0]).fill.clone().unwrap(); + assert!(near_color(&fill, &Color::Rgb([0.5, 0.5, 1.0])), "{fill:?}"); +} + +#[test] +fn a_layer_name_keeps_its_windows_1252_characters_in_the_8_bit_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("€ ‰ 中", vec![plain])] }])).unwrap().bytes; + // The 8-bit name: a u16 count, then the bytes. + let narrow = [5u8, 0, 0x80, b' ', 0x89, b' ', b'?']; + assert!(bytes.windows(narrow.len()).any(|w| w == narrow), "the euro and per-mille signs have bytes; the last character has none"); +} + +#[test] +fn more_layers_than_the_layer_number_holds_are_refused() { + let layers = (0..=usize::from(u16::MAX)).map(|_| layer("", Vec::new())).collect(); + assert_eq!(write_cmx(&drawing(vec![Page { size: None, layers }])), Err(Error::Limit("layers"))); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + /// Paths of lines and curves read back with every point within a coordinate unit. + #[test] + fn paths_read_back_point_for_point( + pts in prop::collection::vec((-1.0e5f64..1.0e5, -1.0e5f64..1.0e5), 4..60), + closed in any::(), + curves in any::(), + ) { + let p = |(x, y): (f64, f64)| Pt { x, y }; + let start = p(pts[0]); + let segments: Vec = if curves { + pts[1..].as_chunks::<3>().0.iter().map(|[a, b, c]| Segment::Cubic(p(*a), p(*b), p(*c))).collect() + } else { + pts[1..].iter().map(|q| Segment::Line(p(*q))).collect() + }; + prop_assume!(!segments.is_empty()); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start, segments, closed }] }); + let s = Shape::new(geometry.clone(), Matrix::IDENTITY, Some(Color::Rgb([0.5, 0.5, 0.5])), None); + let d = drawing(vec![Page { size: Some((612.0, 792.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let back = round_trip(&d); + let read = &shape(&back.pages[0].layers[0].objects[0]).geometry; + let Geometry::Path(path) = read else { panic!() }; + prop_assert_eq!(path.subpaths[0].closed, closed); + let (want, got) = (points(&geometry), points(read)); + prop_assert_eq!(got.len(), want.len()); + for (a, b) in want.iter().zip(&got) { + prop_assert!(near(a.x, b.x) && near(a.y, b.y), "{:?} {:?}", a, b); + } + } +} diff --git a/crates/cdr/tests/it/main.rs b/crates/cdr/tests/it/main.rs index 4fc7dcbdc9..6057491186 100644 --- a/crates/cdr/tests/it/main.rs +++ b/crates/cdr/tests/it/main.rs @@ -4,5 +4,7 @@ mod bench; mod cmx; +mod cmx_write; mod provenance; mod read; +mod write; diff --git a/crates/cdr/tests/it/write.rs b/crates/cdr/tests/it/write.rs new file mode 100644 index 0000000000..6112e035f8 --- /dev/null +++ b/crates/cdr/tests/it/write.rs @@ -0,0 +1,976 @@ +//! Writing drawings and reading them back. + +use std::io::Read as _; + +use craft_cdr::WriteError as Error; +use craft_cdr::model::{ + Blend, Cap, Color, Drawing, Flags, Geometry, Guideline, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath, +}; +use craft_cdr::{Limits, WRITTEN_VERSION, is_cdr, read, write}; +use proptest::prelude::*; + +/// `n` coordinate units (1/254000 inch) in points, which the file stores exactly. +fn u(n: i32) -> f64 { + f64::from(n) * (72.0 / 254_000.0) +} + +fn pt(x: i32, y: i32) -> Pt { + Pt { x: u(x), y: u(y) } +} + +/// A byte value as a color component, which the file stores exactly. +fn c(v: u8) -> f32 { + f32::from(v) / 255.0 +} + +fn moved(x: f64, y: f64) -> Matrix { + Matrix([1.0, 0.0, 0.0, 1.0, x, y]) +} + +fn layer(name: &str, objects: Vec) -> Layer { + Layer { name: name.into(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() } +} + +fn rect(w: i32, h: i32, fill: Option) -> Object { + Object::Shape(Box::new(Shape::new(Geometry::Rect { w: u(w), h: u(h), radii: [0.0; 4] }, moved(10.0, -20.0), fill, None))) +} + +/// A drawing of one page and one layer holding `objects`. +fn one_layer(objects: Vec) -> Drawing { + Drawing { + version: WRITTEN_VERSION, + page_size: None, + pages: vec![Page { size: None, layers: vec![layer("A", objects)] }], + master: Vec::new(), + guides: Vec::new(), + warnings: Vec::new(), + } +} + +/// A drawing with every kind of thing the writer writes. +fn everything() -> Drawing { + let black = Outline { + width: u(5080), + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let dashed = Outline { + width: u(2540), + color: Color::Cmyk([c(0), c(128), c(255), c(13)]), + cap: Cap::Round, + join: Join::Bevel, + dashes: vec![3.0, 1.0], + behind_fill: true, + scale_with: true, + }; + let curve = Path { + subpaths: vec![ + SubPath { + start: pt(0, 0), + segments: vec![Segment::Line(pt(254_000, 0)), Segment::Cubic(pt(254_000, 50_000), pt(100_000, 254_000), pt(0, 254_000))], + closed: true, + }, + SubPath { start: pt(-1000, -1000), segments: vec![Segment::Line(pt(-5000, -9000))], closed: false }, + ], + }; + let mut path = + Shape::new(Geometry::Path(curve), Matrix([0.5, 0.25, -0.25, 2.0, 100.0, -40.0]), Some(Color::Rgb([c(255), c(64), c(0)])), Some(dashed)); + path.nonzero = true; + path.opacity = 0.75; + path.blend = Blend::Multiply; + let mut rounded = Shape::new( + Geometry::Rect { w: u(200_000), h: u(-100_000), radii: [u(10_000), u(0), u(25_000), u(50_000)] }, + moved(0.0, 0.0), + Some(Color::Registration), + Some(black.clone()), + ); + rounded.flags = Flags { hidden: true, locked: true }; + let spot = Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([0.0, c(255), 0.0]) }; + let ellipse = Shape::new( + Geometry::Ellipse { w: u(80_000), h: u(40_000) }, + moved(-30.0, 30.0), + Some(spot.clone()), + Some(Outline { color: spot, ..black.clone() }), + ); + let container = Shape::new(Geometry::Rect { w: u(100_000), h: u(100_000), radii: [0.0; 4] }, moved(0.0, 0.0), None, Some(black.clone())); + let inner = Object::Clip { container: Box::new(container.clone()), objects: vec![rect(10_000, 10_000, Some(Color::Gray(c(128))))] }; + let clip = Object::Clip { container: Box::new(container), objects: vec![rect(20_000, 30_000, None), inner] }; + let group = Object::Group { + objects: vec![Object::Shape(Box::new(ellipse)), rect(1000, 2000, Some(Color::Gray(0.0)))], + flags: Flags { hidden: true, locked: false }, + }; + let mut art = layer("Art", vec![Object::Shape(Box::new(path)), Object::Shape(Box::new(rounded)), group, clip]); + art.guides.push(Guideline { at: pt(0, 254_000), angle: -45.0, hidden: false }); + let mut back = layer("Back ünïcode", vec![rect(5000, 5000, Some(Color::Rgb([c(1), c(2), c(3)])))]); + back.flags = Flags { hidden: true, locked: true }; + let mut desktop = layer("Desktop", vec![rect(3000, 3000, None)]); + desktop.kind = LayerKind::Desktop; + Drawing { + version: WRITTEN_VERSION, + page_size: Some((u(2_159_000), u(2_794_000))), + pages: vec![ + Page { size: Some((u(2_159_000), u(2_794_000))), layers: vec![art, back] }, + Page { size: Some((u(1_000_000), u(500_000))), layers: vec![layer("Second", vec![rect(7000, 8000, None)])] }, + ], + master: vec![desktop], + guides: vec![Guideline { at: pt(254_000, 0), angle: 90.0, hidden: false }], + warnings: Vec::new(), + } +} + +/// Rounds every number of `d` past the precision a round trip keeps. +fn rounded(mut d: Drawing) -> Drawing { + fn r(v: &mut f64) { + *v = (*v * 1e4).round() / 1e4 + 0.0; + } + fn rc(c: &mut Color) { + let f = |v: &mut f32| *v = (*v * 1e3).round() / 1e3 + 0.0; + match c { + Color::Rgb(v) => v.iter_mut().for_each(f), + Color::Cmyk(v) => v.iter_mut().for_each(f), + Color::Gray(v) => f(v), + Color::Registration => {} + Color::Spot { tint, look, .. } => { + f(tint); + if let Some(l) = look { + l.iter_mut().for_each(f); + } + } + } + } + fn rp(p: &mut Pt) { + r(&mut p.x); + r(&mut p.y); + } + fn rs(s: &mut Shape) { + s.matrix.0.iter_mut().for_each(r); + match &mut s.geometry { + Geometry::Rect { w, h, radii } => { + r(w); + r(h); + radii.iter_mut().for_each(r); + } + Geometry::Ellipse { w, h } => { + r(w); + r(h); + } + Geometry::Path(p) => { + for sp in &mut p.subpaths { + rp(&mut sp.start); + for seg in &mut sp.segments { + match seg { + Segment::Line(a) => rp(a), + Segment::Cubic(a, b, e) => [a, b, e].into_iter().for_each(rp), + } + } + } + } + } + s.fill.iter_mut().for_each(rc); + if let Some(o) = &mut s.outline { + r(&mut o.width); + rc(&mut o.color); + } + s.opacity = (s.opacity * 1e3).round() / 1e3; + } + let mut stack: Vec<&mut Object> = Vec::new(); + for l in d.pages.iter_mut().flat_map(|p| p.layers.iter_mut()).chain(d.master.iter_mut()) { + for g in &mut l.guides { + rp(&mut g.at); + } + stack.extend(l.objects.iter_mut()); + } + while let Some(o) = stack.pop() { + match o { + Object::Shape(s) => rs(s), + Object::Group { objects, .. } => stack.extend(objects.iter_mut()), + Object::Clip { container, objects } => { + rs(container); + stack.extend(objects.iter_mut()); + } + } + } + for g in &mut d.guides { + rp(&mut g.at); + } + for (w, h) in d.pages.iter_mut().filter_map(|p| p.size.as_mut()).chain(d.page_size.as_mut()) { + r(w); + r(h); + } + d +} + +/// `d` as it reads back once written: rounded, and each closed subpath whose last segment ends away +/// from its start given a closing line to its start. +fn as_read(d: Drawing) -> Drawing { + let mut d = rounded(d); + let mut stack: Vec<&mut Object> = d.pages.iter_mut().flat_map(|p| p.layers.iter_mut()).flat_map(|l| l.objects.iter_mut()).collect(); + stack.extend(d.master.iter_mut().flat_map(|l| l.objects.iter_mut())); + while let Some(o) = stack.pop() { + let shape = match o { + Object::Shape(s) => s, + Object::Group { objects, .. } => { + stack.extend(objects.iter_mut()); + continue; + } + Object::Clip { container, objects } => { + stack.extend(objects.iter_mut()); + container + } + }; + let Geometry::Path(p) = &mut shape.geometry else { continue }; + for sp in &mut p.subpaths { + let end = sp.segments.last().map(|s| match s { + Segment::Line(e) | Segment::Cubic(_, _, e) => *e, + }); + if sp.closed && end.is_some_and(|e| e != sp.start) { + sp.segments.push(Segment::Line(sp.start)); + } + } + } + d +} + +/// The RIFF file inside a written package. +fn riff_of(file: &[u8]) -> Vec { + // The second member, after the stored `mimetype`. + let (name, data) = member(file, 0); + assert_eq!((name, data), (&b"mimetype"[..], &b"application/x-vnd.corel.draw.document+zip"[..])); + let next = 30 + name.len() + data.len(); + let (name, data) = member(file, next); + assert_eq!(name, b"content/riffData.cdr"); + let mut out = Vec::new(); + flate2::read::DeflateDecoder::new(data).read_to_end(&mut out).unwrap(); + out +} + +/// The name and packed bytes of the member whose local header is at `at`. +fn member(file: &[u8], at: usize) -> (&[u8], &[u8]) { + let le16 = |i: usize| usize::from(u16::from_le_bytes([file[at + i], file[at + i + 1]])); + let packed = u32::from_le_bytes(file[at + 18..at + 22].try_into().unwrap()) as usize; + let name = &file[at + 30..at + 30 + le16(26)]; + let start = at + 30 + le16(26) + le16(28); + (name, &file[start..start + packed]) +} + +fn count(hay: &[u8], needle: &[u8]) -> usize { + hay.windows(needle.len()).filter(|w| *w == needle).count() +} + +#[test] +fn a_written_drawing_reads_back_as_written() { + let d = everything(); + let file = write(&d, Limits::default()).unwrap(); + let back = read(&file, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(rounded(back), as_read(d)); +} + +#[test] +fn a_written_file_is_a_version_15_package_and_the_same_each_time() { + let file = write(&everything(), Limits::default()).unwrap(); + assert!(is_cdr(&file) && file.starts_with(b"PK\x03\x04")); + let riff = riff_of(&file); + assert_eq!(&riff[8..12], b"CDRF"); + assert_eq!(&riff[12..18], b"vrsn\x02\0"); + assert_eq!(read(&file, Limits::default()).unwrap().version, 1500); + assert_eq!(file, write(&everything(), Limits::default()).unwrap()); + // `mcfg` starts with the tag 1300 and the length of the rest (R72). + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let mcfg = riff.windows(4).position(|w| w == b"mcfg").unwrap(); + assert_eq!((le32(mcfg + 8), le32(mcfg + 12)), (1300, le32(mcfg + 4) - 8)); + // Every child of `LIST filt` is a `LIST filc` that holds one `fild` and nothing else (R72). + let padded = |size: usize| 8 + size + (size & 1); + let filt = riff.windows(12).position(|w| &w[..4] == b"LIST" && &w[8..] == b"filt").unwrap(); + let (mut at, end) = (filt + 12, filt + 8 + le32(filt + 4)); + let mut lists = 0; + while at < end { + assert_eq!((&riff[at..at + 4], &riff[at + 8..at + 12], &riff[at + 12..at + 16]), (&b"LIST"[..], &b"filc"[..], &b"fild"[..])); + assert_eq!(at + 12 + padded(le32(at + 16)), at + padded(le32(at + 4))); + at += padded(le32(at + 4)); + lists += 1; + } + assert_eq!((at, lists), (end, count(&riff, b"fild"))); + assert!(lists > 0); +} + +#[test] +fn each_container_names_its_own_clipped_group_by_the_stored_id() { + let riff = riff_of(&write(&everything(), Limits::default()).unwrap()); + let ids: Vec = + (0..riff.len() - 12).filter(|&p| &riff[p..p + 4] == b"spnd").map(|p| u32::from_le_bytes(riff[p + 8..p + 12].try_into().unwrap())).collect(); + let mut distinct = ids.clone(); + distinct.sort_unstable(); + distinct.dedup(); + assert!(ids.len() > 1 && distinct.len() == ids.len(), "{ids:?}"); + // The first u32 of each container argument (8005), from every `loda` record: a `loda` chunk's + // body starts with its own length. + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let mut named: Vec = (0..riff.len() - 28) + .filter(|&p| &riff[p..p + 4] == b"loda" && le32(p + 4) == le32(p + 8)) + .flat_map(|p| { + let loda = p + 8; + let (n, offsets, types) = (le32(loda + 4), loda + le32(loda + 8), loda + le32(loda + 12)); + (0..n).filter(move |i| le32(types + 4 * (n - 1 - i)) == 8005).map(move |i| le32(loda + le32(offsets + 4 * i)) as u32) + }) + .collect(); + named.sort_unstable(); + // Each container names its group by the group's `spnd` id unchanged, and no two name one group. + assert_eq!(named, distinct); +} + +#[test] +fn shapes_with_the_same_fill_and_outline_share_one_record_of_each() { + let fill = || Some(Color::Rgb([c(10), c(20), c(30)])); + let records = |d: &Drawing| { + let riff = riff_of(&write(d, Limits::default()).unwrap()); + (count(&riff, b"fild"), count(&riff, b"outl")) + }; + assert_eq!(records(&one_layer((0..50).map(|i| rect(1000 + i, 1000, fill())).collect())), records(&one_layer(vec![rect(1000, 1000, fill())]))); +} + +#[test] +fn a_closed_subpath_ends_at_its_start_and_its_other_nodes_can_be_edited() { + let start = pt(1234, 5678); + let open_end = SubPath { start, segments: vec![Segment::Line(pt(90_000, 5678)), Segment::Line(pt(1234, 90_000))], closed: true }; + let triangle = + |sp: SubPath| one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(Path { subpaths: vec![sp] }), Matrix::IDENTITY, None, None)))]); + let riff = riff_of(&write(&triangle(open_end.clone()), Limits::default()).unwrap()); + // The closing point at the start, then the type bytes: an editable closed move, two editable + // line ends and the closing line end, which is not editable. + let tail: Vec = [1234i32, 5678].iter().flat_map(|v| v.to_le_bytes()).chain([0x0C, 0x44, 0x44, 0x48]).collect(); + assert_eq!(count(&riff, &tail), 1); + // A subpath that already ends at its start is written as it is. + let mut ends_at_start = open_end; + ends_at_start.segments.push(Segment::Line(start)); + assert_eq!(riff_of(&write(&triangle(ends_at_start), Limits::default()).unwrap()), riff); +} + +#[test] +fn every_page_names_the_master_pages_guides_desktop_and_grid_by_their_ids() { + let mut d = everything(); + // A drawing layer of the master page, which the other pages do not name. The drawing has no + // grid layer of its own, as a read drawing has none. + d.master.push(layer("Master art", vec![rect(100, 100, None)])); + let riff = riff_of(&write(&d, Limits::default()).unwrap()); + let layers = layer_entries(&riff); + // Each page names the master page's guides, desktop and grid layers (object types 12, 17 and + // 11) once each, by kind, name and id: the guides and desktop before the page's own layers, + // the grid after them. + let named = |page: usize, kinds: &[usize]| { + let kept = |l: &&Entry| l.0 == page && l.1 == 1 && kinds.contains(&l.2); + let mut v: Vec<_> = layers.iter().filter(kept).map(|l| (l.2, &l.3, &l.4)).collect(); + v.sort(); + v + }; + assert_eq!(named(0, &[11, 12, 17]).len(), 3); + for page in 1..=d.pages.len() { + assert_eq!(named(page, &[11, 12, 17, 0]), named(0, &[11, 12, 17])); + let kinds: Vec = layers.iter().filter(|l| l.0 == page).map(|l| if l.1 == 0 { 0 } else { l.2 }).collect(); + let own = kinds.iter().position(|k| *k == 0).unwrap(); + assert!(kinds[..own].iter().all(|k| [12, 17].contains(k)) && kinds[own..].iter().filter(|k| **k != 0).all(|k| *k == 11), "{kinds:?}"); + assert!(kinds.ends_with(&[11]), "{kinds:?}"); + } + // The master page's layers and the pages' own layers each have their own 16-byte id. + let mut own: Vec<&[u8]> = layers.iter().filter(|l| l.0 == 0 || l.1 == 0).map(|l| &l.4[..]).collect(); + assert!(own.iter().all(|id| id.len() == 16)); + let count = own.len(); + own.sort(); + own.dedup(); + assert_eq!(own.len(), count); + // The guides layer, the first layer written, gets another id in a drawing that differs only in + // a fill color. + // A guides layer of the drawing's own master page takes the drawing's guidelines too, and is + // the only guides layer there; a hidden or locked one keeps them off it. + let guide = |x: i32| Guideline { at: pt(x, 0), angle: 90.0, hidden: false }; + let with_guides = |flags: Flags, drawing_guides: Vec| { + let mut guides = layer("Guides", Vec::new()); + guides.kind = LayerKind::Guides; + guides.flags = flags; + guides.guides = vec![guide(100)]; + Drawing { master: vec![guides], guides: drawing_guides, ..one_layer(Vec::new()) } + }; + for (flags, drawing_guides, layers) in [ + (Flags::default(), vec![guide(200)], 1), + (Flags { hidden: true, locked: false }, Vec::new(), 1), + (Flags { hidden: true, locked: false }, vec![guide(200)], 2), + (Flags { hidden: false, locked: true }, vec![guide(200)], 2), + ] { + let d = with_guides(flags, drawing_guides.clone()); + let file = write(&d, Limits::default()).unwrap(); + let entries = layer_entries(&riff_of(&file)); + assert_eq!(entries.iter().filter(|l| l.0 == 0 && l.2 == 12).count(), layers, "{flags:?}"); + // Each guideline once, the drawing's in a layer that is shown and unlocked: each guideline + // object's x (in units), and bytes 0 and 1 of the flags of the layer it is in. + let riff = riff_of(&file); + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let mut placed: Vec<(i32, u8, u8)> = (0..riff.len() - 28) + .filter(|&p| &riff[p..p + 4] == b"loda" && le32(p + 8 + 16) == 0x16) + .map(|p| { + let arg = p + 8 + le32(p + 8 + le32(p + 8 + 8)); + let layr = riff[..p].windows(8).rposition(|w| w == b"layrflgs").unwrap(); + (i32::from_le_bytes(riff[arg + 16..arg + 20].try_into().unwrap()), riff[layr + 12], riff[layr + 13]) + }) + .collect(); + placed.sort(); + let xs: Vec = placed.iter().map(|g| g.0).collect(); + assert_eq!(xs, if drawing_guides.is_empty() { vec![100] } else { vec![100, 200] }, "{flags:?}"); + assert!(placed.iter().filter(|g| g.0 == 200).all(|g| g.1 & 0x10 == 0 && g.2 == 0), "{flags:?}"); + } + let first = |c: Color| layer_entries(&riff_of(&write(&one_layer(vec![rect(100, 100, Some(c))]), Limits::default()).unwrap()))[0].4.clone(); + assert_ne!(first(Color::Gray(0.0)), first(Color::Gray(1.0))); +} + +/// A layer list of a written file: its page (0 the master page), byte 2 of its flags, its object +/// type, and its name and id arguments. +type Entry = (usize, u8, usize, Vec, Vec); + +/// The layer lists of `riff`, each `layr` with its `flgs` chunk, then `LIST lgob` with its `loda`. +fn layer_entries(riff: &[u8]) -> Vec { + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let pages: Vec = riff.windows(12).enumerate().filter(|(_, w)| &w[..4] == b"LIST" && &w[8..] == b"page").map(|(p, _)| p).collect(); + riff.windows(8) + .enumerate() + .filter(|(_, w)| w == b"layrflgs") + .map(|(p, _)| { + let page = pages.iter().filter(|&&at| at < p).count() - 1; + let loda = p + 36; + let (n, offsets, types) = (le32(loda + 4), loda + le32(loda + 8), loda + le32(loda + 12)); + let arg = |t: usize| { + let i = (0..n).find(|i| le32(types + 4 * (n - 1 - i)) == t).unwrap(); + riff[loda + le32(offsets + 4 * i)..loda + le32(offsets + 4 * i + 4)].to_vec() + }; + (page, riff[p + 14], le32(loda + 16), arg(1000), arg(40050)) + }) + .collect() +} + +#[test] +fn a_guideline_runs_along_the_angle_it_stores() { + // Starts `by` units inside a corner of the coordinate range. + let near = |by: f64| Pt { x: u(i32::MAX) - by * u(1), y: u(i32::MAX) - by * u(1) }; + let guide = |at: Pt, angle: f64| Drawing { guides: vec![Guideline { at, angle, hidden: false }], ..one_layer(Vec::new()) }; + // A quarter of a unit past the corner, on the corner itself, and less than half a unit inside + // it, the start rounds onto the corner, and no other point of the line rounds within the range + // along it. The last line runs almost level, so every point of it in the range rounds onto the + // corner too, as does the line that starts on the corner and half a unit past it. + let on_corner = Pt { x: 608_735.521_984_251_9, y: 608_735.521_984_251_9 }; + let level = [(near(-0.49), -0.9), (Pt { x: 608_735.521_984_252, y: 608_735.522_125_984_2 }, -0.00004)]; + for (at, angle) in [near(-0.25), on_corner, near(0.1), near(0.01), near(0.00025)].map(|at| (at, -45.0)).into_iter().chain(level) { + assert!(matches!(write(&guide(at, angle), Limits::default()), Err(Error::Unwritable(_))), "{at:?}"); + } + let inside = [(pt(1000, 2000), 30.0), (pt(1000, 2000), -45.0), (pt(1000, 2000), 1e20)]; + // A unit or more inside the corner, a point a whole unit or more away on each axis fits; + // at 1.25 units the farthest points in the range round off the angle and a nearer one does not. + // At -44 degrees the only point along the line turns from it by exactly a degree. At -18 + // degrees the one point along the line lies between whole units on both axes. + let between = Pt { x: u(i32::MAX) - 2.0 * u(1), y: u(i32::MAX) - 1.48 * u(1) }; + // A start a unit and a half and half a unit inside the corner lies on the edges of rounding. + let edges = Pt { x: 608_735.521_559_055_1, y: 608_735.521_842_519_8 }; + let near_corner = [(near(1000.0), -45.0), (near(1.25), -45.0), (near(1.0), -45.0), (near(1.0), -44.0), (between, -18.0), (edges, -45.0)]; + for (at, angle) in inside.into_iter().chain(near_corner) { + let corner = at.x > u(1_000_000); + let d = Drawing { guides: vec![Guideline { at, angle, hidden: false }], ..one_layer(Vec::new()) }; + let riff = riff_of(&write(&d, Limits::default()).unwrap_or_else(|e| panic!("{at:?} {angle}: {e}"))); + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let i32_at = |at: usize| f64::from(i32::from_le_bytes(riff[at..at + 4].try_into().unwrap())); + // The guideline object's `loda` (object type 0x16) and its first argument: 12 bytes, the + // angle in millionths of a degree, then the point and a second point on the line. + let loda = riff.windows(4).enumerate().map(|(p, _)| p).find(|&p| &riff[p..p + 4] == b"loda" && le32(p + 8 + 16) == 0x16).unwrap() + 8; + let arg = loda + le32(loda + le32(loda + 8)); + let a = (i32_at(arg + 12) / 1e6).to_radians(); + let (dx, dy) = (i32_at(arg + 24) - i32_at(arg + 16), i32_at(arg + 28) - i32_at(arg + 20)); + assert!(dx.hypot(dy) > if corner { 0.0 } else { 1000.0 }); + // Off the stored direction by no more than the coordinates' rounding, and, on either + // side, by no more than a degree. + assert!((dx * a.sin() - dy * a.cos()).abs() <= 1.5, "{angle}: {dx} {dy}"); + let turn = (dx * a.sin() - dy * a.cos()).abs().atan2((dx * a.cos() + dy * a.sin()).abs()); + assert!(turn <= 1f64.to_radians() + 1e-12, "{angle}: {dx} {dy}"); + } +} + +#[test] +fn an_outline_record_ends_8_bytes_before_its_chunk_and_its_color_list_at_its_empty_property() { + let spot = Color::Spot { name: "Ink".into(), tint: 1.0, look: Some([0.0; 3]) }; + let o = Outline { width: u(2540), color: spot, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false }; + let outlined = one_layer(vec![Object::Shape(Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o))))]); + let riff = riff_of(&write(&outlined, Limits::default()).unwrap()); + let le32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; + let at = riff.windows(4).position(|w| w == b"outl").unwrap(); + let chunk = &riff[at + 8..at + 8 + le32(&riff, at + 4)]; + // The outline's id, then records (type, length, body) up to the one of type 1. + let mut p = 4; + let mut types = Vec::new(); + loop { + let (kind, len) = (le32(chunk, p), le32(chunk, p + 4)); + types.push(kind); + if kind == 1 { + assert_eq!(len, chunk.len() - p - 8 - 8); + // The body as sample files lay it out (R71): 130 bytes, an f64 1 at bytes 16 and 48, + // 45 degrees at byte 84 and 60 at byte 88. + let body = &chunk[p + 8..p + 8 + len]; + let f64_at = |at: usize| f64::from_le_bytes(body[at..at + 8].try_into().unwrap()); + assert_eq!((len, f64_at(16), f64_at(48), le32(body, 84), le32(body, 88)), (130, 1.0, 1.0, 45_000_000, 60)); + break; + } + // The color property list (type byte, length, body) ends at its first empty property. + if kind == 2 { + let mut q = p + 8; + while chunk[q] != 0 { + q += 5 + le32(chunk, q + 1); + } + assert_eq!((q + 5, le32(chunk, q + 1)), (p + 8 + len, 0)); + } + p += 8 + len; + } + assert_eq!(types, [2, 1]); +} + +#[test] +fn a_transparency_names_a_white_fill_record_of_the_file() { + let mut s = Shape::new(rect_geometry(), Matrix::IDENTITY, Some(Color::Gray(1.0)), None); + s.opacity = 0.5; + let riff = riff_of(&write(&one_layer(vec![Object::Shape(Box::new(s))]), Limits::default()).unwrap()); + let head: Vec = [1300u32, 117].iter().flat_map(|v| v.to_le_bytes()).collect(); + let at = riff.windows(head.len()).position(|w| w == head).unwrap() + head.len(); + let id = &riff[at + 105..at + 109]; + // The `fild` chunk of that id (chunk id, size, record id) holds the RGB color record of white. + let fild = riff.windows(12).position(|w| &w[..4] == b"fild" && &w[8..] == id).unwrap(); + let size = u32::from_le_bytes(riff[fild + 4..fild + 8].try_into().unwrap()) as usize; + let white = [5, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0]; + assert_eq!(count(&riff[fild + 8..fild + 8 + size], &white), 1); +} + +#[test] +fn empty_groups_are_left_out_and_a_container_without_objects_is_a_shape() { + let container = Shape::new(Geometry::Ellipse { w: u(10_000), h: u(10_000) }, Matrix::IDENTITY, None, None); + let objects = vec![ + Object::Group { objects: Vec::new(), flags: Flags::default() }, + Object::Clip { container: Box::new(container.clone()), objects: Vec::new() }, + ]; + let back = read(&write(&one_layer(objects), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers[0].objects, vec![Object::Shape(Box::new(container.clone()))]); + assert!(back.warnings.is_empty()); + // A container whose objects are groups that draw nothing is written as the plain shape is. + let hollow = Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() }; + let clips_hollow = one_layer(vec![Object::Clip { container: Box::new(container.clone()), objects: vec![hollow] }]); + let file = write(&clips_hollow, Limits::default()).unwrap(); + assert_eq!(file, write(&one_layer(vec![Object::Shape(Box::new(container))]), Limits::default()).unwrap()); + // A group that holds only groups that draw nothing is written as no group at all. + assert_eq!(write(&one_layer(vec![hollow_group()]), Limits::default()).unwrap(), write(&one_layer(Vec::new()), Limits::default()).unwrap()); +} + +fn hollow_group() -> Object { + Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() } +} + +#[test] +fn a_drawing_without_pages_is_written_with_one_empty_page() { + let d = Drawing { pages: Vec::new(), ..one_layer(Vec::new()) }; + let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(back.pages.len(), 1); + assert!(back.pages[0].layers.iter().all(|l| l.objects.is_empty())); + // Without a page size of its own, the drawing reads back without one. + assert_eq!(back.page_size, None); +} + +/// At the smallest value of a limit at which the reader reads `d`'s file whole, the writer writes +/// it; one below, the writer refuses it. +fn writes_at_the_readers_limit(d: &Drawing, set: fn(&mut Limits, usize)) -> usize { + let limits = |n| { + let mut l = Limits::default(); + set(&mut l, n); + l + }; + let file = write(d, Limits::default()).unwrap(); + let whole = |n| read(&file, limits(n)).is_ok_and(|b| b.warnings.is_empty()); + // The smallest value that reads whole: a read that fits a limit fits every larger one. + let (mut n, mut above) = (0, 100_000); + while n < above { + let mid = (n + above) / 2; + if whole(mid) { above = mid } else { n = mid + 1 } + } + assert!(whole(n), "{n}"); + assert_eq!(write(d, limits(n)).as_ref(), Ok(&file), "{n}"); + assert!(n > 0 && matches!(write(d, limits(n - 1)), Err(Error::Limit(_))), "{n}"); + n +} + +#[test] +fn every_limit_a_read_applies_is_applied_when_writing() { + let d = everything(); + let set: [fn(&mut Limits, usize); 10] = [ + |l, n| l.input = n, + |l, n| l.inflated = n, + |l, n| l.arguments = n, + |l, n| l.clipped_chunks = n, + |l, n| l.chunks = n, + |l, n| l.member = n, + |l, n| l.dashes = n, + |l, n| l.objects = n, + |l, n| l.coordinates = n, + |l, n| l.members = n, + ]; + for set in set { + writes_at_the_readers_limit(&d, set); + } + // Without clipped groups the outline table ends the file: an empty drawing, and one whose + // last record is an outline. + let o = Outline { + width: u(2540), + color: Color::Gray(0.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let outlined = one_layer(vec![Object::Shape(Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o))))]); + let bytes: [fn(&mut Limits, usize); 3] = [|l, n| l.input = n, |l, n| l.inflated = n, |l, n| l.member = n]; + for d in [one_layer(Vec::new()), outlined] { + for set in bytes { + writes_at_the_readers_limit(&d, set); + } + } + // A group that holds only an empty group is left out, and takes nothing of the object count. + let hollow = + one_layer(vec![Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() }]); + assert!(write(&hollow, Limits { objects: 0, ..Limits::default() }).is_ok()); +} + +#[test] +fn a_path_past_the_coordinate_count_stops_before_its_points_are_written() { + // The closing point's coordinates are past the file's range; the count is refused first. + let mut segments: Vec = (1..10).map(|i| Segment::Line(pt(i * 100, 0))).collect(); + segments.push(Segment::Line(Pt { x: 1e30, y: 0.0 })); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: true }] }; + let d = one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))]); + assert!(matches!(write(&d, Limits::default()), Err(Error::Unwritable(_)))); + assert!(matches!(write(&d, Limits { coordinates: 5, ..Limits::default() }), Err(Error::Limit(_)))); + // A shape takes at least three arguments, counted before its points. + assert_eq!(write(&d, Limits { arguments: 2, ..Limits::default() }), Err(Error::Limit("argument count"))); + // So is the file's size, from the segment count: a long path refused at half its bytes. + let long = |end: Pt| { + let mut segments: Vec = (1..1000).map(|i| Segment::Line(pt(i * 100, i % 2 * 100))).collect(); + segments.push(Segment::Line(end)); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: true }] }; + one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))]) + }; + let member = riff_of(&write(&long(pt(0, 100)), Limits::default()).unwrap()).len() - 1000 * 9 / 2; + assert!(matches!(write(&long(Pt { x: 1e30, y: 0.0 }), Limits::default()), Err(Error::Unwritable(_)))); + assert!(matches!(write(&long(Pt { x: 1e30, y: 0.0 }), Limits { member, ..Limits::default() }), Err(Error::Limit(_)))); + // So are the shape's nested lists: one level short of what a rectangle in its place takes. + let fits = |n| write(&one_layer(vec![rect(100, 100, None)]), Limits { depth: n, ..Limits::default() }).is_ok(); + let depth = (1..64).find(|&n| fits(n)).unwrap(); + assert_eq!(write(&d, Limits { depth: depth - 1, ..Limits::default() }), Err(Error::Limit("nesting depth"))); + // In a clipped group, every other chunk of the file counts too: one chunk short of what the + // drawing takes with a path in range, the clipped path is refused before its points. + let clipped = |path: Path| { + let container = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None); + // A fill of its own, whose record counts as well. + let shape = Shape::new(Geometry::Path(path), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + one_layer(vec![Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(shape))] }]) + }; + let Some(Object::Shape(s)) = d.pages[0].layers[0].objects.first() else { panic!("no path") }; + let Geometry::Path(past) = s.geometry.clone() else { panic!("no path") }; + let mut within = past.clone(); + within.subpaths[0].segments.pop(); + let chunks = (1..1000).find(|&n| write(&clipped(within.clone()), Limits { chunks: n, ..Limits::default() }).is_ok()).unwrap(); + assert!(matches!(write(&clipped(past.clone()), Limits::default()), Err(Error::Unwritable(_)))); + assert_eq!(write(&clipped(past), Limits { chunks: chunks - 1, ..Limits::default() }), Err(Error::Limit("chunk count"))); +} + +#[test] +fn a_rectangle_repeats_the_scale_of_its_transform() { + // Scaled by 2 and 3, then turned a quarter turn: the scale fields hold 2 and 3 (R29). + for m in [Matrix([2.0, 0.0, 0.0, 3.0, 5.0, 7.0]), Matrix([0.0, 2.0, -3.0, 0.0, 5.0, 7.0])] { + let shape = Shape::new(Geometry::Rect { w: u(1000), h: u(2000), radii: [0.0; 4] }, m, None, None); + let riff = riff_of(&write(&one_layer(vec![Object::Shape(Box::new(shape))]), Limits::default()).unwrap()); + // The record's width and height in coordinate units, then the two scale fields. + let units = |v: f64| (v * (254_000.0 / 72.0)).to_le_bytes(); + let fields = [units(u(1000)), units(u(2000)), 2.0f64.to_le_bytes(), 3.0f64.to_le_bytes()].concat(); + assert_eq!(count(&riff, &fields), 1, "{m:?}"); + } +} + +#[test] +fn the_pages_clipped_groups_and_records_share_the_byte_limit() { + // A long path on the page and another in a clipped group each fit the limit; together they do + // not, and writing stops at the second before it reaches the unwritable shape after it. + let long = || { + let segments = (1..4000).map(|i| Segment::Line(pt(i * 100, (i % 7) * 100))).collect(); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: false }] }; + Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None))) + }; + let container = || Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, None)); + let fits = one_layer(vec![long(), Object::Clip { container: container(), objects: vec![long()] }]); + let past = Shape::new(Geometry::Rect { w: 1e30, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None); + let stops = one_layer(vec![long(), Object::Clip { container: container(), objects: vec![long(), Object::Shape(Box::new(past))] }]); + assert!(matches!(write(&stops, Limits::default()), Err(Error::Unwritable(_)))); + let member = riff_of(&write(&fits, Limits::default()).unwrap()).len() - 4000 * 9 / 2; + assert!(matches!(write(&stops, Limits { member, ..Limits::default() }), Err(Error::Limit(_)))); + // Shapes whose fills all differ: the page fits the limit, and the fill table takes it past + // before the writer reaches the unwritable shape at the end of the page. + let shapes = || (0..=255u8).map(|v| rect(1000, 1000, Some(Color::Gray(c(v))))).collect::>(); + let riff = riff_of(&write(&one_layer(shapes()), Limits::default()).unwrap()); + let filt = riff.windows(12).position(|w| &w[..4] == b"LIST" && &w[8..] == b"filt").unwrap(); + let table = u32::from_le_bytes(riff[filt + 4..filt + 8].try_into().unwrap()) as usize; + let member = riff.len() - table / 2; + let past = Shape::new(Geometry::Rect { w: 1e30, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None); + let stops = one_layer(shapes().into_iter().chain([Object::Shape(Box::new(past))]).collect()); + assert!(matches!(write(&stops, Limits::default()), Err(Error::Unwritable(_)))); + assert!(matches!(write(&stops, Limits { member, ..Limits::default() }), Err(Error::Limit(_)))); +} + +#[test] +fn clips_nest_as_deep_as_a_read_takes() { + let nested = |depth: usize| { + let mut o = rect(100, 100, None); + for _ in 0..depth { + let container = Shape::new(Geometry::Ellipse { w: u(1000), h: u(1000) }, Matrix::IDENTITY, None, None); + o = Object::Clip { container: Box::new(container), objects: vec![o] }; + } + one_layer(vec![o]) + }; + let back = read(&write(&nested(64), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(rounded(back), as_read(nested(64))); + assert_eq!(write(&nested(65), Limits::default()), Err(Error::Limit("clip nesting"))); +} + +#[test] +fn ten_dashes_fit_before_the_arrowheads_and_eleven_do_not() { + let dashed = |n: usize| { + let o = Outline { + width: u(2540), + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: (1..=n).map(|d| d as f64).collect(), + behind_fill: false, + scale_with: false, + }; + one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Ellipse { w: u(1000), h: u(1000) }, Matrix::IDENTITY, None, Some(o))))]) + }; + let back = read(&write(&dashed(10), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(rounded(back), as_read(dashed(10))); + assert!(matches!(write(&dashed(11), Limits::default()), Err(Error::Unwritable(_)))); +} + +#[test] +fn names_and_values_the_reader_would_change_are_refused() { + let named = |name: String| Drawing { pages: vec![Page { size: None, layers: vec![layer(&name, Vec::new())] }], ..one_layer(Vec::new()) }; + let back = read(&write(&named("é".repeat(256)), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers[0].name, "é".repeat(256)); + assert!(back.warnings.is_empty()); + for name in ["é".repeat(257), "A\0B".to_string()] { + assert!(matches!(write(&named(name), Limits::default()), Err(Error::Unwritable(_)))); + } + let filled = |c: Color| one_layer(vec![rect(100, 100, Some(c))]); + // At a 10% tint, the stored byte nearest a black look reads back a step off, and the next one + // reads back black. + let black_tint = Color::Spot { name: "Ink".into(), tint: 0.1, look: Some([0.0; 3]) }; + let back = read(&write(&filled(black_tint.clone()), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(rounded(back), rounded(filled(black_tint))); + for c in [ + Color::Rgb([f32::NAN, 0.0, 0.0]), + Color::Gray(1.5), + Color::Spot { name: String::new(), tint: 1.0, look: None }, + Color::Spot { name: "Red".into(), tint: 0.0, look: Some([1.0, 0.0, 0.0]) }, + Color::Spot { name: "Gray".into(), tint: 0.01, look: Some([0.5, 0.5, 0.5]) }, + ] { + assert!(matches!(write(&filled(c), Limits::default()), Err(Error::Unwritable(_)))); + } + // A corner past half the shorter side, a page of no width, a dash past what a u16 holds. + let corner = Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [9.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, None, None); + assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(corner))]), Limits::default()), Err(Error::Unwritable(_)))); + let flat = Drawing { page_size: Some((0.0, 10.0)), ..one_layer(Vec::new()) }; + assert!(matches!(write(&flat, Limits::default()), Err(Error::Unwritable(_)))); + let long = Outline { + width: 1.0, + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: vec![100_000.0], + behind_fill: false, + scale_with: false, + }; + let fine = Outline { dashes: vec![0.4, 0.4], ..long.clone() }; + for o in [long, fine] { + let dashed = Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o)); + assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(dashed))]), Limits::default()), Err(Error::Unwritable(_)))); + } + let mut see_through = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None); + see_through.opacity = f32::NAN; + assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(see_through))]), Limits::default()), Err(Error::Unwritable(_)))); + let mut grid = layer("Grid", vec![rect(100, 100, None)]); + grid.kind = LayerKind::Grid; + assert!(matches!(write(&Drawing { master: vec![grid], ..one_layer(Vec::new()) }, Limits::default()), Err(Error::Unwritable(_)))); +} + +fn rect_geometry() -> Geometry { + Geometry::Rect { w: u(1000), h: u(1000), radii: [0.0; 4] } +} + +#[test] +fn a_grid_layer_keeps_its_lock_state() { + for locked in [false, true] { + let mut grid = layer("Grid", vec![rect(100, 100, None)]); + grid.kind = LayerKind::Grid; + grid.flags.locked = locked; + let d = Drawing { pages: vec![Page { size: None, layers: vec![grid] }], ..one_layer(Vec::new()) }; + let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!((back.pages[0].layers[0].kind, back.pages[0].layers[0].flags.locked), (LayerKind::Grid, locked)); + } +} + +/// A drawing at a limit is written and read whole; one past it is refused. +#[test] +fn drawings_past_what_a_read_takes_are_refused() { + let flat = |n: i32| one_layer((0..n).map(|i| rect(100 + i, 100, None)).collect()); + let limits = Limits { objects: 10, ..Limits::default() }; + let back = read(&write(&flat(10), limits).unwrap(), limits).unwrap(); + assert!(back.warnings.is_empty()); + assert_eq!(write(&flat(11), limits), Err(Error::Limit("object count"))); + // Groups nested in groups: each one takes a list. + let nested = |depth: usize| { + let mut o = rect(100, 100, None); + for _ in 0..depth { + o = Object::Group { objects: vec![o], flags: Flags::default() }; + } + one_layer(vec![o]) + }; + // The smallest depth a read of eight nested groups takes whole is the smallest the writer + // takes, and a ninth group is refused at it. + let depth = writes_at_the_readers_limit(&nested(8), |l, n| l.depth = n); + assert_eq!(write(&nested(9), Limits { depth, ..Limits::default() }), Err(Error::Limit("nesting depth"))); + let limits = Limits { depth: 12, ..Limits::default() }; + // Groups that hold nothing are refused past the depth too, in a layer and in a clip. + let hollow = |depth: usize| { + let mut o = Object::Group { objects: Vec::new(), flags: Flags::default() }; + for _ in 0..depth { + o = Object::Group { objects: vec![o], flags: Flags::default() }; + } + o + }; + // `hollow(n)` is n + 1 groups deep. + let clip = |o| Object::Clip { container: Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, None)), objects: vec![o] }; + for wrap in [|o| o, clip] { + assert!(write(&one_layer(vec![wrap(hollow(11))]), limits).is_ok()); + assert_eq!(write(&one_layer(vec![wrap(hollow(12))]), limits), Err(Error::Limit("nesting depth"))); + } + let limits = Limits { coordinates: 3, ..Limits::default() }; + let line = |n: i32| { + let segments = (1..n).map(|i| Segment::Line(pt(i, i))).collect(); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: false }] }; + one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))]) + }; + assert!(read(&write(&line(3), limits).unwrap(), limits).unwrap().warnings.is_empty()); + assert_eq!(write(&line(4), limits), Err(Error::Limit("coordinate count"))); +} + +#[test] +fn numbers_the_file_cant_hold_are_refused() { + let with = |s: Shape| one_layer(vec![Object::Shape(Box::new(s))]); + let far = Shape::new(Geometry::Ellipse { w: 1e9, h: 1.0 }, Matrix::IDENTITY, None, None); + assert!(matches!(write(&with(far), Limits::default()), Err(Error::Unwritable(_)))); + let nan = Shape::new(Geometry::Rect { w: f64::NAN, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None); + assert!(matches!(write(&with(nan), Limits::default()), Err(Error::Unwritable(_)))); + let inf = Shape::new(Geometry::Ellipse { w: 1.0, h: 1.0 }, Matrix([f64::INFINITY, 0.0, 0.0, 1.0, 0.0, 0.0]), None, None); + assert!(matches!(write(&with(inf), Limits::default()), Err(Error::Unwritable(_)))); +} + +#[test] +fn values_outside_their_range_are_refused() { + let with = |s: Shape| one_layer(vec![Object::Shape(Box::new(s))]); + let outlined = |width: f64| Outline { + width, + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let mut opaque = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None); + opaque.opacity = 1.5; + let far = Path { subpaths: vec![SubPath { start: Pt { x: 1e9, y: 0.0 }, segments: vec![Segment::Line(pt(0, 0))], closed: false }] }; + let cases = [ + ("negative outline width", with(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(outlined(-1.0))))), + // A width of 0 reads back as no width. + ("positive outline width that rounds to 0", with(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(outlined(u(1) / 4.0))))), + ("negative corner radius", with(Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [-1.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, None, None))), + ("opacity past 1", with(opaque)), + ("tint past 1", one_layer(vec![rect(100, 100, Some(Color::Spot { name: "Red".into(), tint: 1.5, look: Some([1.0, 1.0, 1.0]) }))])), + ("path point past 32 bits", with(Shape::new(Geometry::Path(far), Matrix::IDENTITY, None, None))), + ("page size past 32 bits", Drawing { page_size: Some((1e9, 10.0)), ..one_layer(Vec::new()) }), + ]; + let written: Vec<_> = + cases.iter().filter(|(_, d)| !matches!(write(d, Limits::default()), Err(Error::Unwritable(_)))).map(|(what, _)| *what).collect(); + assert!(written.is_empty(), "{written:?}"); +} + +fn arb_color() -> impl Strategy { + prop_oneof![ + any::<[u8; 3]>().prop_map(|v| Color::Rgb(v.map(c))), + any::<[u8; 4]>().prop_map(|v| Color::Cmyk(v.map(c))), + any::().prop_map(|v| Color::Gray(c(v))), + Just(Color::Registration), + ] +} + +fn arb_shape() -> impl Strategy { + let size = || (-1_000_000i32..1_000_000, -1_000_000i32..1_000_000); + let geometry = prop_oneof![ + size().prop_map(|(w, h)| Geometry::Rect { w: u(w), h: u(h), radii: [0.0; 4] }), + size().prop_map(|(w, h)| Geometry::Ellipse { w: u(w), h: u(h) }), + (prop::collection::vec(size(), 1..20), any::()).prop_map(|(pts, closed)| { + let segments = pts.iter().map(|&(x, y)| Segment::Line(pt(x, y))).collect(); + Geometry::Path(Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed }] }) + }), + ]; + (geometry, prop::option::of(arb_color()), any::(), -500i32..500) + .prop_map(|(g, fill, nonzero, x)| Shape { nonzero, ..Shape::new(g, moved(f64::from(x), -f64::from(x)), fill, None) }) +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })] + + #[test] + fn random_drawings_read_back_as_written(shapes in prop::collection::vec(arb_shape(), 0..30), grouped in 0usize..30) { + let mut objects: Vec = shapes.into_iter().map(|s| Object::Shape(Box::new(s))).collect(); + let tail = objects.split_off(grouped.min(objects.len())); + if !tail.is_empty() { + objects.push(Object::Group { objects: tail, flags: Flags::default() }); + } + let d = Drawing { page_size: Some((u(1_000_000), u(1_000_000))), ..one_layer(objects) }; + let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap(); + prop_assert!(back.warnings.is_empty()); + prop_assert_eq!(rounded(back), as_read(d)); + } + + #[test] + fn writing_never_panics( + w in prop_oneof![-1e4..1e4f64, any::()], + h in prop_oneof![-1e4..1e4f64, any::()], + m in prop_oneof![prop::array::uniform6(-1e3..1e3f64), any::<[f64; 6]>()], + dashes in prop::collection::vec(prop_oneof![-1.0..20.0f64, any::()], 0..12), + opacity in prop_oneof![-0.5..1.5f32, any::()], + ) { + let outline = + Outline { width: w, color: Color::Gray(opacity), cap: Cap::Square, join: Join::Round, dashes, behind_fill: false, scale_with: false }; + // Corners within half the shorter side, so a rectangle of a size the file holds is written. + let r = w.abs().min(h.abs()) / 4.0; + let mut s = Shape::new(Geometry::Rect { w, h, radii: [r, 0.0, r, 0.0] }, Matrix(m), Some(Color::Rgb([opacity; 3])), Some(outline)); + s.opacity = opacity; + let d = Drawing { pages: vec![Page { size: Some((w, h)), layers: vec![layer("A", vec![Object::Shape(Box::new(s))])] }], ..everything() }; + if let Ok(file) = write(&d, Limits::default()) { + prop_assert!(read(&file, Limits::default()).is_ok()); + } + } +} diff --git a/crates/cloud-local/README.md b/crates/cloud-local/README.md index a5006c2ca3..a3c8d53c9e 100644 --- a/crates/cloud-local/README.md +++ b/crates/cloud-local/README.md @@ -37,3 +37,16 @@ write never truncates its target in place. It writes a new sibling file and rena over the target, so the target's directory entry is replaced rather than its bytes being overwritten. A rename only ever changes one name; it does not reach through to any other name, inside the root or out, that happens to point at the same inode. + +## Concurrent saves + +A `Job::Write` checks the file's etag again just before the rename, and holds one lock for this +process from that check until the rename is done. Within one process, when two saves are made +from the same etag, the second gets `Fault::Conflict`, unless the first save left the file with an +unchanged etag (see the next paragraph). A second process writing the same folder does not take +that lock, so its save can still land between the check and the rename. A deployment that needs +the guarantee across processes needs a backend whose provider offers a conditional write. + +The etag is the file's length and modification time. On a filesystem whose timestamps are coarser +than the time between two saves, two saves of the same length can leave the same etag, and the +second save is then not refused. diff --git a/crates/cloud-local/src/lib.rs b/crates/cloud-local/src/lib.rs index 715a870842..5fca54f9b7 100644 --- a/crates/cloud-local/src/lib.rs +++ b/crates/cloud-local/src/lib.rs @@ -62,6 +62,7 @@ use std::ffi::OsStr; use std::fs; use std::io::{Read as _, Write as _}; use std::path::{Component, Path, PathBuf}; +use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use cap_std::fs::{Dir, OpenOptions}; @@ -208,8 +209,9 @@ fn is_windows_reserved_name(name: &str) -> bool { /// outright first, because a Unix build's [`Component`] parser does not /// treat either as a separator and would wave a Windows drive letter or UNC /// prefix (`C:`, `\\server\share`) straight through as one ordinary name. A -/// Windows reserved device name is refused the same way. None of this costs -/// anything here, unlike applying it to a name `list` merely discovered. +/// Windows reserved device name is refused the same way, and so is a name +/// [`is_temp_name`] matches, which [`list`] would leave out. None of this +/// costs anything here, unlike applying it to a name `list` merely discovered. fn confine_name(name: &str) -> Result<&str, Fault> { if name.contains('\\') || name.contains(':') { return Err(Fault::Refused(format!("{name} is not a plain file name"))); @@ -217,6 +219,9 @@ fn confine_name(name: &str) -> Result<&str, Fault> { if is_windows_reserved_name(name) { return Err(Fault::Refused(format!("{name} is a reserved device name on Windows"))); } + if is_temp_name(name) { + return Err(Fault::Refused(format!("{name} is a name this backend uses for its temporary files"))); + } confine_segment(name) } @@ -252,6 +257,13 @@ fn io_fault(error: &std::io::Error) -> Fault { } } +/// Lists the files and folders in `path`. +/// +/// A regular file whose name [`is_temp_name`] matches is left out before its +/// metadata is read. Such a file is a save in progress, or one that was +/// stopped between its create and its rename, and it is not a document. +/// [`confine_name`] refuses these names for a new file. A folder or a link +/// with such a name is listed. fn list(root: &Path, path: &str) -> Result, Fault> { let rel = relative(path)?; let dir = open_root(root)?; @@ -260,8 +272,11 @@ fn list(root: &Path, path: &str) -> Result, Fault> { let mut entries = Vec::new(); for item in read { let item = item.map_err(|error| io_fault(&error))?; - let meta = item.metadata().map_err(|error| io_fault(&error))?; let name = item.file_name().to_string_lossy().into_owned(); + if is_temp_name(&name) && item.file_type().is_ok_and(|kind| kind.is_file()) { + continue; + } + let meta = item.metadata().map_err(|error| io_fault(&error))?; let id = child_path(path, &name); entries.push(Entry { room: format!("local:{id}"), @@ -322,64 +337,154 @@ fn read(root: &Path, entry: &Entry) -> Result<(Entry, Vec), Fault> { /// so a hard link sharing the target's inode keeps its own, unmodified copy: /// the rename replaces `entry.id`'s directory entry, and never reaches /// through to any other name pointing at the same inode. +/// +/// The etag is checked once before any bytes are written, and again under +/// [`WRITE_LOCK`] just before the rename. Two saves made from the same etag +/// at once otherwise both pass the check before either renames, both report +/// success, and the later rename replaces the first save without a +/// [`Fault::Conflict`]. fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result { let rel = relative(&entry.id)?; let dir = open_root(root)?; - match dir.symlink_metadata(&rel) { - Ok(meta) if meta.is_symlink() => return Err(Fault::Refused("that path is a link, not a plain file".to_owned())), - Ok(meta) => { - if Some(etag_of(&meta)) != entry.etag { - return Err(Fault::Conflict); - } - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(io_fault(&error)), - } + check_unchanged(&dir, &rel, entry)?; if let Some(parent) = rel.parent() { dir.create_dir_all(parent).map_err(|error| io_fault(&error))?; } - write_replacing(&dir, &rel, bytes)?; - let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?; + let meta = write_replacing(&dir, &rel, bytes, || check_unchanged(&dir, &rel, entry))?; Ok(Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() }) } +/// Refuses a link at `rel`, and a file whose etag is no longer `entry.etag`. +/// A file that does not exist passes. +fn check_unchanged(dir: &Dir, rel: &Path, entry: &Entry) -> Result<(), Fault> { + match dir.symlink_metadata(rel) { + Ok(meta) if meta.is_symlink() => Err(Fault::Refused("that path is a link, not a plain file".to_owned())), + Ok(meta) if Some(etag_of(&meta)) != entry.etag => Err(Fault::Conflict), + Ok(_) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(io_fault(&error)), + } +} + +/// Held by [`write_replacing`] from its last check until the rename is done +/// and the new file's metadata is read, and by [`create_in_place`] from the +/// moment it creates its file until the file is complete or removed. No other +/// save in this process can change the file between a save's check and its +/// rename, a save cannot replace a file that `create_in_place` is still +/// writing, and `create_in_place` cannot remove a replacement when its own +/// write fails. The temporary file is written and synced before the lock is +/// taken, so a slow save does not hold up the others. Another process writing +/// the same folder is not covered. +static WRITE_LOCK: Mutex<()> = Mutex::new(()); + /// The next in a run of sibling temporary names, unique within this process. /// Not meant to resist a second process picking the same name; the create -/// this writes with is exclusive (`create_new`), so a collision there is -/// just retried under a new counter value rather than silently overwritten. +/// [`open_temp`] does is exclusive (`create_new`), so a collision there is +/// retried under a new counter value rather than silently overwritten. static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); +/// How many temporary names [`open_temp`] tries before it gives up. +const TEMP_ATTEMPTS: usize = 16; + +/// The start of every name [`temp_name`] makes. +const TEMP_PREFIX: &str = ".craft-save-"; + +/// The end of every name [`temp_name`] makes. +const TEMP_SUFFIX: &str = ".tmp"; + +/// The temporary name for process `pid`, clock part `started` and sequence +/// value `n`. [`is_temp_name`] matches every name this returns. +fn temp_name(pid: u32, started: u128, n: u64) -> String { + format!("{TEMP_PREFIX}{pid}-{started:x}-{n}{TEMP_SUFFIX}") +} + +/// Whether [`temp_name`] returns exactly `name` for some process id, clock +/// part and sequence value. The three parts are read back from `name` and +/// passed to `temp_name`, so a name the two would format differently (a +/// leading zero, an uppercase hexadecimal digit, a sign) does not match. +/// [`list`] leaves these names out. A name with only the same prefix and +/// suffix, such as `.craft-save-notes.tmp`, does not match and is listed. +fn is_temp_name(name: &str) -> bool { + let Some(middle) = name.strip_prefix(TEMP_PREFIX).and_then(|rest| rest.strip_suffix(TEMP_SUFFIX)) else { + return false; + }; + let mut parts = middle.split('-'); + let (Some(pid), Some(started), Some(n), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { + return false; + }; + match (pid.parse::(), u128::from_str_radix(started, 16), n.parse::()) { + (Ok(pid), Ok(started), Ok(n)) => temp_name(pid, started, n) == name, + _ => false, + } +} + +/// Creates a new hidden temporary file beside `rel`, named from +/// [`TEMP_SEQUENCE`], and returns its path and handle. A name that already +/// exists (a file another process or an earlier run left) is skipped for the +/// next one, and never opened or removed. The name does not include `rel`'s +/// file name, so a file name near the filesystem's length limit still gets a +/// temporary name that fits. +fn open_temp(dir: &Dir, rel: &Path) -> Result<(PathBuf, cap_std::fs::File), Fault> { + if rel.file_name().is_none() { + return Err(Fault::Refused("that path names no file".to_owned())); + } + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + // The clock part keeps a stale file from an earlier run with the same + // process id from matching a run of names, so needing all the attempts + // takes 16 files made for this exact moment. + let started = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_nanos()); + #[cfg(test)] + let started = if tests::FIXED_TEMP_CLOCK.with(std::cell::Cell::get) { 0 } else { started }; + let mut last = None; + for _ in 0..TEMP_ATTEMPTS { + let temp_name = temp_name(std::process::id(), started, TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed)); + let temp_rel = match rel.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent.join(&temp_name), + _ => PathBuf::from(&temp_name), + }; + match dir.open_with(&temp_rel, &options) { + Ok(handle) => return Ok((temp_rel, handle)), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => last = Some(error), + Err(error) => return Err(io_fault(&error)), + } + } + Err(last.map_or_else(|| Fault::Unreachable("no temporary name was free".to_owned()), |error| io_fault(&error))) +} + /// Writes `bytes` to a new sibling of `rel` inside `dir`, then renames that /// sibling over `rel`. See the module docs for why: a direct write would /// truncate whatever `rel` currently names in place, and if that happens to /// be a hard link to a file outside `root`, the outside copy would be /// corrupted along with it. A rename only ever replaces `rel`'s own /// directory entry. -fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8]) -> Result<(), Fault> { - let name = rel.file_name().ok_or_else(|| Fault::Refused("that path names no file".to_owned()))?; - let mut temp_name = OsStr::new(".").to_os_string(); - temp_name.push(name); - temp_name.push(format!(".tmp-{}-{}", std::process::id(), TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed))); - let temp_rel = match rel.parent() { - Some(parent) if !parent.as_os_str().is_empty() => parent.join(&temp_name), - _ => PathBuf::from(&temp_name), - }; - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - let written = (|| -> Result<(), Fault> { - let mut handle = dir.open_with(&temp_rel, &options).map_err(|error| io_fault(&error))?; - handle.write_all(bytes).map_err(|error| io_fault(&error))?; - handle.sync_all().map_err(|error| io_fault(&error)) - })(); +/// +/// `check` runs under [`WRITE_LOCK`] right before the rename; when it fails, +/// the temporary file is removed and `rel` is left as it was. Returns the +/// metadata of the file just published. +fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8], check: impl FnOnce() -> Result<(), Fault>) -> Result { + let (temp_rel, mut handle) = open_temp(dir, rel)?; + let written = handle.write_all(bytes).map_err(|error| io_fault(&error)).and_then(|()| handle.sync_all().map_err(|error| io_fault(&error))); + drop(handle); if let Err(fault) = written { let _ = dir.remove_file(&temp_rel); return Err(fault); } - if let Err(error) = dir.rename(&temp_rel, dir, rel) { + #[cfg(test)] + tests::before_lock(); + let published = { + let _serialized = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + check().and_then(|()| { + #[cfg(test)] + tests::after_check(); + dir.rename(&temp_rel, dir, rel).map_err(|error| io_fault(&error))?; + dir.metadata(rel).map_err(|error| io_fault(&error)) + }) + }; + if published.is_err() { let _ = dir.remove_file(&temp_rel); - return Err(io_fault(&error)); } - Ok(()) + published } fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result { @@ -397,24 +502,46 @@ fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result handle, - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { - return Err(Fault::Refused(format!("{name} already exists"))); - } + // A taken name is refused before any bytes are written. The hard link + // below is still the check that settles a race. + match dir.symlink_metadata(&rel) { + Ok(_) => return Err(Fault::Refused(format!("{name} already exists"))), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(io_fault(&error)), - }; - handle.write_all(bytes).map_err(|error| io_fault(&error))?; + } + // The bytes go to a sibling temporary file first. A write that fails part + // way (a full disk, a lost share) leaves only that file, which is removed, + // so the name stays free for the next Save As instead of holding a partial + // file that makes it fail with "already exists". + let (temp_rel, mut handle) = open_temp(&dir, &rel)?; + let written = write_new(&mut handle, bytes).and_then(|()| sync_new(&handle)); drop(handle); + if let Err(fault) = written { + let _ = dir.remove_file(&temp_rel); + return Err(fault); + } + // The finished file takes `name` with a hard link, not an `exists` check + // ahead of a rename: two creates of the same name racing both see "not + // there yet" otherwise, and the second silently replaces the first. A link + // fails when the name is taken, so the loser gets an error instead of a + // chance to overwrite the winner. It also fails when `name` already exists + // as a symlink, dangling or not. + #[cfg(not(test))] + let linked = dir.hard_link(&temp_rel, &dir, &rel); + #[cfg(test)] + let linked = if tests::NO_HARD_LINKS.with(std::cell::Cell::get) { + Err(std::io::Error::other("no hard links")) + } else { + dir.hard_link(&temp_rel, &dir, &rel) + }; + let _ = dir.remove_file(&temp_rel); + match linked { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Err(Fault::Refused(format!("{name} already exists"))), + // A filesystem without hard links (FAT, some network shares): the + // temporary copy is gone by now, and the file is created in place. + Err(_) => create_in_place(&dir, &rel, name, bytes)?, + } let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?; let id = child_path(folder, name); Ok(Entry { @@ -432,9 +559,314 @@ fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result Result<(), Fault> { + let _writing = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut create_options = OpenOptions::new(); + create_options.write(true).create_new(true); + let mut handle = match dir.open_with(rel, &create_options) { + Ok(handle) => handle, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Err(Fault::Refused(format!("{name} already exists"))), + Err(error) => return Err(io_fault(&error)), + }; + let written = write_new(&mut handle, bytes).and_then(|()| sync_new(&handle)); + drop(handle); + #[cfg(test)] + tests::in_place_finished(); + if written.is_err() { + let _ = dir.remove_file(rel); + } + written +} + +/// Syncs a file [`create`] is making. +fn sync_new(handle: &cap_std::fs::File) -> Result<(), Fault> { + #[cfg(test)] + if tests::FAIL_CREATE_SYNC.with(|countdown| { + let left = countdown.get(); + countdown.set(left.saturating_sub(1)); + left == 1 + }) { + return Err(Fault::Unreachable("no space left on device".to_owned())); + } + handle.sync_all().map_err(|error| io_fault(&error)) +} + +/// Writes the bytes of a file [`create`] is making. +fn write_new(handle: &mut cap_std::fs::File, bytes: &[u8]) -> Result<(), Fault> { + #[cfg(test)] + if tests::FAIL_CREATE_WRITE.with(|countdown| { + let left = countdown.get(); + countdown.set(left.saturating_sub(1)); + left == 1 + }) { + let half = bytes.get(..bytes.len() / 2).unwrap_or_default(); + handle.write_all(half).map_err(|error| io_fault(&error))?; + return Err(Fault::Unreachable("no space left on device".to_owned())); + } + handle.write_all(bytes).map_err(|error| io_fault(&error)) +} + #[cfg(test)] mod tests { use super::*; + use std::sync::mpsc; + + /// Run once by the next [`write`] to pass its etag check, then cleared. + type Hook = Box; + static AFTER_CHECK: Mutex> = Mutex::new(None); + + pub(super) fn after_check() { + let hook = AFTER_CHECK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(hook) = hook { + hook(); + } + } + + /// Run once by the next [`write_replacing`] to finish its temporary file, + /// before it takes [`WRITE_LOCK`], then cleared. + static BEFORE_LOCK: Mutex> = Mutex::new(None); + + pub(super) fn before_lock() { + let hook = BEFORE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(hook) = hook { + hook(); + } + } + + fn entry_for(id: &str) -> Entry { + Entry { + room: format!("local:{id}"), + name: id.trim_start_matches('/').to_owned(), + kind: EntryKind::File, + size: None, + modified: None, + mime: None, + etag: None, + writable: true, + shared_by: None, + path: id.to_owned(), + id: id.to_owned(), + } + } + + #[test] + fn two_saves_from_one_etag_cannot_both_pass_the_check() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("Note.txt"), b"original").unwrap(); + let (read_entry, _) = read(root.path(), &entry_for("/Note.txt")).unwrap(); + + let (checked_tx, checked_rx) = mpsc::channel::<()>(); + let (go_tx, go_rx) = mpsc::channel::<()>(); + *AFTER_CHECK.lock().unwrap() = Some(Box::new(move || { + checked_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + })); + + let first = { + let (root, entry) = (root.path().to_owned(), read_entry.clone()); + std::thread::spawn(move || write(&root, &entry, b"first save")) + }; + checked_rx.recv().unwrap(); + // The first save has passed its check and not yet renamed. A second + // save must not be able to reach its own check in between. + assert!(WRITE_LOCK.try_lock().is_err(), "the check and the rename must run under one lock"); + // The second save passes its early check and writes its temporary + // file before the first one renames, so only the recheck under the + // lock can refuse it. + let (ready_tx, ready_rx) = mpsc::channel::<()>(); + *BEFORE_LOCK.lock().unwrap() = Some(Box::new(move || ready_tx.send(()).unwrap())); + let second = { + let (root, entry) = (root.path().to_owned(), read_entry.clone()); + std::thread::spawn(move || write(&root, &entry, b"second save")) + }; + ready_rx.recv().unwrap(); + go_tx.send(()).unwrap(); + + assert!(first.join().unwrap().is_ok()); + assert!(matches!(second.join().unwrap(), Err(Fault::Conflict)), "the second save started from a stale etag"); + assert_eq!(std::fs::read(root.path().join("Note.txt")).unwrap(), b"first save"); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Note.txt"], "the refused save's temporary file is removed"); + } + + thread_local! { + /// When set to n, the nth [`write_new`] call on this thread from now + /// writes half its bytes and fails. 0 turns it off. + pub(super) static FAIL_CREATE_WRITE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Makes [`create`] on this thread take the path for a filesystem + /// without hard links. + pub(super) static NO_HARD_LINKS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Makes [`open_temp`] on this thread use 0 for its clock part. + pub(super) static FIXED_TEMP_CLOCK: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// When set to n, the nth [`sync_new`] call on this thread from now + /// fails. 0 turns it off. + pub(super) static FAIL_CREATE_SYNC: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Run once by [`create_in_place`] on this thread after its write and + /// sync, before it removes a failed file. + static IN_PLACE_FINISHED: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + } + + pub(super) fn in_place_finished() { + if let Some(hook) = IN_PLACE_FINISHED.with(|hook| hook.borrow_mut().take()) { + hook(); + } + } + + #[test] + fn without_hard_links_a_failed_sync_leaves_no_file_and_keeps_a_concurrent_save() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + let path = root.path().to_path_buf(); + let held = std::rc::Rc::new(std::cell::Cell::new(false)); + let saver = std::rc::Rc::new(std::cell::RefCell::new(None)); + let (seen_held, seen_saver) = (held.clone(), saver.clone()); + IN_PLACE_FINISHED.with(|hook| { + *hook.borrow_mut() = Some(Box::new(move || { + seen_held.set(WRITE_LOCK.try_lock().is_err()); + // A save of the same name starts while the failed file is + // still there. It must not land before that file is removed. + *seen_saver.borrow_mut() = Some(std::thread::spawn(move || { + let dir = open_root(&path).unwrap(); + write_replacing(&dir, Path::new("Minutes.txt"), b"saved meanwhile", || Ok(())) + })); + })); + }); + NO_HARD_LINKS.with(|off| off.set(true)); + // The temporary copy syncs, then the in-place file's sync fails. + FAIL_CREATE_SYNC.with(|fail| fail.set(2)); + let failed = create(root.path(), "", "Minutes.txt", b"the whole document"); + FAIL_CREATE_SYNC.with(|fail| fail.set(0)); + NO_HARD_LINKS.with(|off| off.set(false)); + + assert!(matches!(failed, Err(Fault::Unreachable(_))), "a failed sync is a failed create: {failed:?}"); + assert!(held.get(), "the in-place file is written and removed under the write lock"); + let saver = saver.borrow_mut().take().unwrap(); + saver.join().unwrap().unwrap(); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Minutes.txt"]); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"saved meanwhile", "the removal took only the failed file"); + } + + /// Held by the tests that make temporary files, so the next value of + /// [`TEMP_SEQUENCE`] is known to the test that reads it. + static TEMP_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + #[test] + fn a_stale_temporary_file_is_skipped_and_kept() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + let next = TEMP_SEQUENCE.load(Ordering::Relaxed); + let stale: Vec<_> = (next..next + 3).map(|n| temp_name(std::process::id(), 0, n)).collect(); + for name in &stale { + std::fs::write(root.path().join(name), b"left by an earlier run").unwrap(); + } + FIXED_TEMP_CLOCK.with(|fixed| fixed.set(true)); + let made = create(root.path(), "", "Minutes.txt", b"minutes"); + FIXED_TEMP_CLOCK.with(|fixed| fixed.set(false)); + made.unwrap(); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"minutes"); + for name in &stale { + assert_eq!(std::fs::read(root.path().join(name)).unwrap(), b"left by an earlier run", "{name} is not this call's file"); + } + } + + #[test] + fn a_listing_leaves_out_a_temporary_file_a_stopped_save_left() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + std::fs::create_dir(root.path().join("Archive")).unwrap(); + std::fs::write(root.path().join("Minutes.txt"), b"minutes").unwrap(); + std::fs::write(root.path().join(".craft-save-notes.tmp"), b"a person's own file").unwrap(); + let folder = temp_name(1, 2, 3); + std::fs::create_dir(root.path().join(&folder)).unwrap(); + let dir = open_root(root.path()).unwrap(); + // A save stopped after its create and before its rename leaves the + // temporary file, at the root and inside a folder. + let (at_root, handle) = open_temp(&dir, Path::new("Minutes.txt")).unwrap(); + drop(handle); + let (in_folder, handle) = open_temp(&dir, &Path::new("Archive").join("Agenda.txt")).unwrap(); + drop(handle); + assert!(root.path().join(&at_root).exists() && root.path().join(&in_folder).exists()); + + let names: Vec<_> = list(root.path(), "").unwrap().into_iter().map(|entry| entry.name).collect(); + assert_eq!(names, [".craft-save-1-2-3.tmp", "Archive", ".craft-save-notes.tmp", "Minutes.txt"], "a folder with the pattern stays listed"); + assert!(list(root.path(), "/Archive").unwrap().is_empty()); + } + + #[test] + fn a_create_refuses_a_name_a_listing_would_leave_out() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + let name = temp_name(1, 2, 3); + assert!(matches!(create(root.path(), "", &name, b"bytes"), Err(Fault::Refused(_)))); + assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0); + create(root.path(), "", ".craft-save-notes.tmp", b"bytes").unwrap(); + } + + #[test] + fn is_temp_name_matches_only_the_names_temp_name_makes() { + assert!(is_temp_name(&temp_name(4242, 0x1a2b, 7))); + assert!(is_temp_name(&temp_name(u32::MAX, u128::MAX, u64::MAX))); + for other in [ + ".craft-save-notes.tmp", + ".craft-save-1-2.tmp", + ".craft-save-1-2-3-4.tmp", + ".craft-save--2-3.tmp", + ".craft-save-1-xy-3.tmp", + "craft-save-1-2-3.tmp", + ".craft-save-1-2-3.tmp.txt", + ".craft-save-01-2-3.tmp", + ".craft-save-1-2A-3.tmp", + ".craft-save-+1-2-3.tmp", + ] { + assert!(!is_temp_name(other), "{other} is not a temporary name"); + } + } + + #[test] + fn without_hard_links_a_create_still_refuses_a_taken_name_and_cleans_up() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + NO_HARD_LINKS.with(|off| off.set(true)); + let made = create(root.path(), "", "Minutes.txt", b"first"); + let taken = create(root.path(), "", "Minutes.txt", b"second"); + // The temporary copy is written, then the in-place write fails. + FAIL_CREATE_WRITE.with(|fail| fail.set(2)); + let failed = create(root.path(), "", "Agenda.txt", b"the whole agenda"); + FAIL_CREATE_WRITE.with(|fail| fail.set(0)); + NO_HARD_LINKS.with(|off| off.set(false)); + + assert_eq!(made.unwrap().size, Some(5)); + assert!(matches!(taken, Err(Fault::Refused(_)))); + assert!(matches!(failed, Err(Fault::Unreachable(_)))); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Minutes.txt"], "only the finished file is left"); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"first"); + } + + #[test] + fn a_create_whose_write_fails_leaves_no_file_behind() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + FAIL_CREATE_WRITE.with(|fail| fail.set(1)); + let failed = create(root.path(), "", "Minutes.txt", b"the whole document"); + FAIL_CREATE_WRITE.with(|fail| fail.set(0)); + assert!(matches!(failed, Err(Fault::Unreachable(_)))); + assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0, "no partial or temporary file is left"); + + let retried = create(root.path(), "", "Minutes.txt", b"the whole document").unwrap(); + assert_eq!(retried.size, Some(18)); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"the whole document"); + } #[test] fn a_parent_segment_cannot_walk_out_of_root() { diff --git a/crates/cloud-ui/src/cloud/backend.rs b/crates/cloud-ui/src/cloud/backend.rs index f92328cef2..d5479f3397 100644 --- a/crates/cloud-ui/src/cloud/backend.rs +++ b/crates/cloud-ui/src/cloud/backend.rs @@ -70,6 +70,9 @@ pub enum Event { }, } +/// An answer with the account generation its job was issued in. +pub(crate) type Stamped = (u64, Event); + /// Where a worker's answers go. /// /// Handed to [`CloudBackend::submit`] with the job it belongs to. A worker is @@ -77,7 +80,10 @@ pub enum Event { /// sign-in reports the URL it wants a browser pointed at and then reports that /// the user finished there. A send after the window closed is not a failure. pub struct Post { - tx: Sender, + /// Each event goes with the generation its job was issued in, so + /// [`super::pump`] can drop one that waited in the channel across a + /// sign-out or a new sign-in. + tx: Sender, /// The window's account generation as of the moment the job this answers /// was issued, beside a handle to what it is now. A sign-out or a new /// sign-in bumps the live value; a reply that arrives after is for a @@ -87,7 +93,7 @@ pub struct Post { } impl Post { - pub(crate) fn new(tx: Sender, generation: Arc) -> Post { + pub(crate) fn new(tx: Sender, generation: Arc) -> Post { let issued = generation.load(Ordering::Relaxed); Post { tx, generation, issued } } @@ -99,16 +105,19 @@ impl Post { Post { tx: self.tx.clone(), generation: self.generation.clone(), issued: self.issued } } - /// Delivers the event, unless the window has signed out or signed in - /// again since the job this answers was issued. Silently dropping it - /// there, rather than delivering it, is what keeps a late reply from - /// restoring the previous session's account, files or busy state on top - /// of whatever replaced it. + /// Queues the event with the generation its job was issued in. + /// + /// [`super::pump`] holds the check that keeps a late reply from restoring + /// the previous session's account, files or busy state on top of whatever + /// replaced it: it drops every event whose generation is not the current + /// one, including an event sent here just before a sign-out or a new + /// sign-in. This method only skips the send when the generation has + /// already moved on, so an answer that `pump` would drop is not queued. pub fn send(&self, event: Event) { if self.generation.load(Ordering::Relaxed) != self.issued { return; } - let _ = self.tx.send(event); + let _ = self.tx.send((self.issued, event)); } } diff --git a/crates/cloud-ui/src/cloud/conflict_tests.rs b/crates/cloud-ui/src/cloud/conflict_tests.rs index 1e22e815fe..03b6257ed8 100644 --- a/crates/cloud-ui/src/cloud/conflict_tests.rs +++ b/crates/cloud-ui/src/cloud/conflict_tests.rs @@ -214,6 +214,53 @@ fn sign_out_recovers_save_after_a_backend_job_never_replies() { assert!(saved.is_ok(), "after sign-out and sign-in, Save is still refused: {saved:?}; busy={:?}", app.cloud.busy.as_ref().map(Busy::text)); } +/// While a sign-in waits on the browser, the previous account may still be the one the service +/// answers for. No folder is listed until the sign-in answers, and then both are listed again, +/// so a listing from before the sign-in does not stay on screen as the new account's files. +#[test] +fn folders_are_listed_again_only_after_a_sign_in_answers() { + let (mut app, held, _log) = two_tabs(); + let ctx = egui::Context::default(); + start(&mut app); + held.take(|j| matches!(j, Job::Account)).unwrap().1.send(Event::Account(Ok(account("Ada")))); + held.take(|j| matches!(j, Job::List(_))).unwrap().1.send(Event::Listed { path: String::new(), entries: Ok(vec![entry("/Ada.note", "a1")]) }); + drain(&mut app, &ctx); + assert!(app.cloud.mine.loaded); + + sign_in(&mut app); + start(&mut app); + drain(&mut app, &ctx); + assert!(held.take(|j| matches!(j, Job::List(_))).is_none(), "a folder is listed before the sign-in says who is signed in"); + assert!(report(&app)["entries"].as_array().is_some_and(Vec::is_empty), "the previous account's files stay on screen during sign-in"); + + held.take(|j| matches!(j, Job::SignIn)).unwrap().1.send(Event::Account(Ok(account("Grace")))); + drain(&mut app, &ctx); + assert!(!app.cloud.mine.loading && !app.cloud.mine.loaded && !app.cloud.shared.loading && !app.cloud.shared.loaded); + start(&mut app); + let (_, list_post) = held.take(|j| matches!(j, Job::List(_))).expect("the root folder is listed again once the sign-in answers"); + list_post.send(Event::Listed { path: String::new(), entries: Ok(vec![entry("/Grace.note", "g1")]) }); + drain(&mut app, &ctx); + assert_eq!(report(&app)["entries"], serde_json::json!(["Grace.note"])); +} + +/// A sign-in empties the folder the Save As page was showing. Until it answers, a save would go +/// to the root rather than the folder the user picked, so Save As refuses. +#[test] +fn save_as_waits_for_a_sign_in_to_answer() { + let (mut app, held, _log) = two_tabs(); + browse(&mut app, "/Projects"); + sign_in(&mut app); + let folder = app.cloud.mine.path.clone(); + let refused = save_as(&mut app, &folder, "B"); + assert!(refused.is_err(), "Save As went ahead during sign-in: {refused:?}"); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none()); + + held.take(|j| matches!(j, Job::SignIn)).unwrap().1.send(Event::Account(Ok(account("Ada")))); + drain(&mut app, &egui::Context::default()); + assert!(save_as(&mut app, "", "B").is_ok()); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_some()); +} + /// An account and a listing answer a job issued before sign-out. Landing after it, they must /// not put the previous session's account and file names on screen with nobody signed in. #[test] @@ -235,6 +282,58 @@ fn a_late_reply_from_before_sign_out_is_dropped() { ); } +/// File › Open calls `start` on every frame. A sign-out has no answer, so nothing orders it +/// before a request the next frame sends. A provider that still holds the session answers that +/// request with the departed account, and the window must not show that account or its files. +#[test] +fn a_page_drawn_after_sign_out_does_not_bring_the_account_back() { + let (mut app, held, _log) = two_tabs(); + start(&mut app); + let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap(); + post.send(Event::Account(Ok(account("Previous Person")))); + held.take(|j| matches!(j, Job::List(_))).unwrap(); + drain(&mut app, &egui::Context::default()); + sign_out(&mut app); + start(&mut app); + // Whatever the frame asked is answered as a provider that has not yet ended the session would. + while let Some((job, post)) = held.take(|j| matches!(j, Job::Account | Job::List(_))) { + match job { + Job::Account => post.send(Event::Account(Ok(account("Previous Person")))), + Job::List(path) => post.send(Event::Listed { path, entries: Ok(vec![entry("/Payroll 2026.note", "p1")]) }), + _ => {} + } + } + drain(&mut app, &egui::Context::default()); + let r = report(&app); + assert!( + r["account"].is_null() && r["entries"].as_array().is_some_and(Vec::is_empty), + "signed out, yet account={} entries={}", + r["account"], + r["entries"] + ); + sign_in(&mut app); + let (_, post) = held.take(|j| matches!(j, Job::SignIn)).unwrap(); + post.send(Event::Account(Ok(account("Ada")))); + drain(&mut app, &egui::Context::default()); + start(&mut app); + assert!(held.take(|j| matches!(j, Job::List(_))).is_some(), "the next sign-in lists the root folder again"); +} + +/// Save As while signed out has no account to land in. A provider that has not ended the session +/// yet would create the file in the account that is leaving. +#[test] +fn save_as_after_sign_out_is_refused_until_the_next_sign_in() { + let (mut app, held, _log) = two_tabs(); + start(&mut app); + let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap(); + post.send(Event::Account(Ok(account("Previous Person")))); + drain(&mut app, &egui::Context::default()); + sign_out(&mut app); + let refused = save_as(&mut app, "", "Plan"); + assert!(refused.is_err(), "signed out, yet Save As went ahead: {refused:?}"); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none(), "nothing is created while signed out"); +} + /// Save as a copy, then the first click on the Save As page is refused (no name typed yet). The /// second click, with a name, must still copy the conflicted document A, not the active tab B. #[test] diff --git a/crates/cloud-ui/src/cloud/mod.rs b/crates/cloud-ui/src/cloud/mod.rs index b1013a8ad4..b99ea2f612 100644 --- a/crates/cloud-ui/src/cloud/mod.rs +++ b/crates/cloud-ui/src/cloud/mod.rs @@ -178,7 +178,8 @@ pub struct Guest { /// exists. pub struct CloudFiles { backend: Option>, - events: (Sender, Receiver), + /// Each answer with the account generation its job was issued in. + events: (Sender, Receiver), /// The badge and its menu. Signing in is the only way into any of this. /// The badge is the only control that offers it. It lives here. An /// application declares no field for it. @@ -190,6 +191,11 @@ pub struct CloudFiles { pub account_fault: Option, /// The account is asked for once per run. A frame never asks again. asked_account: bool, + /// Set by [`sign_out`] and cleared by [`sign_in`]. While it is set, the + /// pages ask the service nothing. [`Job::SignOut`] has no answer and no + /// order against a later job, so a provider that still holds the session + /// could answer an account or listing request with the departed account. + signed_out: bool, /// The folder being browsed. Shared by the Open and Save As pages, which /// are never on screen together. pub mine: Folder, @@ -215,9 +221,14 @@ pub struct CloudFiles { /// stay set after a failed sign-in. sign_in_from_menu: bool, /// Bumped on sign-out and on a new sign-in. Stamped onto every [`Post`] - /// handed out by [`submit`] so a reply to a job issued before the bump is - /// dropped rather than applied to the session that replaced it. + /// handed out by [`submit`] and onto every answer it queues. [`pump`] + /// drops an answer to a job issued before the bump rather than applying + /// it to the session that replaced it. account_generation: Arc, + /// Set by [`sign_in`] and cleared by the account answer that follows it. + /// While it is set both folders read as loading, so no listing is asked + /// for before the service says who is now signed in. + relist_after_sign_in: bool, /// The document Save As must act on, when it is not the active one. /// /// Set only by the conflict modal's "Save as a copy", so the copy it asks @@ -243,6 +254,7 @@ impl CloudFiles { account: None, account_fault: None, asked_account: false, + signed_out: false, mine: Folder::default(), shared: Folder::default(), source: Source::default(), @@ -256,6 +268,7 @@ impl CloudFiles { guest: None, sign_in_from_menu: false, account_generation: Arc::new(AtomicU64::new(0)), + relist_after_sign_in: false, save_as_target: None, } } @@ -337,8 +350,10 @@ pub fn submit(app: &A, job: Job) { } /// Asks who is signed in, once per run, and lists the root folder. +/// +/// After [`sign_out`] it asks nothing until the next [`sign_in`]. pub fn start(app: &mut A) { - if !available(app) { + if !available(app) || app.cloud().signed_out { return; } if !app.cloud().asked_account { @@ -368,14 +383,21 @@ pub fn sign_in(app: &mut A) { // would then be swallowed by the guard that stops a frame asking twice. A // button that does nothing the second time reads as a broken button. cloud.asked_account = true; + cloud.signed_out = false; cloud.link = None; cloud.status = Some(working); // A new session. A job the previous one left outstanding may never - // answer, and if it does, that answer is not about this account: see - // `Post::send`. Busy goes with it, or a stuck read from before this + // answer, and if it does, that answer is not about this account: `pump` + // drops it. Busy goes with it, or a stuck read from before this // sign-in would leave Save refused for a session that never asked for it. + // A folder listing that was outstanding is dropped the same way. Both + // folders wait for the account answer, which empties them so the next + // frame lists them for the account that is now signed in. cloud.account_generation.fetch_add(1, Ordering::Relaxed); cloud.busy = None; + cloud.mine = Folder { loading: true, ..Folder::default() }; + cloud.shared = Folder { loading: true, ..Folder::default() }; + cloud.relist_after_sign_in = true; submit(app, Job::SignIn); } @@ -389,6 +411,10 @@ pub fn sign_out(app: &mut A) { cloud.account = None; cloud.account_fault = None; cloud.asked_account = false; + // File › Open and Save As call `start` on every frame. Without this, the + // next frame would ask who is signed in and list the root folder while + // the sign-out may still be on its way. + cloud.signed_out = true; cloud.link = None; cloud.mine = Folder::default(); cloud.shared = Folder::default(); @@ -396,26 +422,37 @@ pub fn sign_out(app: &mut A) { cloud.status = Some(signed_out); // The session this window had ends here. A job it started may never // answer, and a reply that does arrive late must not land on whatever - // comes next: see `Post::send`. Busy goes with it, so an open or a save + // comes next: `pump` drops it. Busy goes with it, so an open or a save // that never heard back does not refuse every one after it forever. cloud.account_generation.fetch_add(1, Ordering::Relaxed); cloud.busy = None; + cloud.sharing_save = false; + cloud.relist_after_sign_in = false; cloud.save_as_target = None; + // Sharing went with the account: Share is not offered on the old + // account's answer, and a sheet open on one of its documents closes. The + // next sign-in asks the provider again. + app.sharing().signed_out(); submit(app, Job::SignOut); } /// Lists one folder. An empty path is the user's root. +/// +/// Nothing is sent while a sign-in waits for its answer. A listing sent then +/// can answer after the account does, and its files may be the previous +/// account's; the answer empties the folder so it is listed again. pub fn browse(app: &mut A, path: &str) { - if !available(app) { + if !available(app) || app.cloud().relist_after_sign_in { return; } app.cloud_mut().mine.begin(path); submit(app, Job::List(path.to_owned())); } -/// Lists what other people have shared with this user. +/// Lists what other people have shared with this user. Like [`browse`], it +/// sends nothing while a sign-in waits for its answer. pub fn load_shared(app: &mut A) { - if !available(app) { + if !available(app) || app.cloud().relist_after_sign_in { return; } app.cloud_mut().shared.begin(""); @@ -608,6 +645,12 @@ pub fn save_as(app: &mut A, folder: &str, name: &str) -> Result(app: &mut A, ctx: &egui::Context) { while let Ok(event) = app.cloud().events.1.try_recv() { arrived.push(event); } - for event in arrived { + for (issued, event) in arrived { + // A worker that sent just before a sign-out or a new sign-in passed + // `Post::send`'s check, and its answer waited here while the session + // changed. It is about the session that is gone. + if issued != app.cloud().account_generation.load(Ordering::Relaxed) { + continue; + } apply(app, event); } poll_link(app); @@ -649,6 +698,15 @@ pub fn pump(app: &mut A, ctx: &egui::Context) { fn apply(app: &mut A, event: Event) { let noun = app.kind().noun; + if matches!(event, Event::Account(_)) && app.cloud().relist_after_sign_in { + // The sign-in has answered, whether or not it succeeded. Both folders + // are emptied and not loading, so `start` and the Open page list them + // again for whoever is signed in now. + let cloud = app.cloud_mut(); + cloud.relist_after_sign_in = false; + cloud.mine = Folder::default(); + cloud.shared = Folder::default(); + } match event { Event::Account(Ok(account)) => { let linked = account.provider_linked; diff --git a/crates/cloud-ui/src/cloud/pages.rs b/crates/cloud-ui/src/cloud/pages.rs index 86e71d1c88..0d42813869 100644 --- a/crates/cloud-ui/src/cloud/pages.rs +++ b/crates/cloud-ui/src/cloud/pages.rs @@ -42,6 +42,11 @@ fn header(app: &mut A, ui: &mut Ui) { let line = if account.display.is_empty() { app.tr("Signed in") } else { account.display.clone() }; dim(ui, &style, &line); } + // Nothing is asked after a sign-out, so there is nothing to wait for. + (None, None) if app.cloud().signed_out => { + let signed_out = app.tr("Signed out"); + dim(ui, &style, &signed_out); + } (None, None) => { let waiting = app.tr("Connecting to your cloud account…"); dim(ui, &style, &waiting); @@ -422,7 +427,9 @@ pub fn save_page(app: &mut A, ui: &mut Ui) -> bool { asked = typing.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); }); ui.add_space(10.0); - let ready = app.cloud().busy.is_none() && !document_name(&app.cloud().save_name, kind).is_empty(); + // A sign-in in progress has emptied the folder, so the destination is not + // the one the user picked until the folders are listed again. + let ready = app.cloud().busy.is_none() && !app.cloud().relist_after_sign_in && !document_name(&app.cloud().save_name, kind).is_empty(); if ui.add_enabled(ready, egui::Button::new(save_label)).clicked() { asked = true; } diff --git a/crates/cloud-ui/src/cloud/tests.rs b/crates/cloud-ui/src/cloud/tests.rs index 875612144f..951535eda2 100644 --- a/crates/cloud-ui/src/cloud/tests.rs +++ b/crates/cloud-ui/src/cloud/tests.rs @@ -197,6 +197,12 @@ fn pumped(app: &mut Notebook, ctx: &egui::Context) { ctx.end_pass().textures_delta.clear(); } +/// Puts an answer in the channel as a worker for the current session would. +fn deliver(app: &Notebook, event: Event) { + let issued = app.cloud.account_generation.load(Ordering::Relaxed); + app.cloud.events.0.send((issued, event)).unwrap(); +} + fn wired() -> (Notebook, Arc>>, egui::Context) { let mut app = Notebook::new(); let jobs = Arc::new(Mutex::new(Vec::new())); @@ -339,7 +345,7 @@ fn a_refused_save_is_put_to_the_user_and_never_retried() { pumped(&mut app, &ctx); jobs.lock().unwrap().clear(); // What a service answers when somebody else saved first. - app.cloud.events.0.send(Event::Saved { uid: 1, entry: Err(Fault::Conflict) }).unwrap(); + deliver(&app, Event::Saved { uid: 1, entry: Err(Fault::Conflict) }); pumped(&mut app, &ctx); assert_eq!(report(&app)["conflict"]["name"], "Minutes.note", "the user is told, and asked what to do"); assert_eq!(app.did().dropped, vec![1], "the version that did not land is forgotten"); @@ -349,7 +355,7 @@ fn a_refused_save_is_put_to_the_user_and_never_retried() { #[test] fn no_account_yet_is_an_offer_to_link_and_never_an_error() { let (mut app, _jobs, ctx) = wired(); - app.cloud.events.0.send(Event::Account(Err(Fault::NotLinked))).unwrap(); + deliver(&app, Event::Account(Err(Fault::NotLinked))); pumped(&mut app, &ctx); assert_eq!(report(&app)["link"], "offered"); assert_eq!(report(&app)["accountError"], serde_json::Value::Null, "not having linked an account yet is not a failure"); @@ -359,7 +365,7 @@ fn no_account_yet_is_an_offer_to_link_and_never_an_error() { #[test] fn a_browser_round_trip_is_polled_until_the_user_is_done() { let (mut app, jobs, ctx) = wired(); - app.cloud.events.0.send(Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) }).unwrap(); + deliver(&app, Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) }); pumped(&mut app, &ctx); assert_eq!(app.did().urls, vec!["https://cloud.example/link/abc".to_owned()], "the browser is opened for them"); assert_eq!(report(&app)["link"]["waiting"], "https://cloud.example/link/abc"); @@ -403,11 +409,10 @@ fn working_together_needs_somewhere_for_the_room_to_be_keyed_on() { #[test] fn a_conversation_uses_the_hosts_chat_opener() { let (mut app, _, ctx) = wired(); - app.cloud - .events - .0 - .send(Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() }))) - .unwrap(); + deliver( + &app, + Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() })), + ); pumped(&mut app, &ctx); @@ -430,6 +435,118 @@ fn signing_out_forgets_everything_this_window_knew() { assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too"); } +/// A sharing service that says it can share and answers nothing else. +struct Shares; + +impl crate::share::ShareBackend for Shares { + fn submit(&self, request: crate::share::Request, reply: crate::share::Replier) { + if request == crate::share::Request::Capabilities { + reply.answer(crate::share::Answer::Capabilities { capabilities: vec![Capability::Sharing], linked: true }); + } + } +} + +#[test] +fn signing_out_takes_sharing_with_it() { + let (mut app, _jobs, ctx) = wired(); + app.share.connect(Shares); + // Enough frames for an account answer to land, the provider to be asked, + // and its answer to be read. + let frames = |app: &mut Notebook| { + for _ in 0..3 { + ctx.begin_pass(Default::default()); + app.share.show(&ctx); + pump(app, &ctx); + ctx.end_pass().textures_delta.clear(); + } + }; + frames(&mut app); + assert!(app.share.available()); + app.share.open("/Minutes.note", "Minutes"); + assert!(app.share.is_open()); + + sign_out(&mut app); + assert!(!app.share.is_open(), "a sheet open on the old account's document closes"); + assert!(!app.share.available(), "Share is not offered on the old account's answer"); + // The provider is not asked again while the sign-out may still be on its + // way, so a service that still has the old account cannot offer it back. + frames(&mut app); + assert!(!app.share.available(), "nobody is signed in"); + + sign_in(&mut app); + frames(&mut app); + assert!(app.share.available(), "the next sign-in asks again"); +} + +#[test] +fn an_answer_queued_before_the_session_changed_is_dropped() { + let (mut app, _jobs, ctx) = wired(); + let old = Account { display: "Ada Lovelace".to_owned(), capabilities: vec![Capability::Files], provider_linked: true }; + + // A worker answers, and the answers wait in the channel while the user + // signs out in the same frame. + let post = Post::new(app.cloud.events.0.clone(), app.cloud.account_generation.clone()); + post.send(Event::Account(Ok(old))); + post.dup().send(Event::Listed { path: String::new(), entries: Ok(vec![file("/Minutes.note")]) }); + sign_out(&mut app); + pumped(&mut app, &ctx); + let state = report(&app); + assert_eq!(state["account"], serde_json::Value::Null, "the previous session's account must not come back"); + assert_eq!(state["entries"], serde_json::json!([]), "nor its files"); + + // The same across a new sign-in. + let post = Post::new(app.cloud.events.0.clone(), app.cloud.account_generation.clone()); + post.send(Event::Listed { path: String::new(), entries: Ok(vec![file("/Stale.note")]) }); + sign_in(&mut app); + pumped(&mut app, &ctx); + assert_eq!(report(&app)["entries"], serde_json::json!([]), "a listing for the signed-out session is not shown to the new one"); +} + +#[test] +fn a_sign_in_that_drops_a_listing_leaves_no_folder_loading() { + let (mut app, _jobs, ctx) = wired(); + + // Both listings are asked for, and the answer to the first waits in the + // channel while the user signs in again. The shared one never answers. + browse(&mut app, ""); + load_shared(&mut app); + sign_in(&mut app); + pumped(&mut app, &ctx); + assert!(!app.cloud.mine.loading, "a dropped listing must not leave the folder loading forever"); + assert!(!app.cloud.shared.loading, "nor the shared one, which would then never be asked for again"); + + // A listing the new session asks for still completes. + browse(&mut app, ""); + pumped(&mut app, &ctx); + assert!(app.cloud.mine.loaded); + assert_eq!(report(&app)["entries"], serde_json::json!(["Minutes.note", "Archive"])); +} + +#[test] +fn a_listing_asked_for_before_the_sign_in_answers_is_not_sent() { + let (mut app, jobs, ctx) = wired(); + sign_in(&mut app); + jobs.lock().unwrap().clear(); + + // Asked for after the sign-in and before its answer. A listing sent now + // could answer after the account does, and its files may be the previous + // account's. + browse(&mut app, ""); + load_shared(&mut app); + assert!( + !jobs.lock().unwrap().iter().any(|j| matches!(j, Job::List(_) | Job::SharedWithMe)), + "no listing goes out while the sign-in is outstanding" + ); + pumped(&mut app, &ctx); + assert!(!app.cloud.mine.loaded && !app.cloud.mine.loading, "the folder waits to be listed for the new account"); + assert!(!app.cloud.shared.loaded && !app.cloud.shared.loading, "and so does the shared one"); + + // Once the sign-in has answered, a listing goes through. + browse(&mut app, ""); + pumped(&mut app, &ctx); + assert!(app.cloud.mine.loaded); +} + #[test] fn bytes_are_said_the_way_a_person_reads_them() { assert_eq!(size_text(None), ""); diff --git a/crates/cloud-ui/src/share/mod.rs b/crates/cloud-ui/src/share/mod.rs index e380674119..9d03472e50 100644 --- a/crates/cloud-ui/src/share/mod.rs +++ b/crates/cloud-ui/src/share/mod.rs @@ -338,6 +338,10 @@ pub struct ShareDialog { provider: Option, /// When the capability question was last asked. asked: Option, + /// The last request number issued before the latest [`ShareDialog::refresh`] + /// or [`ShareDialog::connect`]. A capabilities answer to that request or an + /// earlier one describes the account as it was, and is ignored. + capabilities_after: u64, open: Option, /// Keyed by the URL the contact carried, so reopening the dialog does not /// fetch the same faces again. @@ -370,6 +374,7 @@ impl ShareDialog { seq: 0, provider: None, asked: None, + capabilities_after: 0, open: None, avatars: HashMap::new(), wants_save: None, @@ -387,6 +392,7 @@ impl ShareDialog { self.backend = Some(Box::new(backend)); self.provider = None; self.asked = None; + self.capabilities_after = self.seq; } pub fn connected(&self) -> bool { @@ -413,10 +419,25 @@ impl ShareDialog { /// The answer is kept once it arrives, so a host that signs somebody /// in after the first answer has to say so. Without this the dialog /// keeps the answer it got while nobody was signed in, and Share - /// stays unavailable for the rest of the run. + /// stays unavailable for the rest of the run. An answer to a question + /// asked before the refresh is ignored when it arrives. pub fn refresh(&mut self) { self.provider = None; self.asked = None; + self.capabilities_after = self.seq; + } + + /// Forget sharing for an account that signed out. + /// + /// Closes the sheet and offers nothing until [`ShareDialog::refresh`], + /// which the next sign-in calls. The provider is not asked again here: a + /// question asked before the sign-out reaches the service would describe + /// the account that is leaving. Answers to earlier questions are ignored. + pub fn signed_out(&mut self) { + self.close(); + self.provider = Some(Provider { sharing: false, contacts: false, mail: false, links: false, key: false, key_required: false }); + self.asked = None; + self.capabilities_after = self.seq; } pub fn available(&self) -> bool { @@ -639,6 +660,8 @@ impl ShareDialog { // once the open sheet is no longer borrowed. let mut reload = None; match answer { + // Asked before the account changed: it describes the old one. + Answer::Capabilities { .. } if seq <= self.capabilities_after => {} Answer::Capabilities { capabilities, linked } => { self.provider = Some(Provider { sharing: linked && capabilities.contains(&Capability::Sharing), @@ -675,14 +698,17 @@ impl ShareDialog { } } Answer::Granted { shared, failed } => { - // A link was asked for in order to be handed out, so it goes - // to the clipboard without a second click. - if let Some(url) = shared.iter().find_map(|s| s.url.clone()) { - ctx.copy_text(url); - } if let Some(sheet) = &mut self.open && sheet.granting == Some(seq) { + // A link was asked for in order to be handed out, so it + // goes to the clipboard without a second click. Only for + // the sheet that asked: a grant answered after the sheet + // closed or moved to another document leaves the + // clipboard alone. + if let Some(url) = shared.iter().find_map(|s| s.url.clone()) { + ctx.copy_text(url); + } sheet.granting = None; sheet.error = None; // Recipients that went through leave the picker. The ones @@ -714,13 +740,16 @@ impl ShareDialog { } } Answer::Linked => { - // An account arrived, so the list is stale. - if let Some(sheet) = &mut self.open { - sheet.destinations = None; - } - let seq = self.issue(Request::Destinations); - if let Some(sheet) = &mut self.open { - sheet.destinations_seq = Some(seq); + // An account arrived, so the list is stale. With no sheet open + // there is no list to reload. + if self.open.is_some() { + if let Some(sheet) = &mut self.open { + sheet.destinations = None; + } + let seq = self.issue(Request::Destinations); + if let Some(sheet) = &mut self.open { + sheet.destinations_seq = Some(seq); + } } } Answer::Withdrawn { share_id } => { @@ -918,9 +947,11 @@ fn draw(ui: &mut Ui, sheet: &mut Sheet, avatars: &HashMap, label ui.add(egui::TextEdit::singleline(&mut sheet.link_key).hint_text(labels.key_hint.as_str()).password(true).desired_width(150.0)); } // A key the server insists on cannot be skipped, so the control - // stays disabled until one is typed. + // stays disabled until one is typed. It also waits, as Send does, + // while a grant is in flight: the answer to that grant is the one + // the sheet takes, and an earlier link would be dropped. let keyed = !sheet.link_key.trim().is_empty(); - let ready = keyed || !allowed.key_required; + let ready = (keyed || !allowed.key_required) && sheet.granting.is_none(); if ui.add_enabled(ready, egui::Button::new(labels.create_link.as_str())).clicked() { acts.push(Act::Grant(Grant { id: sheet.id.clone(), diff --git a/crates/cloud-ui/src/share/tests.rs b/crates/cloud-ui/src/share/tests.rs index dfdb3eb1e3..283ce0274b 100644 --- a/crates/cloud-ui/src/share/tests.rs +++ b/crates/cloud-ui/src/share/tests.rs @@ -113,6 +113,24 @@ fn nothing_is_offered_until_the_service_says_sharing_exists() { assert!(dialog.is_open()); } +#[test] +fn a_capabilities_answer_asked_before_a_refresh_is_ignored() { + let ctx = Context::default(); + let backend = Silent::default(); + let mut dialog = ShareDialog::new(); + dialog.connect(backend.clone()); + dialog.collect(&ctx); + dialog.refresh(); + dialog.collect(&ctx); + assert_eq!(backend.seen(), vec![Request::Capabilities, Request::Capabilities], "the refresh asks again"); + + // The first question was about the account before the refresh. + dialog.receive(&ctx, 1, Ok(everything())); + assert!(!dialog.available(), "the old account's answer must not offer Share"); + dialog.receive(&ctx, 2, Ok(everything())); + assert!(dialog.available()); +} + #[test] fn an_unlinked_account_cannot_share_even_where_the_provider_can() { let ctx = Context::default(); @@ -240,6 +258,85 @@ fn a_share_reaching_four_of_five_names_the_fifth() { assert_eq!(left.chosen.first().map(|c| &c.target), Some(&ShareTarget::Email("nobody@@".into()))); } +fn copied(ctx: &Context) -> Vec { + ctx.output(|o| o.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(text) = c { Some(text.clone()) } else { None }).collect()) +} + +fn ask_for_link(dialog: &mut ShareDialog) -> u64 { + let granting = dialog.issue(Request::Grant(Grant { + id: "files/budget.xlsx".into(), + password: None, + targets: Vec::new(), + permission: Permission::View, + note: None, + notify: false, + })); + if let Some(sheet) = &mut dialog.open { + sheet.granting = Some(granting); + } + granting +} + +fn link(url: &str) -> Answer { + let mut made = share("s1", ShareTarget::Email("anyone@example.com".into())); + made.url = Some(url.into()); + Answer::Granted { shared: vec![made], failed: Vec::new() } +} + +#[test] +fn a_granted_link_goes_to_the_clipboard() { + let (ctx, mut dialog, _) = ready(); + let granting = ask_for_link(&mut dialog); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert_eq!(copied(&ctx), ["https://cloud.example/l/budget"]); +} + +#[test] +fn a_link_granted_after_the_sheet_moved_on_is_not_copied() { + let (ctx, mut dialog, _) = ready(); + let granting = ask_for_link(&mut dialog); + dialog.close(); + dialog.open("files/plan.docx", "Plan"); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert!(copied(&ctx).is_empty(), "the budget's link must not replace the clipboard while the plan is open"); + + let (ctx, mut dialog, _) = ready(); + let granting = ask_for_link(&mut dialog); + dialog.close(); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert!(copied(&ctx).is_empty(), "nor after the sheet closed"); +} + +/// Whether one frame of the sheet offers "Get a link" as a button that can +/// be pressed, read off the accessibility tree. +fn link_button_enabled(dialog: &mut ShareDialog) -> Option { + let ctx = Context::default(); + ctx.enable_accesskit(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 900.0))), ..Default::default() }; + let mut output = ctx.run_ui(raw, |ui| dialog.show_in(ui)); + output.textures_delta.clear(); + let tree = output.platform_output.accesskit_update?; + tree.nodes + .iter() + .find(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label() == Some("Get a link")) + .map(|(_, node)| !node.is_disabled()) +} + +#[test] +fn get_a_link_waits_while_a_grant_is_in_flight() { + let ctx = Context::default(); + let mut dialog = ShareDialog::new(); + dialog.connect(Silent::default()); + dialog.collect(&ctx); + dialog.receive(&ctx, 1, Ok(can(vec![Capability::Sharing, Capability::LinkShares]))); + dialog.open("files/budget.xlsx", "Budget"); + assert_eq!(link_button_enabled(&mut dialog), Some(true)); + let granting = ask_for_link(&mut dialog); + assert_eq!(link_button_enabled(&mut dialog), Some(false), "a second grant would make the first one's link be dropped"); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert_eq!(link_button_enabled(&mut dialog), Some(true)); +} + #[test] fn a_refusal_that_stopped_the_whole_call_is_not_a_failed_recipient() { let (ctx, mut dialog, _) = ready(); @@ -501,6 +598,15 @@ fn a_closed_dialog_still_collects_and_reports_nothing() { assert!(shared.is_empty() && failed.is_empty()); } +#[test] +fn a_link_answer_arriving_with_no_sheet_open_asks_for_nothing() { + let (ctx, mut dialog, backend) = ready(); + dialog.signed_out(); + let before = backend.seen().len(); + dialog.receive(&ctx, 99, Ok(Answer::Linked)); + assert_eq!(backend.seen().len(), before); +} + #[test] fn pressing_return_takes_the_first_match_or_an_address() { let (_ctx, mut dialog, _) = ready(); diff --git a/crates/cms/src/black_tests.rs b/crates/cms/src/black_tests.rs index 2d4864a990..90b7bee271 100644 --- a/crates/cms/src/black_tests.rs +++ b/crates/cms/src/black_tests.rs @@ -10,9 +10,8 @@ fn opts() -> TransformOptions { TransformOptions::default() } -/// L* of a CMYK colour under `p`, measured as the transform with `o` measures it. -fn lightness(p: &Profile, o: TransformOptions, cmyk: [f32; 4]) -> f32 { - let t = Transform::with_options(p, Builtin::LabD50.profile(), o).unwrap(); +/// L* of a CMYK colour, measured by the prebuilt transform. +fn lightness(t: &Transform, cmyk: [f32; 4]) -> f32 { let mut lab = [0.0f32; 3]; t.eval(&cmyk, &mut lab).unwrap(); lab[0] * 100.0 @@ -70,18 +69,22 @@ fn the_destination_black_matches_the_source_lightness() { for intent in [Intent::RelativeColorimetric, Intent::Perceptual] { for bpc in [true, false] { let o = TransformOptions { intent, bpc, ..opts() }; + let coated_lab = Transform::with_options(coated(), Builtin::LabD50.profile(), o).unwrap(); + let fogra_lab = Transform::with_options(fogra(), Builtin::LabD50.profile(), o).unwrap(); // Both directions for one setting; the other settings in the forward one. let directions = if intent == Intent::RelativeColorimetric && bpc { 2 } else { 1 }; - for (src, dst) in [(coated(), fogra()), (fogra(), coated())].into_iter().take(directions) { + for (src, dst, src_lab, dst_lab) in + [(coated(), fogra(), &coated_lab, &fogra_lab), (fogra(), coated(), &fogra_lab, &coated_lab)].into_iter().take(directions) + { let bp = BlackPreserving::new(src, dst, o).unwrap(); - let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]); + let dst_black = lightness(dst_lab, [0.0, 0.0, 0.0, 1.0]); for k in [0.1f32, 0.5, 0.9, 1.0] { - let want = lightness(src, o, [0.0, 0.0, 0.0, k]); + let want = lightness(src_lab, [0.0, 0.0, 0.0, k]); if want <= dst_black { assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1"); continue; } - let got = lightness(dst, o, [0.0, 0.0, 0.0, bp.map_k(k)]); + let got = lightness(dst_lab, [0.0, 0.0, 0.0, bp.map_k(k)]); assert!((got - want).abs() < 0.02, "{intent:?} bpc {bpc} k {k}: L* {got} for {want}"); } assert_eq!(bp.map_k(0.0), 0.0, "paper stays paper"); diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index cb2c2f3972..c026896980 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -319,23 +319,33 @@ fn solve_cmy_by(model: &F, k: f64, limit: f64, seeds: &[[f6 const SEEDS: [[f64; 3]; 5] = [[0.3, 0.3, 0.3], [0.05, 0.05, 0.05], [0.8, 0.8, 0.8], [0.9, 0.2, 0.2], [0.2, 0.9, 0.9]]; -/// Black for a gray component `g` (the smallest of C, M, Y without black). +/// Black for a gray component `g` (the smallest of C, M, Y without black), at most the total ink +/// limit: the CMY solve gets `tac - k`, so black above `tac` would break the limit on its own. fn gcr(p: &CmykParams, g: f64) -> f64 { - let Some(first) = p.gcr_curve.first() else { + let k = match p.gcr_curve.first() { // The Photocraft profile's curve. - return if g <= p.gcr_start { 0.0 } else { p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) }; - }; - let mut k = first[1]; - for w in p.gcr_curve.windows(2) { - let ([g0, k0], [g1, k1]) = (w[0], w[1]); - if g >= g1 { - k = k1; - } else if g > g0 { - k = k0 + (k1 - k0) * (g - g0) / (g1 - g0); - break; + None => { + if g <= p.gcr_start { + 0.0 + } else { + p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) + } } - } - k.clamp(0.0, 1.0) + Some(first) => { + let mut k = first[1]; + for w in p.gcr_curve.windows(2) { + let ([g0, k0], [g1, k1]) = (w[0], w[1]); + if g >= g1 { + k = k1; + } else if g > g0 { + k = k0 + (k1 - k0) * (g - g0) / (g1 - g0); + break; + } + } + k + } + }; + k.clamp(0.0, 1.0).min(p.tac.max(0.0)) } /// Colorimetric separation of a relative Lab target: GCR black generation then a CMY solve. @@ -712,6 +722,9 @@ fn check_grids(p: &CmykParams) -> Result<(), CmsError> { if p.white_on_node && p.grid_b2a.is_multiple_of(2) { return Err(invalid_arg(format!("white on a node needs an odd BToA grid, not {}", p.grid_b2a))); } + if !(p.tac.is_finite() && p.tac >= 0.0) { + return Err(invalid_arg(format!("total ink limit {} must be finite and not negative", p.tac))); + } let valid = |v: &[f64; 2]| v.iter().all(|x| (0.0..=1.0).contains(x)); if !p.gcr_curve.iter().all(valid) || p.gcr_curve.windows(2).any(|w| w[1][0] <= w[0][0]) { return Err(invalid_arg(format!("black generation curve {:?} needs points in [0, 1] with increasing gray components", p.gcr_curve))); @@ -847,6 +860,33 @@ mod tests { } } + #[test] + fn total_ink_limit_must_be_finite_and_not_negative() { + for tac in [-0.5, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let p = CmykParams { grid_a2b: 2, grid_b2a: 2, tac, ..CmykParams::default() }; + assert!(cmyk_profile(&p).is_err(), "tac {tac}"); + } + // `separate` is public and does not validate: black is still never negative. + let p = CmykParams { tac: -0.5, gcr_curve: vec![[0.0, 0.75]], ..CmykParams::default() }; + assert_eq!(gcr(&p, 0.5), 0.0); + } + + #[test] + fn curve_black_stays_within_the_ink_limit() { + // Black from either the profile curve or the default empty-curve fallback never exceeds the ink limit. + let m = CmykModel::coated(CmykParams::default().tvi); + for gcr_curve in [vec![[0.0, 0.75]], vec![]] { + for tac in [0.5, 0.0] { + let p = CmykParams { tac, gcr_curve: gcr_curve.clone(), ..CmykParams::default() }; + assert!(gcr(&p, 1.0) <= p.tac, "tac {tac} curve {gcr_curve:?}"); + for target in [[50.0, 0.0, 0.0], [90.0, 0.0, 0.0], [30.0, 20.0, -10.0]] { + let (cmyk, _) = separate(&m, &p, target, None); + assert!(cmyk.iter().sum::() <= p.tac + 1e-6, "{target:?} -> {cmyk:?}"); + } + } + } + } + #[test] fn oklab_round_trips() { let m = CmykModel::coated(CmykParams::default().tvi); @@ -861,7 +901,7 @@ mod tests { #[test] fn oklab_profile_has_three_tables() { - let p = CmykParams { grid_a2b: 5, grid_b2a: 5, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() }; + let p = CmykParams { grid_a2b: 3, grid_b2a: 3, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() }; let profile = cmyk_profile(&p).unwrap(); let [Some(b0), Some(b1), Some(b2)] = &profile.b2a else { panic!("missing BToA tables") }; assert!(b0 != b1 && b0 != b2, "perceptual shares a table"); diff --git a/crates/cms/tests/fogra39.rs b/crates/cms/tests/fogra39.rs index 806bff7138..a555f34c54 100644 --- a/crates/cms/tests/fogra39.rs +++ b/crates/cms/tests/fogra39.rs @@ -430,6 +430,8 @@ fn separates_like_the_reference_application() { for (rgb, want) in REFERENCE_SEPARATIONS { for ((intent, bpc), want) in SEPARATION_INTENTS.into_iter().zip(want) { let got = separation(intent, bpc, rgb); + // `f32::max` drops a NaN, so a NaN ink would otherwise count as no difference. + assert!(got.iter().all(|v| v.is_finite()), "{rgb:?} {intent:?} bpc {bpc}: {got:?}"); let diff = (0..4).map(|i| (got[i] - want[i]).abs()).fold(0.0f32, f32::max); eprintln!("{rgb:?} {intent:?} bpc {bpc}: {got:.1?} reference {want:?} (max {diff:.1})"); worst = worst.max(diff); diff --git a/crates/color-ui/README.md b/crates/color-ui/README.md index 9c81d3d68b..a38b1f9827 100644 --- a/crates/color-ui/README.md +++ b/crates/color-ui/README.md @@ -7,3 +7,8 @@ Stories: `patterns/color/{picker-dialog, panel, swatches, eyedropper-bar, sample Without `ui`: `CmykModel` (CMYK through a craft-cms profile), swatch files (`palette`: `.aco`, `.act`, `.ase`, `.gpl`, `.css`), the display transform and its caches (`display`), and colour harmonies (`harmony`). The colour model and conversions are in `craft-theme`; profiles and transforms in `craft-cms`. + +`ColorPanel::edited` can supply a colour's native components. Editing one channel preserves the other components, +even when the host renders the colour through a different working-space transform. Current host components take +precedence over the panel's remembered values. Canceling a channel gesture restores the host's complete opening +colour, including its display colour, alpha and native components. diff --git a/crates/color-ui/src/ui/choice.rs b/crates/color-ui/src/ui/choice.rs index 0cd393e88e..0af3dfc6ec 100644 --- a/crates/color-ui/src/ui/choice.rs +++ b/crates/color-ui/src/ui/choice.rs @@ -59,7 +59,7 @@ pub enum ChosenColor { pub struct ColorChoiceOutput { /// The choice's response. pub response: Response, - /// The row chosen this pass; the host stores it. + /// The row committed this pass; the host stores it. Navigating an open popup reports no choice. pub chosen: Option, /// "Select Custom Color…" was chosen, for this pass only: the app opens its colour picker from the request (key /// [`ColorChoice::CUSTOM_KEY`], the custom colour) and, on OK, stores the colour and chooses @@ -151,7 +151,7 @@ impl<'a> ColorChoice<'a> { entries.push(Entry::separator()); entries.push(Entry::new(Row::SelectCustom, words.select_custom.as_str().to_owned())); let shown = Select::new(self.label.clone(), Bind::given(row), &entries).enabled(self.enabled).show(ui); - let picked = shown.value().cloned(); + let picked = shown.events.committed().cloned(); let mut pick_color = None; let chosen = match picked { Some(Row::Named(id)) => Some(ChosenColor::Named(id)), diff --git a/crates/color-ui/src/ui/eyedropper.rs b/crates/color-ui/src/ui/eyedropper.rs index 9a238c2863..4e17c7b572 100644 --- a/crates/color-ui/src/ui/eyedropper.rs +++ b/crates/color-ui/src/ui/eyedropper.rs @@ -61,7 +61,7 @@ craft_ui::words! { } /// How many pixels around the pointer the eyedropper averages: Photoshop's Sample Size list. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum SampleSize { @@ -115,7 +115,7 @@ impl SampleSize { } /// Which layers the eyedropper reads: Photoshop's Sample list. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum SampleSource { @@ -172,7 +172,7 @@ impl SampleSource { } /// The Eyedropper's options bar values. -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct EyedropperOptions { diff --git a/crates/color-ui/src/ui/gradient/editor/bar.rs b/crates/color-ui/src/ui/gradient/editor/bar.rs index ba55ee2823..394dcdfeab 100644 --- a/crates/color-ui/src/ui/gradient/editor/bar.rs +++ b/crates/color-ui/src/ui/gradient/editor/bar.rs @@ -845,7 +845,7 @@ impl Component for GradientBar<'_, P> { let edge_of = |m: StopRef| { if self.selected_marker == Some(m) { style.selected - } else if !dragging && cx.hover_pos(part_of(m)).is_some() { + } else if !dragging && cx.part_if_declared(part_of(m)).is_some_and(|result| result.hovered) { style.hovered } else { cx.resolve(&style.edge) diff --git a/crates/color-ui/src/ui/pair.rs b/crates/color-ui/src/ui/pair.rs index 8cb8cda739..5504a5a901 100644 --- a/crates/color-ui/src/ui/pair.rs +++ b/crates/color-ui/src/ui/pair.rs @@ -440,8 +440,13 @@ impl Component for SwatchPair<'_, P> { flags.set(Flags::MIXED, self.wells[i].paint.same().is_none()); flags.set(Flags::CHECKED, well == active); let shape = if cx.style.round { HitShape::circle(at.center(), at.width() / 2.0) } else { HitShape::Rect(at) }; - let part = - cx.part(WELL.at(i as u64), shape).sense(sense).priority(HitPriority::new(HitLevel::Body, u8::from(front))).flags(flags).focusable(); + let part = cx + .part(WELL.at(i as u64), shape) + .sense(sense) + .priority(HitPriority::new(HitLevel::Body, u8::from(front))) + .flags(flags) + .focusable() + .tooltip(self.wells[i].label.clone()); // Focus arrives at the active well, so arriving makes no other well active. let part = if well == active { part.selected() } else { part }; if self.popover { @@ -449,10 +454,10 @@ impl Component for SwatchPair<'_, P> { } } let buttons = self.button_rects(cx.style); - for (key, button, shown) in [(DEFAULT, buttons[0], self.default_button.is_some()), (SWAP, buttons[1], self.swap_button.is_some())] { - if shown { + for (key, button, name) in [(DEFAULT, buttons[0], &self.default_button), (SWAP, buttons[1], &self.swap_button)] { + if let Some(name) = name { let at = flow.to_physical(button.translate(rect.min.to_vec2())); - cx.part(key, at).sense(Sense::CLICK).pointer_only("The host's Default Colours and Swap Colours commands"); + cx.part(key, at).sense(Sense::CLICK).tooltip(name.clone()).pointer_only("The host's Default Colours and Swap Colours commands"); } } cx.roving(Roving::new(NavShape::Flat)); diff --git a/crates/color-ui/src/ui/palette.rs b/crates/color-ui/src/ui/palette.rs index 000e8ca818..b5d35ac5c0 100644 --- a/crates/color-ui/src/ui/palette.rs +++ b/crates/color-ui/src/ui/palette.rs @@ -3,15 +3,15 @@ use craft_behavior::{EditEvent, IconId, Mixed, Selection}; use craft_theme::Srgba; -use craft_ui::choice::{SwatchSpacing, SwatchTable}; -use craft_ui::contract::{ActivateOn, Bind, Held, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _}; +use craft_ui::choice::{SwatchSpacing, SwatchTable, SwatchTableOutput}; +use craft_ui::contract::{ActivateOn, Bind, Held, LeadOnOpen, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _, SpaceAction}; use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::Stack; use craft_ui::runtime::env::Label; use craft_ui::runtime::memory::StageAccess; use craft_ui::runtime::requests::ColorRequest; use craft_ui::style::TypeRole; -use egui::{Response, Ui}; +use egui::{PointerButton, Response, Ui}; use std::sync::Arc; #[cfg(feature = "suite")] @@ -35,6 +35,9 @@ pub struct SwatchPaletteOutput { pub pick_color: Option, /// Every swatch click of this pass, also a click on the colour already bound, which files no `edit`. pub picked: Option, + /// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour. + /// The recent row and the Other… cell do not report a swatch index. + pub picked_swatch: Option, } impl Outcome for SwatchPaletteOutput { @@ -65,6 +68,7 @@ pub struct SwatchPalette<'a> { label: Label, color: PaletteColor<'a>, swatches: &'a [(Label, Srgba)], + selected_swatch: Option, spacing: SwatchSpacing, drag: Option, /// The Other… cell: the key of its colour request and its name. @@ -109,7 +113,7 @@ impl PaletteColor<'_> { #[derive(Clone, Copy)] enum Pick { /// A swatch or a recent colour. - Color(Srgba), + Color { color: Srgba, swatch: Option }, /// The Other… cell. Other, } @@ -119,6 +123,15 @@ fn cell_of(swatches: &[(Label, Srgba)], color: Option) -> Selection Option { + table.open.or_else(|| { + table.selected.filter(|_| { + ui.input(|input| input.pointer.button_pressed(PointerButton::Secondary) || input.pointer.button_released(PointerButton::Secondary)) + }) + }) +} + impl<'a> SwatchPalette<'a> { /// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`. pub fn new(label: impl Into