diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 000000000..02cdf71c8 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,188 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/ai-core.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/atomic.yml': + - 'actions/checkout@v4.4.0' + - 'actions/checkout@v7.0.1' + - 'dtolnay/rust-toolchain@stable' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/audio.yml': + - 'actions/cache@v6.1.0' + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/cms.yml': + - 'actions/checkout@v4.4.0' + - 'dtolnay/rust-toolchain@stable' + '.github/workflows/crw.yml': + - 'actions/cache@v6.1.0' + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/dialogs.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/doc.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/docpath.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/ecproj-format.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/font-store.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/formats.yml': + - 'actions/checkout@v7.0.1' + - 'dtolnay/rust-toolchain@stable' + - 'step-security/harden-runner@v2.22.4' + - 'swatinem/rust-cache@v2.9.3' + '.github/workflows/house-rules.yml': [] + '.github/workflows/i18n.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/jpeg.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/keymap.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/lockfile.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/media.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/menu.yml': + - 'actions/checkout@v7.0.1' + - 'dtolnay/rust-toolchain@stable' + - 'swatinem/rust-cache@v2.9.3' + '.github/workflows/pcraft-format.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/pdf.yml': + - 'actions/checkout@v7.0.1' + - 'actions/setup-python@v7.1.0' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + - 'step-security/taiki-e-install-action@v2.87.32' + '.github/workflows/print.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/proof.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/sonarcloud.yml': [] + '.github/workflows/ui.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/update.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/vectorcraft-format.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/video.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/web-api.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/taiki-e-install-action@v2.87.32' + '.github/workflows/web-host.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + - 'step-security/taiki-e-install-action@v2.87.32' + '.github/workflows/window.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/workspace.yml': [] +dependencies: + 'actions/cache@v6.1.0': + ref: 'v6.1.0' + commit: 'sha1-55cc8345863c7cc4c66a329aec7e433d2d1c52a9' + owner_id: 44036562 + repo_id: 215566462 + 'actions/checkout@v4.4.0': + ref: 'v4.4.0' + commit: 'sha1-11d5960a326750d5838078e36cf38b85af677262' + owner_id: 44036562 + repo_id: 197814629 + 'actions/checkout@v7.0.1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'actions/setup-python@v7.1.0': + ref: 'v7.1.0' + commit: 'sha1-6d4fd22b20465ccc0f7354476588e8df7c9ca0e0' + owner_id: 44036562 + repo_id: 192625525 + 'dtolnay/rust-toolchain@stable': + ref: 'stable' + commit: 'sha1-39008827e6b4319a349e9a42dfc90579dd25f1ca' + owner_id: 1940490 + repo_id: 260749683 + 'step-security/dtolnay-rust-toolchain@v1.0.0': + ref: 'v1.0.0' + commit: 'sha1-8dd607977d06adf4ed49b190381e74c17a9dd25f' + owner_id: 88700172 + repo_id: 1249865941 + 'step-security/harden-runner@v2.22.4': + ref: 'v2.22.4' + commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a' + owner_id: 88700172 + repo_id: 422287306 + 'step-security/rust-cache@v2.9.2': + ref: 'v2.9.2' + commit: 'sha1-8871c8ba063416da7c32246932ea6ae08700453e' + owner_id: 88700172 + repo_id: 822636713 + 'step-security/taiki-e-install-action@v2.87.32': + ref: 'v2.87.32' + commit: 'sha1-76747d22a7567cc4438546a84f11bdf18e670ab8' + owner_id: 88700172 + repo_id: 1382753260 + 'swatinem/rust-cache@v2.9.3': + ref: 'v2.9.3' + commit: 'sha1-d1527c8f67ef9af357290475d4af4b0fab8f12e0' + owner_id: 580492 + repo_id: 298565987 diff --git a/.github/workflows/ai-core.yml b/.github/workflows/ai-core.yml index cc8d738ac..5471bf1ec 100644 --- a/.github/workflows/ai-core.yml +++ b/.github/workflows/ai-core.yml @@ -28,11 +28,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/atomic.yml b/.github/workflows/atomic.yml index 1a20fa679..f72a64f1e 100644 --- a/.github/workflows/atomic.yml +++ b/.github/workflows/atomic.yml @@ -28,11 +28,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy @@ -50,7 +50,7 @@ jobs: name: Atomic WASM runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - uses: dtolnay/rust-toolchain@stable with: targets: wasm32-unknown-unknown diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index 0104f848e..d6a7ff5e2 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -25,18 +25,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-audio-lint save-if: ${{ github.ref == 'refs/heads/main' }} @@ -44,7 +44,7 @@ jobs: # Each feature on its own, so code that needs another feature fails here. - name: Clippy, each feature alone run: | - for f in "" decode decode-native symphonia encode lossless-encode pcm-encode flac-encode peaks aac-decode aac-encode "aac-encode,rayon" opus-decode ac3-decode mpa-decode serde; do + for f in "" decode decode-native symphonia encode lossless-encode pcm-encode flac-encode peaks aac-decode aac-encode "aac-encode,rayon" opus-decode opus-encode ac3-decode mpa-decode serde; do echo "::group::features: ${f:-none}" cargo clippy -p craft-audio --all-targets --locked --no-default-features ${f:+--features "$f"} -- -D warnings echo "::endgroup::" @@ -69,15 +69,15 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false # The workspace's rust-version. - run: rustup toolchain install 1.95.0 --profile minimal - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-audio-msrv save-if: ${{ github.ref == 'refs/heads/main' }} @@ -88,16 +88,16 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-audio-features save-if: ${{ github.ref == 'refs/heads/main' }} @@ -113,20 +113,20 @@ jobs: runs-on: ubuntu-26.04 steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-audio-test save-if: ${{ github.ref == 'refs/heads/main' }} - - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + - uses: actions/cache@v6.1.0 with: path: ${{ runner.temp }}/media-fixtures/opus/vectors # The archive's SHA-256 (scripts/fetch-opus-vectors.sh checks it). diff --git a/.github/workflows/cms.yml b/.github/workflows/cms.yml index a15a48c9d..74ce0815f 100644 --- a/.github/workflows/cms.yml +++ b/.github/workflows/cms.yml @@ -16,7 +16,7 @@ jobs: timeout-minutes: 20 runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - uses: dtolnay/rust-toolchain@stable with: components: clippy diff --git a/.github/workflows/crw.yml b/.github/workflows/crw.yml index 8fec98661..54be7ba3b 100644 --- a/.github/workflows/crw.yml +++ b/.github/workflows/crw.yml @@ -29,17 +29,17 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-crw-${{ matrix.os }} save-if: ${{ github.ref == 'refs/heads/main' }} @@ -53,17 +53,17 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-crw-wasm save-if: ${{ github.ref == 'refs/heads/main' }} @@ -75,21 +75,21 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-crw-samples save-if: ${{ github.ref == 'refs/heads/main' }} - name: Cache the CC0 sample files - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + uses: actions/cache@v6.1.0 with: path: ${{ runner.temp }}/crw-samples key: crw-samples-${{ hashFiles('crates/crw/tests/samples.json') }} diff --git a/.github/workflows/dialogs.yml b/.github/workflows/dialogs.yml index 97a931aec..c8d43d725 100644 --- a/.github/workflows/dialogs.yml +++ b/.github/workflows/dialogs.yml @@ -23,15 +23,15 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: # The token isn't needed after checkout; cargo runs build scripts and proc macros from # dependencies, so don't leave it in .git/config for that third-party code to read. persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: clippy diff --git a/.github/workflows/doc.yml b/.github/workflows/doc.yml index a0c619c1e..6caa4f0ee 100644 --- a/.github/workflows/doc.yml +++ b/.github/workflows/doc.yml @@ -28,13 +28,13 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/docpath.yml b/.github/workflows/docpath.yml index 571b65eca..e0115f6f5 100644 --- a/.github/workflows/docpath.yml +++ b/.github/workflows/docpath.yml @@ -28,11 +28,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/ecproj-format.yml b/.github/workflows/ecproj-format.yml index 16bab05c7..24a3350af 100644 --- a/.github/workflows/ecproj-format.yml +++ b/.github/workflows/ecproj-format.yml @@ -28,13 +28,13 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/font-store.yml b/.github/workflows/font-store.yml index f246f621a..0578f18ec 100644 --- a/.github/workflows/font-store.yml +++ b/.github/workflows/font-store.yml @@ -28,11 +28,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index e19902e8c..84d2c0d7e 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -72,17 +72,17 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: Swatinem/rust-cache@v2.9.3 with: key: ${{ matrix.crate }} save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml index 5f717aeff..7e6903188 100644 --- a/.github/workflows/i18n.yml +++ b/.github/workflows/i18n.yml @@ -28,11 +28,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/jpeg.yml b/.github/workflows/jpeg.yml index 900baf678..21db0ab79 100644 --- a/.github/workflows/jpeg.yml +++ b/.github/workflows/jpeg.yml @@ -25,18 +25,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-jpeg save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index aba535265..41fcc0502 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -27,24 +27,24 @@ jobs: CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - name: Checkout test fonts - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@v7.0.1 with: repository: storytold/craft-fonts ref: b076417b5880bd4154bd22f00695b1d28c6bea83 path: .test-inputs/craft-fonts persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-keymap-linux save-if: ${{ github.ref == 'refs/heads/main' }} @@ -71,23 +71,23 @@ jobs: CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - name: Checkout test fonts - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@v7.0.1 with: repository: storytold/craft-fonts ref: b076417b5880bd4154bd22f00695b1d28c6bea83 path: .test-inputs/craft-fonts persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-keymap-${{ matrix.os }} save-if: ${{ github.ref == 'refs/heads/main' }} @@ -98,17 +98,17 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-keymap-wasm save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/lockfile.yml b/.github/workflows/lockfile.yml new file mode 100644 index 000000000..e630c9a8f --- /dev/null +++ b/.github/workflows/lockfile.yml @@ -0,0 +1,34 @@ +name: Lockfile + +# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin +# no longer verifies upstream, so a moved tag cannot slip a different commit into a run. +# Docs: https://gh.io/actions-lockfile +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +env: + GH_TOKEN: ${{ github.token }} + +jobs: + lockfile: + name: Lockfile is in sync + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Install gh-actions-lock + run: gh extension install github/gh-actions-lock --pin v0.4.1 + - name: Verify the lockfile + run: gh actions-lock --verify diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index cb3912d54..4814e35ca 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -25,18 +25,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-media-lint save-if: ${{ github.ref == 'refs/heads/main' }} @@ -56,16 +56,16 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-media-test save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/menu.yml b/.github/workflows/menu.yml index 6d0e082cb..8d1058731 100644 --- a/.github/workflows/menu.yml +++ b/.github/workflows/menu.yml @@ -21,14 +21,14 @@ jobs: name: Menu (Linux) runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy targets: aarch64-apple-darwin, wasm32-unknown-unknown - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: Swatinem/rust-cache@v2.9.3 with: key: craft-menu-linux - run: cargo fmt -p craft-menu --check diff --git a/.github/workflows/pcraft-format.yml b/.github/workflows/pcraft-format.yml index 177bb4593..9c66b5a10 100644 --- a/.github/workflows/pcraft-format.yml +++ b/.github/workflows/pcraft-format.yml @@ -28,13 +28,13 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" components: rustfmt, clippy diff --git a/.github/workflows/pdf.yml b/.github/workflows/pdf.yml index a494d085c..09ddfabca 100644 --- a/.github/workflows/pdf.yml +++ b/.github/workflows/pdf.yml @@ -31,19 +31,19 @@ jobs: RUSTFLAGS: --cfg craft_pdf_unicode_fixtures steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-pdf save-if: ${{ github.ref == 'refs/heads/main' }} - - uses: actions/setup-python@v7 + - uses: actions/setup-python@v7.1.0 with: python-version: "3.12" - name: Provision licensed PDF test fonts @@ -61,14 +61,14 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-pdf-backends save-if: ${{ github.ref == 'refs/heads/main' }} @@ -81,19 +81,19 @@ jobs: CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-pdf-wasm save-if: ${{ github.ref == 'refs/heads/main' }} - - uses: actions/setup-python@v7 + - uses: actions/setup-python@v7.1.0 with: python-version: "3.12" - name: Provision licensed PDF test fonts @@ -111,7 +111,7 @@ jobs: - name: Install the matching WASM test runner # A prebuilt, checksum-verified binary instead of building it from source on every run. # A version the pinned action does not list yet falls back to `cargo install --locked`. - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 + uses: step-security/taiki-e-install-action@v2.87.32 with: tool: wasm-bindgen@${{ steps.wasm-bindgen.outputs.version }} fallback: cargo-install @@ -122,19 +122,19 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-plate-test save-if: ${{ github.ref == 'refs/heads/main' }} - - uses: actions/setup-python@v7 + - uses: actions/setup-python@v7.1.0 with: python-version: "3.12" - name: Provision licensed PDF test fonts diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml index 3838e6c42..8e2108e09 100644 --- a/.github/workflows/print.yml +++ b/.github/workflows/print.yml @@ -24,11 +24,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/proof.yml b/.github/workflows/proof.yml index 0035b1c04..10365a230 100644 --- a/.github/workflows/proof.yml +++ b/.github/workflows/proof.yml @@ -25,27 +25,27 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false # The Language data (craft-i18n `language-data/`), embedded by crates/proof/build.rs. # Pinned to storytold/craft-i18n#114's head (#109's SCOWL dictionaries + judgment/judgement, # CP2.1); TODO(CP2.1): move to #114's merge commit once it merges. - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: repository: storytold/craft-i18n ref: c239f934ace90b7939afaceb23b472ceeafd6b8a path: craft-i18n persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-proof save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 0892f5a2c..f15ef6ddc 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -30,21 +30,21 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 - name: Install software Vulkan renderer if: runner.os == 'Linux' run: | sudo apt-get update sudo apt-get install -y mesa-vulkan-drivers libvulkan1 echo 'WGPU_BACKEND=vulkan' >> "$GITHUB_ENV" - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-ui save-if: ${{ github.ref == 'refs/heads/main' }} @@ -59,15 +59,15 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-ui-wasm save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index f9c8e1498..9a7139026 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -28,15 +28,15 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: # The token isn't needed after checkout; cargo runs build scripts and proc macros from # dependencies, so don't leave it in .git/config for that third-party code to read. persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/vectorcraft-format.yml b/.github/workflows/vectorcraft-format.yml index b2b20463a..74144f30f 100644 --- a/.github/workflows/vectorcraft-format.yml +++ b/.github/workflows/vectorcraft-format.yml @@ -28,13 +28,13 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" components: rustfmt, clippy diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index ec1c16eda..fa667bdfc 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -22,18 +22,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-video-lint - run: cargo fmt -p craft-video --check @@ -60,16 +60,16 @@ jobs: name: Video tests (${{ matrix.os }}) steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-video-${{ matrix.os }} - name: Install ffmpeg (Linux) diff --git a/.github/workflows/web-api.yml b/.github/workflows/web-api.yml index 2460fb569..4bf1a30fe 100644 --- a/.github/workflows/web-api.yml +++ b/.github/workflows/web-api.yml @@ -26,13 +26,13 @@ jobs: CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy @@ -46,7 +46,7 @@ jobs: - name: Install the matching WASM test runner # A prebuilt, checksum-verified binary instead of building it from source on every run. # A version the pinned action does not list yet falls back to `cargo install --locked`. - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 + uses: step-security/taiki-e-install-action@v2.87.32 with: tool: wasm-bindgen@${{ steps.wasm-bindgen.outputs.version }} fallback: cargo-install diff --git a/.github/workflows/web-host.yml b/.github/workflows/web-host.yml index b780ee76b..76e6701e5 100644 --- a/.github/workflows/web-host.yml +++ b/.github/workflows/web-host.yml @@ -27,18 +27,18 @@ jobs: CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-web-host save-if: ${{ github.ref == 'refs/heads/main' }} @@ -55,7 +55,7 @@ jobs: - name: Install the matching WASM test runner # A prebuilt, checksum-verified binary instead of building it from source on every run. # A version the pinned action does not list yet falls back to `cargo install --locked`. - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 + uses: step-security/taiki-e-install-action@v2.87.32 with: tool: wasm-bindgen@${{ steps.wasm-bindgen.outputs.version }} fallback: cargo-install diff --git a/.github/workflows/window.yml b/.github/workflows/window.yml index f570ef5ce..fdd28e203 100644 --- a/.github/workflows/window.yml +++ b/.github/workflows/window.yml @@ -28,15 +28,15 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: # The token isn't needed after checkout; cargo runs build scripts and proc macros from # dependencies, so don't leave it in .git/config for that third-party code to read. persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index a7a3bb587..20e947480 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -10,6 +10,14 @@ on: permissions: contents: read +concurrency: + # Pull requests share one group per branch, so a newer push cancels the older run. Every other + # run (push to main, a release tag, a manual run) gets a group of its own: it is neither + # cancelled nor replaced while queued, so a main run always finishes and saves the dependency + # cache, and a release run is never cancelled. + group: workspace-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: native: name: Workspace @@ -39,6 +47,7 @@ jobs: printf 'CRAFT_PSD_CORPUS=%s\n' "$GITHUB_WORKSPACE/$corpus_fetcher/corpus" >> "$GITHUB_ENV" printf 'CRAFT_PDF_TEST_FONT_DIR=%s\n' "$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" command: | + python3 scripts/test-workspace-concurrency.py cargo fmt --check cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 19d38973d..77d3578cb 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -6,6 +6,8 @@ author, source and license. Library code and original assets are under the repos | File | Author | Source | License | |---|---|---|---| +| `crates/smime/testdata/` | MailCraft contributors; RFC 9216 example certificates | [MailCraft at 240d1d42](https://github.com/UCS-Care-Group/mailcraft/tree/240d1d42fe394cf3274402b180663ba9b43ca180/crates/smime/testdata), restored unmodified; provenance in the directory README | MIT OR Apache-2.0 (source repository) | +| `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files | | `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 | | `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 | | `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | diff --git a/Cargo.lock b/Cargo.lock index 19754d8d4..8e12a6995 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,30 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "acadrust" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8923c99ea1f151cb7fc17ce2fc14f8b1e330fa22611e535602d985c0cc3c89a2" +dependencies = [ + "anyhow", + "bitflags 2.13.2", + "byteorder", + "encoding_rs", + "flate2", + "foldhash 0.2.0", + "indexmap", + "itoa", + "memmap2", + "nom 7.1.3", + "oem_cp", + "once_cell", + "rayon", + "ryu", + "thiserror 2.0.21", + "web-time", +] + [[package]] name = "accesskit" version = "0.25.1" @@ -198,6 +222,16 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "aotuv_lancer_vorbis_sys" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bc4fd1a61860d2f1198b60bedd30910eaffa978f1ee6214dfb24ac70d589225" +dependencies = [ + "cc", + "ogg_next_sys", +] + [[package]] name = "arbitrary" version = "1.5.0" @@ -267,6 +301,45 @@ dependencies = [ "libloading", ] +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -439,7 +512,7 @@ dependencies = [ "anyhow", "arrayvec", "log", - "nom", + "nom 8.0.0", "num-rational", "v_frame", ] @@ -530,6 +603,9 @@ name = "bit-vec" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] [[package]] name = "bit-vec" @@ -1059,7 +1135,7 @@ dependencies = [ "crmf", "der 0.7.10", "spki 0.7.3", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -1071,7 +1147,19 @@ dependencies = [ "const-oid 0.9.6", "der 0.7.10", "spki 0.7.3", - "x509-cert", + "x509-cert 0.2.5", +] + +[[package]] +name = "cms" +version = "0.3.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d089eddc8a5c984d82fcf1427367a6fa0d019d5af04b6e3197e86c8989533b8d" +dependencies = [ + "const-oid 0.10.3", + "der 0.8.3", + "spki 0.8.1", + "x509-cert 0.3.0", ] [[package]] @@ -1289,6 +1377,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-anicraft-format" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "craft-assuan" version = "0.1.0" @@ -1310,6 +1406,7 @@ version = "0.1.0" dependencies = [ "craft-media", "craft-media-testkit", + "craft-xml", "log", "proptest", "rayon", @@ -1317,8 +1414,13 @@ dependencies = [ "serde_json", "symphonia", "thiserror 2.0.21", + "vorbis_rs", ] +[[package]] +name = "craft-ber" +version = "0.1.0" + [[package]] name = "craft-captions" version = "0.1.0" @@ -1501,6 +1603,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-dwg" +version = "0.1.0" +dependencies = [ + "acadrust", + "log", +] + [[package]] name = "craft-dxf" version = "0.1.0" @@ -1601,12 +1711,32 @@ version = "0.1.0" dependencies = [ "craft-eps", "craft-idml", + "craft-image-codecs", + "craft-kra", + "craft-ora", + "craft-pcraft-bundle", + "craft-raw", "craft-svg", "craft-zip", "serde", "serde_json", ] +[[package]] +name = "craft-file-import" +version = "0.1.0" +dependencies = [ + "craft-dxf", + "craft-eps", + "craft-file-formats", + "craft-pdf 0.1.0", + "craft-raster-codecs", + "craft-svg", + "kurbo 0.13.1", + "thiserror 2.0.21", + "vectorcraft-geom", +] + [[package]] name = "craft-flags" version = "0.1.0" @@ -1709,6 +1839,7 @@ dependencies = [ name = "craft-gif" version = "0.1.0" dependencies = [ + "gif", "image", ] @@ -1785,20 +1916,27 @@ dependencies = [ name = "craft-image-codecs" version = "0.1.0" dependencies = [ + "avif-serialize", "craft-heif", "craft-jpeg", "craft-metadata", + "craft-video", + "crc32fast", "exr", "flate2", "half", + "hayro-jpeg2000", "image", "image-webp", "jpeg-encoder 0.6.1", "jxl-oxide", "png 0.18.1", "proptest", + "rav1e", + "ravif", "rayon", "serde_json", + "sha2 0.10.9", "thiserror 2.0.21", "tiff", "zune-core", @@ -1825,11 +1963,30 @@ dependencies = [ name = "craft-jpeg" version = "0.1.0" dependencies = [ + "jpeg-decoder", "jpeg-encoder 0.6.1", + "rayon", "thiserror 2.0.21", "zune-jpeg", ] +[[package]] +name = "craft-jsonrpc" +version = "0.1.0" +dependencies = [ + "serde_json", +] + +[[package]] +name = "craft-jxl" +version = "0.1.0" +dependencies = [ + "craft-cms", + "jixel", + "jxl-oxide", + "thiserror 2.0.21", +] + [[package]] name = "craft-keymap" version = "0.1.0" @@ -1876,6 +2033,7 @@ dependencies = [ name = "craft-lottie" version = "0.1.0" dependencies = [ + "craft-zip", "serde_json", "thiserror 2.0.21", ] @@ -1907,6 +2065,16 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-mcmat" +version = "0.1.0" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-media" version = "0.1.0" @@ -2094,6 +2262,7 @@ dependencies = [ name = "craft-pcraft-format" version = "0.1.0" dependencies = [ + "flate2", "serde", "serde_json", "thiserror 2.0.21", @@ -2107,6 +2276,7 @@ dependencies = [ "bytemuck", "chrono", "craft-stream-codecs", + "craft-svg", "flate2", "hayro", "hayro-cmap", @@ -2114,14 +2284,17 @@ dependencies = [ "hayro-syntax", "js-sys", "krilla", + "krilla-svg", "kurbo 0.13.1", "md-5 0.11.0", "proptest", + "roxmltree 0.21.2", "serde_json", "sha2 0.11.1", "stringprep", "thiserror 2.0.21", "ttf-parser", + "usvg 0.47.0", "wasm-bindgen", "wasm-bindgen-test", "zeroize", @@ -2287,6 +2460,28 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "craft-proto" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "log", + "proptest", + "zeroize", +] + +[[package]] +name = "craft-ps" +version = "0.1.0" +dependencies = [ + "craft-eps", + "kurbo 0.13.1", + "miniz_oxide 0.8.9", + "pdf-writer", + "skrifa 0.47.0", + "weezl 0.1.12", +] + [[package]] name = "craft-psd" version = "0.1.0" @@ -2420,6 +2615,37 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-smime" +version = "0.1.0" +dependencies = [ + "aes 0.9.4", + "base64 0.23.1", + "cbc", + "cms 0.3.0-rc.2", + "const-oid 0.10.3", + "craft-ber", + "der 0.8.3", + "des 0.9.0", + "hmac 0.13.0", + "p256 0.14.0", + "p384 0.14.0", + "pbkdf2", + "pkcs1 0.8.0", + "pkcs12", + "proptest", + "rcgen", + "ring", + "rsa 0.10.0-rc.18", + "serde", + "sha1 0.11.0", + "sha2 0.11.1", + "spki 0.8.1", + "thiserror 2.0.21", + "x509-cert 0.3.0", + "zeroize", +] + [[package]] name = "craft-stencilcraft-document" version = "0.1.0" @@ -2460,12 +2686,15 @@ version = "0.1.0" dependencies = [ "craft-image-codecs", "craft-xml", + "data-url", "flate2", "kurbo 0.13.1", "resvg 0.48.1", "roxmltree 0.21.2", "thiserror 2.0.21", "usvg 0.48.1", + "vectorcraft-geom", + "vectorcraft-pathops", ] [[package]] @@ -2490,6 +2719,14 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "craft-texture" +version = "0.1.0" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-tga" version = "0.1.0" @@ -2616,6 +2853,7 @@ version = "0.1.0" dependencies = [ "craft-media", "craft-media-testkit", + "rav1e", "rayon", "thiserror 2.0.21", ] @@ -2694,6 +2932,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xfl" +version = "0.1.0" +dependencies = [ + "craft-xml", + "miniz_oxide 0.8.9", + "thiserror 2.0.21", +] + [[package]] name = "craft-xls" version = "0.1.0" @@ -2722,6 +2969,7 @@ name = "craft-xml" version = "0.1.0" dependencies = [ "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] @@ -2763,10 +3011,10 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36fe21b96d5b87f5de4b5b7202ec41c00110ac817ce6728fe75fb2fe5962ed92" dependencies = [ - "cms", + "cms 0.2.3", "der 0.7.10", "spki 0.7.3", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -2990,6 +3238,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" @@ -3012,7 +3266,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "der_derive", + "der_derive 0.7.3", "flagset", "pem-rfc7468 0.7.0", "zeroize", @@ -3025,10 +3279,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ "const-oid 0.10.3", + "der_derive 0.8.0", + "flagset", "pem-rfc7468 1.0.0", "zeroize", ] +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + [[package]] name = "der_derive" version = "0.7.3" @@ -3040,6 +3310,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "der_derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "deranged" version = "0.5.9" @@ -3955,6 +4236,20 @@ dependencies = [ "roxmltree 0.20.0", ] +[[package]] +name = "fontdb" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser", +] + [[package]] name = "fontdb" version = "0.24.0" @@ -4489,7 +4784,7 @@ dependencies = [ "hayro-syntax", "kurbo 0.13.1", "moxcms", - "phf", + "phf 0.13.1", "rustc-hash 2.1.3", "siphasher", "skrifa 0.47.0", @@ -5169,6 +5464,12 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jixel" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "278a75e12caacec34be774d62ad05e45fc0b6a52d1f4e9f7fbc0209ecdf794f3" + [[package]] name = "jni" version = "0.22.4" @@ -5237,6 +5538,15 @@ dependencies = [ "libc", ] +[[package]] +name = "jpeg-decoder" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" +dependencies = [ + "rayon", +] + [[package]] name = "jpeg-encoder" version = "0.6.1" @@ -5535,6 +5845,22 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "krilla-svg" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1237d7c37b16ca9fbc2e72dde13a10d321f9a44aceee35c062bc0a43bfc7ce16" +dependencies = [ + "flate2", + "fontdb 0.23.0", + "krilla", + "resvg 0.47.0", + "skrifa 0.42.1", + "smallvec", + "tiny-skia 0.12.0", + "usvg 0.47.0", +] + [[package]] name = "kurbo" version = "0.11.3" @@ -5767,6 +6093,12 @@ dependencies = [ "walkdir", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -5955,6 +6287,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nom" version = "8.0.0" @@ -6425,6 +6767,33 @@ dependencies = [ "subtle", ] +[[package]] +name = "oem_cp" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7959d3349f484aec36462f98226983578bf7d33f9b034c32967489c7000e1f" +dependencies = [ + "phf 0.11.3", +] + +[[package]] +name = "ogg_next_sys" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2d7a48e247c2bb07e633aefb65a38648ea58c7eedd4e4408a5861721ab049b" +dependencies = [ + "cc", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -6754,7 +7123,7 @@ dependencies = [ "log", "md-5 0.10.6", "memchr", - "nom", + "nom 8.0.0", "num-bigint-dig", "num-traits", "num_enum", @@ -6780,6 +7149,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_shared 0.11.3", +] + [[package]] name = "phf" version = "0.13.1" @@ -6787,7 +7165,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ "phf_macros", - "phf_shared", + "phf_shared 0.13.1", ] [[package]] @@ -6797,7 +7175,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" dependencies = [ "fastrand", - "phf_shared", + "phf_shared 0.13.1", ] [[package]] @@ -6807,12 +7185,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" dependencies = [ "phf_generator", - "phf_shared", + "phf_shared 0.13.1", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.13.1" @@ -6896,6 +7283,21 @@ dependencies = [ "spki 0.8.1", ] +[[package]] +name = "pkcs12" +version = "0.2.0-rc.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fd993500a1de8a428a2e6cc9a2ec942c99a801a88d58a24fb986c5ad3b767ca" +dependencies = [ + "cms 0.3.0-rc.2", + "const-oid 0.10.3", + "der 0.8.3", + "digest 0.11.3", + "spki 0.8.1", + "x509-cert 0.3.0", + "zeroize", +] + [[package]] name = "pkcs8" version = "0.10.2" @@ -7525,6 +7927,19 @@ dependencies = [ "cipher 0.5.2", ] +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "read-fonts" version = "0.39.2" @@ -7699,6 +8114,23 @@ dependencies = [ "usvg 0.45.1", ] +[[package]] +name = "resvg" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9be183ad6a216aa96f33e4c8033b0988b8b3ea6fd2359d19af5bac4643fd8e81" +dependencies = [ + "gif", + "image-webp", + "log", + "pico-args", + "rgb", + "svgtypes 0.16.2", + "tiny-skia 0.12.0", + "usvg 0.47.0", + "zune-jpeg", +] + [[package]] name = "resvg" version = "0.48.1" @@ -7875,6 +8307,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + [[package]] name = "rustix" version = "0.38.44" @@ -8405,7 +8846,7 @@ dependencies = [ "spki 0.7.3", "thiserror 2.0.21", "tracing", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -8454,7 +8895,7 @@ dependencies = [ "sigstore-crypto", "sigstore-types", "thiserror 2.0.21", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -8467,7 +8908,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cmpv2", - "cms", + "cms 0.2.3", "const-oid 0.9.6", "der 0.7.10", "hex", @@ -8479,7 +8920,7 @@ dependencies = [ "sigstore-types", "thiserror 2.0.21", "tracing", - "x509-cert", + "x509-cert 0.2.5", "x509-tsp", ] @@ -8506,7 +8947,7 @@ checksum = "d30aff69036e4579b416956e9ba68cec45b793116f78f10842d04c7f8b924bab" dependencies = [ "base64 0.22.1", "chrono", - "cms", + "cms 0.2.3", "const-oid 0.9.6", "hex", "pem", @@ -8525,7 +8966,7 @@ dependencies = [ "thiserror 2.0.21", "tls_codec", "tracing", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -9076,6 +9517,17 @@ dependencies = [ "futures-core", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -9745,6 +10197,34 @@ dependencies = [ "xmlwriter", ] +[[package]] +name = "usvg" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d46cf96c5f498d36b7a9693bc6a7075c0bb9303189d61b2249b0dc3d309c07de" +dependencies = [ + "base64 0.22.1", + "data-url", + "flate2", + "fontdb 0.23.0", + "imagesize 0.14.0", + "kurbo 0.13.1", + "log", + "pico-args", + "roxmltree 0.21.2", + "rustybuzz", + "simplecss", + "siphasher", + "strict-num", + "svgtypes 0.16.2", + "tiny-skia-path 0.12.0", + "ttf-parser", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + [[package]] name = "usvg" version = "0.48.1" @@ -9753,7 +10233,7 @@ checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" dependencies = [ "base64 0.23.1", "data-url", - "fontdb", + "fontdb 0.24.0", "harfrust 0.12.0", "imagesize 0.15.0", "kurbo 0.13.1", @@ -10123,6 +10603,20 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vorbis_rs" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49c5da94d280f7a27e8c937e9b73df2da3e23a2583f48471fd8fb4c72f9c1933" +dependencies = [ + "aotuv_lancer_vorbis_sys", + "errno", + "getrandom 0.4.3", + "ogg_next_sys", + "thiserror 2.0.21", + "tinyvec", +] + [[package]] name = "wait-timeout" version = "0.2.1" @@ -10868,7 +11362,7 @@ dependencies = [ [[package]] name = "winprint" version = "0.2.1" -source = "git+https://github.com/storytold/winprint.rs?rev=72951d7455ebcab569fbd9386c513d3d9f53fb02#72951d7455ebcab569fbd9386c513d3d9f53fb02" +source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57" dependencies = [ "flate2", "fmt-derive", @@ -11039,6 +11533,35 @@ dependencies = [ "tls_codec", ] +[[package]] +name = "x509-cert" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b" +dependencies = [ + "const-oid 0.10.3", + "der 0.8.3", + "spki 0.8.1", +] + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + [[package]] name = "x509-tsp" version = "0.1.0" @@ -11046,7 +11569,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5ceece934a21607055b7ac5c25adb56a2ff559804b10705dc674d1d838c15e1" dependencies = [ "cmpv2", - "cms", + "cms 0.2.3", "der 0.7.10", ] @@ -11109,6 +11632,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec 0.9.1", + "time", +] + [[package]] name = "yeslogic-fontconfig-sys" version = "6.0.1" @@ -11140,7 +11673,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -11251,7 +11784,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 2e6114c8c..5d0bbbc66 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,14 +11,25 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-smime = { path = "crates/smime" } +craft-ber = { path = "crates/ber" } +craft-proto = { path = "crates/proto" } +acadrust = "=0.6.6" +log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-platform = { path = "crates/platform" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } craft-ai-core = { path = "crates/ai-core" } +craft-anicraft-format = { path = "crates/anicraft-format" } craft-pdf = { path = "crates/pdf", version = "=0.1.0" } +craft-ps = { path = "crates/ps", version = "=0.1.0" } craft-pdn = { path = "crates/pdn" } craft-plate-test = { path = "crates/plate-test" } +pdf-writer = "0.15" +miniz_oxide = "0.8" +weezl = "0.1" +skrifa = "0.47" krilla = { version = "=0.8.2", default-features = false, features = ["raster-images"] } hayro = { version = "=0.7.1", default-features = false } hayro-interpret = { version = "=0.7.0", default-features = false, features = ["embed-fonts", "embed-cmaps"] } @@ -40,16 +51,21 @@ craft-dialogs = { path = "crates/dialogs" } craft-doc-binary = { path = "crates/doc-binary" } craft-docx = { path = "crates/docx" } craft-document-bundle = { path = "crates/document-bundle" } +craft-mcmat = { path = "crates/mcmat" } craft-designcraft-format = { path = "crates/designcraft-format" } craft-dxf = { path = "crates/dxf" } craft-drawingml = { path = "crates/drawingml" } craft-eps = { path = "crates/eps" } craft-file-formats = { path = "crates/file-formats" } +craft-file-import = { path = "crates/file-import" } vectorcraft-doc = { git = "https://github.com/storytold/vectorcraft.git", rev = "6b3a6b8788ebcb420d69449199cbdf323888d27e" } vectorcraft-eps = { git = "https://github.com/storytold/vectorcraft.git", rev = "6b3a6b8788ebcb420d69449199cbdf323888d27e" } +vectorcraft-geom = { git = "https://github.com/storytold/vectorcraft.git", rev = "6b3a6b8788ebcb420d69449199cbdf323888d27e" } +vectorcraft-pathops = { git = "https://github.com/storytold/vectorcraft.git", rev = "6b3a6b8788ebcb420d69449199cbdf323888d27e" } craft-doc = { path = "crates/doc" } craft-docpath = { path = "crates/docpath" } craft-dpx = { path = "crates/dpx" } +craft-dwg = { path = "crates/dwg" } craft-ecproj-format = { path = "crates/ecproj-format" } craft-figma-rest = { path = "crates/figma-rest" } craft-exr = { path = "crates/exr" } @@ -73,15 +89,17 @@ craft-indd = { path = "crates/indd" } craft-jmap = { path = "crates/jmap" } craft-ical = { path = "crates/ical" } craft-jpeg = { path = "crates/jpeg" } +craft-jsonrpc = { path = "crates/jsonrpc" } +craft-jxl = { path = "crates/jxl" } craft-kiwi = { path = "crates/kiwi" } craft-keymap = { path = "crates/keymap" } craft-assuan = { path = "crates/assuan" } craft-kra = { path = "crates/kra" } craft-audio = { path = "crates/audio" } -# No default features, so craft-audio's `encode` builds craft-media without `isobmff`. craft-latex = { path = "crates/latex" } craft-markdown = { path = "crates/markdown" } craft-math = { path = "crates/math" } +# No default features: craft-audio turns on the craft-media modules each of its features needs. craft-media = { path = "crates/media", default-features = false } craft-materialx = { path = "crates/materialx" } craft-media-testkit = { path = "crates/media-testkit" } @@ -126,6 +144,7 @@ craft-stencilcraft-document = { path = "crates/stencilcraft-document" } craft-svg-paths = { path = "crates/svg-paths" } craft-stream-codecs = { path = "crates/stream-codecs" } craft-text = { path = "crates/text" } +craft-texture = { path = "crates/texture" } craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } craft-tiff = { path = "crates/tiff" } @@ -136,6 +155,7 @@ craft-vcard = { path = "crates/vcard" } craft-vectorcraft-format = { path = "crates/vectorcraft-format" } craft-vectordrawable = { path = "crates/vectordrawable" } craft-xls = { path = "crates/xls" } +craft-xfl = { path = "crates/xfl" } craft-wordmodel = { path = "crates/wordmodel" } craft-xlsx = { path = "crates/xlsx" } indd = { git = "https://github.com/storytold/indd-utils", rev = "7f3060e5bce78d21ea70e0d5eacb96edce15dfbe" } @@ -152,6 +172,8 @@ craft-web-host = { path = "crates/web-host" } craft-webp = { path = "crates/webp" } egui = { version = "0.37", default-features = false } md5 = { package = "md-5", version = "0.10", default-features = false } +jxl-oxide = { version = "0.12", default-features = false } +jixel = "=0.3.4" rayon = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/NOTICE b/NOTICE index 10e0fcc19..4fa5e4754 100644 --- a/NOTICE +++ b/NOTICE @@ -5,6 +5,17 @@ Licensed under the MIT License or the Apache License, Version 2.0, at your optio Third-party material +Optional DWG bridge + +`craft-dwg` uses `acadrust` 0.6.6 unmodified as a separate dependency for DWG reading and writing. +It is licensed under the Mozilla Public License 2.0. The license text and upstream third-party +notices are retained in `licenses/dwg/`; the crate is available from crates.io and +https://github.com/hakanaktt/acadrust. + +The byte-level bridge source was moved from CADCraft `crates/dwg` at revision +`664837df8925f932e90a7ae37c58d2f54e7a1320`. The bridge itself is MIT OR Apache-2.0; its only +MPL-2.0 component is the unmodified `acadrust` dependency. + This product bundles third-party material under its own licenses, listed below. The per-file list (author, source, license) is in ATTRIBUTION.md. @@ -243,9 +254,10 @@ applications retain their own document-font selection and licensing policy. linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in -vendor/linesweeper with its upstream license files and one local patch. 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 patch +vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_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 f6e0a4443..c6e95bd4f 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit pages and version detection, and written back; and `model`, the drawing above the tags (header variables, tables, blocks, layouts, entities) and its writer (R12 to 2018), merged from CADCraft's and VectorCraft's readers. Bounded on hostile input. Mapping the model onto a document stays in each app. +- [`craft-dwg`](crates/dwg/README.md): bounded byte-level DWG↔DXF conversion with diagnostics, + capped output and an optional child-process worker; the `acadrust` dependency remains isolated + behind bytes and is unavailable on wasm32 and FreeBSD/aarch64. - [`craft-ecproj-format`](crates/ecproj-format/README.md): the envelope of EffectCraft `.ecproj` project files: `savedBy`, the schema version and its check, and the file object with the project and its saved view as type parameters. The project model stays in EffectCraft. @@ -228,9 +231,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit sockets: session, requests of method calls with back-references, responses, ids, address templates, credentials and the judgement of HTTP answers, over any HTTP implementation. Bounded on hostile answers; what a program asks and makes of the answers stays in it. -- [`craft-jpeg`](crates/jpeg/README.md): clean-room decoder for 12-bit and arithmetic-coded - JPEG (T.81 SOF0/SOF1 at 12 bits, SOF9, SOF10), from PhotoCraft, and a frame probe for routing. - Metadata stays in each app. +- [`craft-jpeg`](crates/jpeg/README.md): clean-room JPEG decoder for 12-bit and arithmetic-coded + frames (T.81 SOF0/SOF1 at 12 bits, SOF9, SOF10), band decoding, and an optimized 8-bit baseline + encoder, from PhotoCraft; includes a frame probe for routing. Metadata interpretation stays in + each app. - [`craft-raster-codecs`](crates/raster-codecs/README.md): small raster formats, one module each, from PhotoCraft: DDS (BC1 to BC3, read and write), DICOM, FITS (read and write), IFF/ILBM (read and write), PCX, PNM/PAM/PFM (read and write) and XPM, into one flat image type. Bounded and @@ -344,6 +348,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`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). +- [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with + nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are + bounded by `Limits`. From MaterialCraft. - [`craft-ui`](crates/ui/README.md): SVG catalogs, icon buttons, tabs, pane controls, transactional docking, print settings and theme helpers for egui frontends; assets, themes, localization and command handling stay in each app. Requires Rust 1.95 or later. - [`craft-vcard`](crates/vcard/README.md): vCard contacts, from MailCraft: vCard 2.1, 3.0 and 4.0 read diff --git a/crates/anicraft-format/Cargo.toml b/crates/anicraft-format/Cargo.toml new file mode 100644 index 000000000..8dad7af33 --- /dev/null +++ b/crates/anicraft-format/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "craft-anicraft-format" +description = "Versioned JSON envelope codec for AniCraft native documents" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } + diff --git a/crates/anicraft-format/src/lib.rs b/crates/anicraft-format/src/lib.rs new file mode 100644 index 000000000..7cc5dc261 --- /dev/null +++ b/crates/anicraft-format/src/lib.rs @@ -0,0 +1,260 @@ +//! The versioned JSON envelope used by AniCraft's native project file. +//! +//! The app owns its document model and the path-table scope used while serializing it. This +//! crate owns the format envelope: field order, duplicate-field handling, and the point at which +//! the caller decodes the document relative to the `paths` field. +//! +//! [`read`] passes the actual nested Serde deserializer to the caller's [`PayloadDecoder`]. That +//! keeps payload parsing in the app's model crate while preserving the original stream order, +//! global JSON error locations, and path-table guard lifetime. + +use serde::{ + Serialize, + de::{Deserialize, DeserializeSeed, MapAccess, Visitor}, +}; +use std::{fmt, marker::PhantomData}; + +/// The native project envelope's identifying format string. +pub const FORMAT_NAME: &str = "anicraft"; +/// Current envelope version (v1 inline paths; v2 shared path table; v3 named scene timelines). +pub const FORMAT_VERSION: u32 = 3; +/// The largest native project file AniCraft accepts. +pub const MAX_FILE_BYTES: u64 = 1024 * 1024 * 1024; +/// Files below this size are pretty-printed for diffs and manual inspection. +pub const PRETTY_LIMIT: usize = 1024 * 1024; + +#[derive(Serialize)] +struct EnvelopeOut<'a, P, T> { + format: &'a str, + version: u32, + generator: &'a str, + paths: &'a [P], + document: &'a T, +} + +/// Serializes the envelope in its stable wire order and uses AniCraft's compact/pretty threshold. +pub fn write(generator: &str, paths: &[P], document: &T) -> Result { + let envelope = EnvelopeOut { format: FORMAT_NAME, version: FORMAT_VERSION, generator, paths, document }; + let compact = serde_json::to_string(&envelope)?; + if compact.len() < PRETTY_LIMIT { serde_json::to_string_pretty(&envelope) } else { Ok(compact) } +} + +/// Decodes one native-document payload under the path table that preceded it in the envelope. +pub trait PayloadDecoder

{ + type Document; + + fn decode<'de, D>(&mut self, deserializer: D, paths: Option>) -> Result + where + D: serde::Deserializer<'de>; +} + +/// The parsed top-level format, version and document payload. +#[derive(Debug, PartialEq)] +pub struct Envelope { + pub format: String, + pub version: u32, + /// Missing is distinct from JSON `null`, which the payload decoder decides whether to accept. + pub document: Option, +} + +struct DocumentSeed<'a, P, D> { + decoder: &'a mut D, + paths: Option>, +} + +impl<'de, P, D> DeserializeSeed<'de> for DocumentSeed<'_, P, D> +where + D: PayloadDecoder

, +{ + type Value = D::Document; + + fn deserialize(self, deserializer: De) -> Result + where + De: serde::Deserializer<'de>, + { + self.decoder.decode(deserializer, self.paths) + } +} + +struct EnvelopeSeed<'a, P, D> { + decoder: &'a mut D, + marker: PhantomData P>, +} + +impl<'de, P, D> DeserializeSeed<'de> for EnvelopeSeed<'_, P, D> +where + P: Deserialize<'de> + Clone, + D: PayloadDecoder

, +{ + type Value = Envelope; + + fn deserialize(self, deserializer: De) -> Result + where + De: serde::Deserializer<'de>, + { + struct EnvelopeVisitor<'a, P, D> { + decoder: &'a mut D, + marker: PhantomData P>, + } + + impl<'de, P, D> Visitor<'de> for EnvelopeVisitor<'_, P, D> + where + P: Deserialize<'de> + Clone, + D: PayloadDecoder

, + { + type Value = Envelope; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("an .anicraft envelope object") + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let (mut format, mut version, mut paths, mut document) = (None, None, None, None); + while let Some(key) = map.next_key::()? { + match key.as_str() { + "format" => format = Some(map.next_value::()?), + "version" => version = Some(map.next_value::()?), + "paths" => paths = Some(map.next_value::>()?), + "document" => { + document = Some(map.next_value_seed(DocumentSeed { decoder: self.decoder, paths: paths.clone() })?); + } + _ => { + map.next_value::()?; + } + } + } + Ok(Envelope { + format: format.ok_or_else(|| serde::de::Error::missing_field("format"))?, + version: version.ok_or_else(|| serde::de::Error::missing_field("version"))?, + document, + }) + } + } + + deserializer.deserialize_map(EnvelopeVisitor { decoder: self.decoder, marker: PhantomData }) + } +} + +/// Reads the envelope while delegating its typed document payload to `decoder`. +/// +/// Unknown top-level fields are ignored. Repeated recognized keys use the last successful value, +/// and each `document` is decoded immediately with the latest preceding `paths` field. A +/// malformed earlier `document` therefore errors before a later duplicate is considered, just as +/// it does with a streaming Serde visitor. +pub fn read<'de, P, D>(json: &'de str, decoder: &mut D) -> Result, serde_json::Error> +where + P: Deserialize<'de> + Clone, + D: PayloadDecoder

, +{ + let mut deserializer = serde_json::Deserializer::from_str(json); + let envelope = EnvelopeSeed { decoder, marker: PhantomData }.deserialize(&mut deserializer)?; + deserializer.end()?; + Ok(envelope) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde::Deserialize; + use serde_json::Value; + + #[derive(Debug, Deserialize, Serialize, PartialEq)] + struct Document { + value: u32, + } + + #[derive(Default)] + struct CaptureDocument { + calls: usize, + } + + impl PayloadDecoder for CaptureDocument { + type Document = (Document, Option>); + + fn decode<'de, D>(&mut self, deserializer: D, paths: Option>) -> Result + where + D: serde::Deserializer<'de>, + { + self.calls += 1; + Ok((Document::deserialize(deserializer)?, paths)) + } + } + + struct ValueDocument; + + impl PayloadDecoder for ValueDocument { + type Document = (Value, Option>); + + fn decode<'de, D>(&mut self, deserializer: D, paths: Option>) -> Result + where + D: serde::Deserializer<'de>, + { + Ok((Value::deserialize(deserializer)?, paths)) + } + } + + #[test] + fn writer_keeps_the_versioned_field_order_and_pretty_threshold() -> Result<(), Box> { + let paths = ["path-a", "path-b"]; + let document = Document { value: 3 }; + let json = write("AniCraft 0.1", &paths, &document)?; + let keys = ["\"format\"", "\"version\"", "\"generator\"", "\"paths\"", "\"document\""]; + let offsets: Vec = keys.iter().map(|key| json.find(key).unwrap_or(usize::MAX)).collect(); + assert!(offsets.windows(2).all(|pair| pair[0] < pair[1])); + assert!(json.contains("\n \"format\""), "small envelopes stay human-readable"); + assert!(json.contains("\"format\": \"anicraft\"")); + assert!(json.contains("\"version\": 3")); + Ok(()) + } + + #[test] + fn repeated_fields_and_paths_before_document_keep_streaming_semantics() -> Result<(), Box> { + let json = r#"{"format":"old","format":"anicraft","version":1,"paths":["first"],"paths":["chosen"],"document":{"value":7},"ignored":true}"#; + let mut decoder = CaptureDocument::default(); + let envelope = read::(json, &mut decoder)?; + assert_eq!(envelope.format, "anicraft"); + assert_eq!(envelope.version, 1); + assert_eq!(envelope.document, Some((Document { value: 7 }, Some(vec!["chosen".to_string()])))); + assert_eq!(decoder.calls, 1); + Ok(()) + } + + #[test] + fn paths_after_document_do_not_retroactively_change_its_scope() -> Result<(), Box> { + let json = r#"{"format":"anicraft","version":1,"document":{"value":1},"paths":["later"]}"#; + let mut decoder = ValueDocument; + let envelope = read::(json, &mut decoder)?; + assert_eq!(envelope.document, Some((serde_json::json!({"value":1}), None))); + Ok(()) + } + + #[test] + fn malformed_earlier_duplicate_document_stops_before_later_document() { + let json = r#"{"format":"anicraft","version":1,"document":null,"document":{"value":2}}"#; + let mut decoder = CaptureDocument::default(); + let result = read::(json, &mut decoder); + assert!(result.is_err()); + assert_eq!(decoder.calls, 1); + } + + #[test] + fn malformed_top_level_keeps_the_native_envelope_diagnostic() { + let mut decoder = CaptureDocument::default(); + let error = read::("[]", &mut decoder).unwrap_err(); + assert!(error.to_string().contains("expected an .anicraft envelope object")); + assert_eq!(decoder.calls, 0); + } + + #[test] + fn duplicate_documents_use_the_last_successful_value() -> Result<(), Box> { + let json = r#"{"format":"anicraft","version":1,"document":{"value":1},"document":{"value":2}}"#; + let mut decoder = CaptureDocument::default(); + let envelope = read::(json, &mut decoder)?; + assert_eq!(envelope.document, Some((Document { value: 2 }, None))); + assert_eq!(decoder.calls, 2); + Ok(()) + } +} diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 822c8a8ad..c411a0357 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-audio" -description = "Audio file I/O and codecs: WAV/AIFF read and write, FLAC encoder, AAC and ALAC decoders and encoders, AC-3/E-AC-3 decoder and encoder, MP3 decoder and encoder, Opus and MP1/MP2 decoders." +description = "Audio file I/O and codecs: WAV/AIFF read and write, FLAC encoder, AAC and ALAC decoders and encoders, AC-3/E-AC-3 decoder and encoder, MP3 decoder and encoder, Opus decoder and encoder, MP1/MP2 decoders." version.workspace = true edition.workspace = true license.workspace = true @@ -19,28 +19,34 @@ workspace = true # µ-law and free-format MP3 through symphonia. decode = ["decode-native", "symphonia"] # `decode` without symphonia: only the formats with a native decoder (others are Unsupported). -decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-decode", "mp3-decode", "craft-media/isobmff", "craft-media/matroska", "craft-media/ogg", "dep:log"] +decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-decode", "mp3-decode", "craft-media/isobmff", "craft-media/matroska", "craft-media/ogg", "dep:log", "dep:craft-xml"] # The symphonia fallback for the formats with no native decoder yet. symphonia = ["decode-native", "dep:symphonia"] -# Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3 and MP3 encoders. -encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode"] +# Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders. +# All but Opus are also file formats of `encode` and `FileEncoder`. +encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode", "vorbis-encode"] # Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files. lossless-encode = ["pcm-encode", "flac-encode"] # Encode WAV/BWF/RF64 and AIFF/AIFF-C files. pcm-encode = [] # Encode FLAC files. flac-encode = ["craft-media/bitstream"] +# Encode Ogg Vorbis files (desktop only: builds the reference libvorbis from its C sources). +vorbis-encode = ["dep:vorbis_rs"] # Codec modules on their own, for packet-level use. aac-decode = ["craft-media/bitstream"] -aac-encode = ["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 = [] +opus-encode = [] ac3-decode = ["craft-media/bitstream"] mpa-decode = ["craft-media/bitstream"] # MPEG-1/2 Layer III (MP3) decoder (`mp3::Decoder`). mp3-decode = ["mpa-decode"] -# ALAC packet decoder and encoder (`alac`), ported from Apple's reference implementation. +# ALAC packet decoder and encoder (`alac`), ported from Apple's reference implementation. The +# encoder also writes ALAC in M4A through `encode` and `FileEncoder`. alac-decode = [] -alac-encode = [] +alac-encode = ["craft-media/isobmff"] ac3-encode = ["craft-media/bitstream"] eac3-encode = ["craft-media/bitstream"] # MPEG-1/2 Layer III (MP3) encoder (`mp3`). @@ -54,6 +60,7 @@ serde = ["dep:serde", "craft-media/serde"] [dependencies] craft-media = { workspace = true } +craft-xml = { workspace = true, optional = true } thiserror = { workspace = true } serde = { workspace = true, optional = true } log = { version = "0.4", optional = true } @@ -61,6 +68,9 @@ rayon = { workspace = true, optional = true } # symphonia keeps its AAC decoder for AAC in CAF, a container craft-media does not read. symphonia = { version = "0.6.1", optional = true, default-features = false, features = ["mp3", "flac", "vorbis", "ogg", "wav", "pcm", "aiff", "isomp4", "aac", "alac", "adpcm", "caf", "mkv"] } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +vorbis_rs = { version = "0.5", optional = true } + [dev-dependencies] craft-media-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/audio/README.md b/crates/audio/README.md index abd3228f4..63251db8d 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -1,7 +1,8 @@ # craft-audio Audio file I/O and codecs for the Craft apps. Native implementations: WAV and AIFF read/write, -FLAC encoder, AAC and ALAC decoders/encoders, AC-3/E-AC-3 decoder/encoder, MP3 decoder/encoder, Opus and MP1/MP2 decoders. +FLAC encoder, AAC and ALAC decoders/encoders, AC-3/E-AC-3 decoder/encoder, MP3 decoder/encoder, Opus +decoder/encoder, MP1/MP2 decoders. Formats without a native decoder are decoded by [symphonia](#symphonia), which is to be replaced by native decoders. @@ -28,19 +29,19 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `decode` | `decode`, `probe`, `Decoder`, `tracks`, `TrackDecoder`; every format in [Format support](#format-support) | `decode-native`, `symphonia` | | `decode-native` | the same, native formats only (others are `Unsupported`); `wav_pcm`, `aiff_pcm` (a file's integer PCM bit for bit, as `RawPcm`) | the six decoders below, craft-media `isobmff`/`matroska`/`ogg`, `log` | | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | -| `encode` | every encoder: the WAV, AIFF and FLAC file writers, and the AAC, ALAC, AC-3/E-AC-3 and MP3 encoders | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode` | +| `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | | `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-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) | craft-media `bitstream` | +| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` | | `alac-decode` | `alac::Decoder` | none | -| `alac-encode` | `alac::Encoder` | none | -| `opus-decode` | `opus::Decoder`/`StreamDecoder` | none | +| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` | +| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none | | `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` | -| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder` | craft-media `bitstream` | +| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` | | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | | `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` | -| `mp3-encode` | `mp3::Encoder` | craft-media `bitstream` | +| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` | | `peaks` | `peaks::Peaks` | none | | `rayon` | parallel AAC encoding (with `aac-encode`) | `rayon` | | `serde` | `Serialize`/`Deserialize` on the shared types | `serde` | @@ -229,17 +230,86 @@ let wav = encode(&surround, &EncodeOptions::default().with_layout(ChannelLayout: let mut enc = FileEncoder::new(std::fs::File::create("take.wav")?, &EncodeOptions::default(), 48_000, 2)?; enc.write(&buf.channels, buf.frames())?; // one slice (or Vec) per channel enc.finish()?; + +// The coded formats go the same way: AAC in M4A at 192 kbit/s, 5.1 as E-AC-3, 16-bit ALAC. +let m4a = encode(&buf, &EncodeOptions::new(EncodeFormat::Aac).with_bitrate(192_000))?; +let eac3 = encode(&surround, &EncodeOptions::new(EncodeFormat::Eac3).with_layout(ChannelLayout::SURROUND_5_1_SIDE))?; +let alac = encode(&buf, &EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16))?; ``` `EncodeOptions::default()` is 24-bit WAV. `with_bwf` adds a BWF `bext` chunk and `with_force_rf64` writes RF64 below 4 GiB; both apply to WAV only. `encode_format_for("aiff")` -maps an extension to an `EncodeFormat`, and `ENCODE_EXTENSIONS` lists the extensions the enabled -features can write. `EncodeFormat::ALL` lists the formats; `extension()` is the extension a new -file gets and `mime_type()` its media type. `write` refuses a block without one slice per channel, or with a slice -shorter than `frames`, and writes nothing. After a write fails for another reason, every later +maps an extension to an `EncodeFormat` (`"m4a"` to AAC; `"alac"` names ALAC), and `ENCODE_EXTENSIONS` lists the extensions the enabled +features can write. `EncodeFormat::ALL` lists the formats and `is_built()` says whether this build +writes one; `extension()` is the extension a new file gets and `mime_type()` its media type. +`write` refuses a block without one slice per channel, or with a slice shorter than `frames`, and +writes nothing. After a write fails for another reason, every later `write` and `finish` returns an error. -### Encode AAC +| `EncodeFormat` | File | Audio | Options used | +|---|---|---|---| +| `Wav`, `Aiff`, `Flac` | WAV / BWF / RF64, AIFF / AIFF-C, FLAC | any rate; FLAC up to 8 channels | `bit_depth`, `dither`, `layout` (WAV, FLAC), `bwf`, `force_rf64` (WAV) | +| `Alac` | M4A | 1–8 channels, any rate | `bit_depth` (16, 24, 32), `dither`, `layout` | +| `Aac` | M4A | AAC-LC, 1–8 channels, the 13 AAC rates (7350–96000 Hz) | `rate_control`, `layout` | +| `Mp3` | `.mp3` stream | mono or stereo; 32, 44.1, 48 kHz or 16, 22.05, 24 kHz | `rate_control` (bit rate), `layout` | +| `Ac3`, `Eac3` | `.ac3` / `.eac3` stream | up to 5.1 (E-AC-3: 7.1); 32, 44.1, 48 kHz | `rate_control` (bit rate), `layout` | + +`with_bitrate(bits_per_second)` sets a constant bit rate for all channels together. A rate the +stream cannot carry is moved to the nearest one it can: MP3 and AC-3 use the highest rate of their +tables not above it, AAC and E-AC-3 keep it inside their range (AAC from 6 kbit/s or a quarter of +the sample rate per channel, whichever is more: from about half of that down the encoder codes +silence). `with_quality(0.0..=1.0)` is AAC's +constant quality (VBR); the other lossy formats return `Unsupported` for it. Without either, AAC +is written at 64 kbit/s per channel, MP3 at 96 kbit/s per channel, and AC-3 and E-AC-3 at +96 kbit/s per full-bandwidth channel (the LFE not counted). + +The audio is in WAV channel order for every format; `layout` (the usual layout for the channel +count when unset) names the speakers, and the channels are reordered into the codec's own order. +Each coded format has a fixed set of layouts, and audio with other speakers is `Unsupported` +rather than written to the wrong ones: + +- AAC: C; L R; L R C; L R C Cb; L R C Ls Rs; 5.1; 6.1; and for 8 channels L R C LFE Lb Rb Lc Rc + (a front pair left and right of centre, mask `0xFF`). ALAC: the same, with 6.1's back centre last. + WAV 7.1 (backs and sides) is not that 7.1, and quad (the usual 4-channel layout) has no centre: + both need another format. +- AC-3 and E-AC-3: the layout picks the coding mode (1/0 to 3/2, with or without LFE; E-AC-3 also + 7.1 with backs and sides). +- A surround pair is a surround pair: side and back surrounds are interchangeable where the format + has one pair. + +Before a file is created, the options and the format say what will happen: + +```rust +let opts = EncodeOptions::new(EncodeFormat::Ac3).with_layout(info.layout).with_bitrate(200_000); +opts.check(info.sample_rate, info.channels)?; // the error FileEncoder::new would return, nothing written +let bps = opts.bitrate(info.sample_rate, info.channels)?; // Some(192_000): the rate actually used; None when lossless or by quality + +EncodeFormat::Ac3.sample_rates(); // Some(&[32_000, 44_100, 48_000]); None when any rate will do +EncodeFormat::Ac3.max_channels(); // 6 +EncodeFormat::Ac3.fixed_layouts(3); // L R C, L R Cb, L R LFE; None for WAV, AIFF and FLAC (any layout) +EncodeFormat::Ac3.supports_layout(&info.layout); // one of those, sides and backs standing for each other +EncodeFormat::Ac3.supports_quality(); // false: AAC only +``` + +`FileEncoder::bitrate()` gives the rate of a file being written. The `EncodeFormat` queries answer +for a format whose feature is off too; `check` and `EncodeOptions::bitrate` (there with any +encoder feature) return `Unsupported` for it. + +The layout `decode` reports (`AudioInfo::layout`) can be passed to `with_layout` as it is. When a +coded format refuses it (2.1 or quad into AAC, a single channel tagged as left, channels with no +speaker assignment), the choices are another format, or audio rearranged into one of the layouts +above with that layout set; leaving `layout` unset declares the usual layout for the count. This +crate's decoder returns 7- and 8-channel AAC without a speaker assignment, in AAC order, so such a +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. + +### 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: ```rust use craft_audio::AudioError; @@ -264,6 +334,40 @@ Ls Rs) has no equivalent in that layout; passed unchanged, its channels go to th are a playable `.aac` file. To write MP4 or Matroska, pass the access units to craft-media's muxers ([MP4](../media/README.md#muxing), [Matroska](../media/README.md#muxing-1)). +### Encode Opus + +```rust +use craft_audio::opus::Encoder; + +let mut enc = Encoder::new(2, 128_000)?; // channels, bits per second +let frame_len = Encoder::FRAME_SIZE * 2; // 20 ms, interleaved stereo +let mut samples = buf.interleaved(); // 48 kHz audio +// Silence after the audio flushes the encoder's delay (the pre-skip) and fills the last frame. +let frames = samples.len() / 2 + enc.pre_skip() as usize; +samples.resize(frames.div_ceil(Encoder::FRAME_SIZE) * frame_len, 0.0); +let mut packets = Vec::new(); +for frame in samples.chunks_exact(frame_len) { + packets.push(enc.encode_float(frame)?); +} +let head = enc.opus_head(); // Matroska's CodecPrivate +let pre_skip = enc.pre_skip(); // samples the player drops at the start +``` + +The encoder takes 48 kHz only, and craft-audio has no resampler. + +craft-media has no Ogg muxer, so `.opus` files cannot be written yet; Opus goes into +Matroska/WebM or MP4: + +- **Matroska/WebM:** `head` is the track's `CodecPrivate`, and the pre-skip goes in + `TrackSpec::codec_delay_ns` (in nanoseconds at 48 kHz). The Matroska muxer cannot write + `DiscardPadding`, so the padding at the end stays in the file. +- **MP4:** the sample entry takes an `isobmff::OpusConfig` (`dOps`) with the same fields as the + `OpusHead`: channels, pre-skip, input rate, gain and mapping family. `TrackConfig::media_start` + set to the pre-skip skips it. To drop the padding as well, give `TrackConfig::edits` one + `Edit` instead, which replaces the edit `media_start` makes: `media_time` the pre-skip (track + timescale), `segment_duration` the audio's length (movie timescale), `media_rate` + `0x0001_0000`. + ### Waveform overviews ```rust @@ -308,14 +412,14 @@ match craft_audio::decode(&bytes, None) { | WAV, BWF, RF64/BW64 | native | native | | AIFF, AIFF-C | native | native | | FLAC | symphonia | native | -| AAC-LC | native | native | +| AAC-LC | native | native; M4A through `encode` / `FileEncoder`, packets through `aac::Encoder` | | HE-AAC v1 | native (SBR) | — | | HE-AAC v2 | native, without parametric stereo (see [Limits](#limits)) | — | -| ALAC | native | native, packets (`alac::Encoder`; no file writer) | +| ALAC | native | native; M4A through `encode` / `FileEncoder`, packets through `alac::Encoder` | | MP1, MP2 (MPEG audio Layer I/II) | native | — | -| MP3 (Layer III) | native | native, frames (`mp3::Encoder`; the frames in a row are an `.mp3` file) | -| Opus | native | — | -| AC-3, E-AC-3 | native | native packet encoder | +| MP3 (Layer III) | native | native; `.mp3` through `encode` / `FileEncoder`, frames through `mp3::Encoder` | +| Opus | native | native, packets (`opus::Encoder`; no file writer) | +| AC-3, E-AC-3 | native | native; `.ac3` / `.eac3` through `encode` / `FileEncoder`, packets through `ac3::encoder::Encoder` | | Vorbis, ADPCM, A-law, µ-law | symphonia | — | | Container | Demuxer | Timing | @@ -375,10 +479,26 @@ match craft_audio::decode(&bytes, None) { - `TrackDecoder` returns `Unsupported` for FLAC and Vorbis; `decode` and `Decoder` read those through symphonia. ALAC in CAF still goes through symphonia (craft-media has no CAF demuxer). -- ALAC: `EncodeFormat` has no ALAC entry; `alac::Encoder` writes packets and the configuration, - and the caller muxes them (MP4 `alac` box, Matroska `A_ALAC`). craft-media's MP4 muxer writes no - `chan` box, so an MP4 of more than two channels carries no explicit layout; decoders then use the - standard ALAC layout for the count. +- ALAC: craft-media's MP4 muxer writes no `chan` box, so an M4A of more than two channels (from + `EncodeFormat::Alac` or muxed from `alac::Encoder` packets) carries no explicit layout; decoders + then use the standard ALAC layout for the count, which is the one written. +- `EncodeFormat::Mp3`, `Ac3` and `Eac3` write raw streams, which cannot signal the codec's delay or + the length: the file decodes with 1057 (MP3) or 256 (AC-3, E-AC-3) frames of delay in front and + padded to whole frames at the end. MP3 gets no Xing / Info frame. `EncodeFormat::Aac` and `Alac` + (M4A) decode to the length written. +- An AAC M4A's length is in the edit list and the last packet's duration. This crate, Apple's + decoders and ffmpeg 9 end the audio there; ffmpeg 8 skips the priming but plays the last + packet's padding (under 1024 frames of near silence). +- `EncodeFormat::Aac` and `Alac` write the `moov` box after the audio (no fast start), and no + metadata. Raw ADTS AAC is not a file format of `encode`; `aac::EncoderConfig::with_adts` gives + the frames. +- This crate's file reader plays a raw E-AC-3 7.1 stream as its 5.1 independent substream. +- `EncodeFormat::Aac` with 8 channels is AAC channel configuration 7 (C, Lc Rc, L R, Ls Rs, LFE), + which Apple's decoders read as written. ffmpeg assumes such a stream is a mislabelled 7.1 with + backs and sides and moves the channels accordingly, unless run with `-strict 1`. +- A file with no audio: MP3, AC-3 and E-AC-3 are then zero bytes, which nothing can probe. An + empty AAC M4A (a track with no samples) is read by ffmpeg; this crate's native reader passes it + on, so `decode-native` alone refuses it and symphonia reads only some as zero frames. - ALAC 32-bit streams: ffmpeg does not decode their uncompressed (escaped) stereo frames, which Apple's encoder and this one write for audio that does not compress; Apple's decoder and this one do. @@ -415,7 +535,7 @@ Each codec module's rustdoc lists the coding tools it implements. | WAV, AIFF | Microsoft RIFF, Apple AIFF/AIFF-C | read: integer 8–32-bit, float 32/64-bit, `WAVE_FORMAT_EXTENSIBLE` masks, RF64/BW64, BWF `bext`, truncated files; write: 16/24/32-bit integer and 32-bit float, RF64 above 4 GiB, any layout, TPDF dither | round trips; hostile-input tests | | FLAC encoder | RFC 9639 | 16, 24, 32 bits; 1–8 channels, layouts decoders would not assume for the count as a `WAVEFORMATEXTENSIBLE_CHANNEL_MASK` comment; up to 655,350 Hz; LPC, stereo decorrelation, wasted bits, STREAMINFO MD5 | bit-exact through ffmpeg, STREAMINFO MD5 checked against ffmpeg | | AAC (`aac`) | ISO/IEC 14496-3; SBR tables from ETSI ES 201 980 Annex I | AAC-LC decode and encode (CBR, VBR, ADTS), 1–8 channels; HE-AAC (SBR) decode, see [Limits](#limits) | ffmpeg: ~135 dB SNR; PNS noise differs per sample at equal band energy. HE-AAC from AudioToolbox, 1–6 channels: same 962-sample delay as ffmpeg, ~54 dB SNR, high band level within 0.01 dB | -| Opus (`opus`) | RFC 6716, 8251, 7845 | decoder: SILK, hybrid, CELT, all frame sizes, PLC and FEC, multistream (`Decoder`) and single stream (`StreamDecoder`), 8–48 kHz output | all 36 RFC 8251 conformance cases | +| Opus (`opus`) | RFC 6716, 8251, 7845 | decoder: SILK, hybrid, CELT, all frame sizes, PLC and FEC, multistream (`Decoder`) and single stream (`StreamDecoder`), 8–48 kHz output; encoder (`Encoder`): SILK, hybrid, CELT, 48 kHz, 20 ms frames, mono or stereo | all 36 RFC 8251 conformance cases; encoder output through ffmpeg's two Opus decoders | | AC-3/E-AC-3 (`ac3`) | decoder: ATSC A/52:2012; encoder/programme API: ETSI TS 102 366 V1.4.1 | single-syncframe and complete-programme decoding; packet encoding through discrete 7.1 (see below) | decoder comparisons and encoder output through ffmpeg, CRC/channel/timing/bit-budget regressions; synthetic quality limitations below | | MP1/MP2 (`mpa`) | ISO/IEC 11172-3, 13818-3 | Layer I and II, MPEG-1/2/2.5, 8–48 kHz; also the Layer II rate/mode pairs the spec disallows (ffmpeg's default mono 384 kbit/s); no free format | ffmpeg-encoded streams, 73–84 dB SNR | | 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) | @@ -446,7 +566,7 @@ finite count as silence and the rest are clamped to ±4, so no input makes an in decoder's 7680-bit input buffer. - Not yet: block switching (short blocks; transients pre-echo), `scfsi` and `preflag`, intensity stereo, a tonality-aware model, VBR/ABR, the Xing/Info and LAME gapless tags (the delay is not - signalled), CRC, free format, and an `EncodeFormat` entry for `encode`/`FileEncoder`. + signalled), CRC and free format. ### AC-3 and E-AC-3 encoding @@ -583,6 +703,7 @@ the full tests with ffmpeg and the vectors required. | MP3 decoder | written here, from ISO/IEC 11172-3 and 13818-3; shares the encoder's tables and the MP1/MP2 synthesis filter | | MP3 encoder | FilmCraft `filmcraft-mp3enc` [4bec22b](https://github.com/storytold/filmcraft/commit/4bec22bd03bd1d995c9cf72e02a284f96d3d72cd) | | ALAC | Apple's reference implementation [macosforge/alac@c38887c](https://github.com/macosforge/alac/tree/c38887c5c5e64a4b31108733bd79ca9b2496d987/codec), Copyright © 2011 Apple Inc., Apache-2.0; ported to Rust and modified (see the `alac` module docs and [NOTICE](../../NOTICE)) | +| Opus encoder | EffectCraft `effectcraft-opusenc` [c618429](https://github.com/storytold/effectcraft/commit/c618429252587525a2a6d4b5bccbe4ec5261e1b9) | Where apps had overlapping implementations, the one that measured better was kept, with the tests of both: @@ -599,7 +720,8 @@ For the apps switching from their own code; to be removed once all three have sw The codec modules' public items keep their names, so apps can re-export them (`pub use craft_audio::aac::*;`). Names kept only for that are `#[doc(hidden)]`: -`ac3::Decoded` (now `ac3::Frame`), `aac::Upsample2x`, `aac::ProgramConfig::parse`, +`ac3::Decoded` (now `ac3::Frame`), `opus::encoder::OpusEncoder` (now `opus::Encoder`), +`aac::Upsample2x`, `aac::ProgramConfig::parse`, `aac::config_layout` and `aac::sample_rate_index`. What else an app adjusts: - `AudioInfo` has `container`, `codec`, `layout` and `damaged` instead of SoundCraft's `format`. @@ -625,8 +747,10 @@ The codec modules' public items keep their names, so apps can re-export them - `TrackInfo::sample_rate` and `channels` are `Option`s. - Features are per codec. SoundCraft's `encode` (WAV, AIFF, FLAC) is now `lossless-encode`, made of `pcm-encode` (WAV, AIFF) and `flac-encode`. `encode` turns on every encoder, including AAC, - ALAC and AC-3/E-AC-3. Writing a format whose feature is off returns `AudioError::Unsupported`. + ALAC, AC-3/E-AC-3 and Opus. Writing a format whose feature is off returns `AudioError::Unsupported`. - AAC encoder settings it cannot use are `aac::Error::InvalidSettings` (`AudioError::Encode`). +- The Opus encoder's constructors and `encode_float` return `Result` instead of panicking on an + invalid channel count, mode/bandwidth or frame length. - `TrackDecoder::decode` returns an error for a corrupt Opus packet, as for the other codecs; call `conceal`. - `FileEncoder::write` takes any per-channel slices, but refuses a block with missing channels or @@ -637,3 +761,8 @@ The codec modules' public items keep their names, so apps can re-export them CAF. MP4 and Matroska files decode to presentation length. A packet that fails is concealed, not dropped. A failed source read is `AudioError::Io`. + +WAV timestamps use `bext` when present, including a zero timestamp. Otherwise a bounded iXML +`BWFXML/BEXT` time reference supplies the timestamp (two unsigned 32-bit words; an omitted high +word is zero). Only the first iXML chunk is considered. Invalid or oversized optional XML is +ignored without rejecting the audio. This works for byte-backed and streaming sources. diff --git a/crates/audio/examples/encode.rs b/crates/audio/examples/encode.rs index 28de0f5ad..51cdecc84 100644 --- a/crates/audio/examples/encode.rs +++ b/crates/audio/examples/encode.rs @@ -1,4 +1,4 @@ -//! Write a tone as WAV and FLAC, whole and streamed, and as AAC packets. +//! Write a tone as WAV, FLAC and AAC in M4A, whole and streamed, and as AAC packets. //! //! `cargo run -p craft-audio --example encode --features lossless-encode,aac-encode -- out` @@ -28,7 +28,11 @@ fn main() -> Result<(), Box> { } enc.finish()?; - // AAC packets for an MP4 or Matroska muxer, with the configuration its sample entry needs. + // AAC in M4A at 160 kbit/s: the same call, with a bit rate in place of a bit depth. + let m4a = encode(&stereo, &EncodeOptions::new(EncodeFormat::Aac).with_bitrate(160_000))?; + std::fs::write(dir.join("tone.m4a"), m4a)?; + + // AAC packets for a muxer of your own, with the configuration its sample entry needs. let mut aac = craft_audio::aac::Encoder::new(craft_audio::aac::EncoderConfig::cbr(rate as u32, 2, 128_000))?; let mut units = aac.encode(&[&tone, &tone]); units.extend(aac.flush()); diff --git a/crates/audio/src/aac/encoder/mod.rs b/crates/audio/src/aac/encoder/mod.rs index 5a0ea5ac8..c641b790b 100644 --- a/crates/audio/src/aac/encoder/mod.rs +++ b/crates/audio/src/aac/encoder/mod.rs @@ -162,6 +162,16 @@ const HISTORY: usize = 2048; /// Bits per channel in a silent frame, rounded up: the smallest frame the encoder writes. const MIN_FRAME_BITS_PER_CHANNEL: u64 = 48; +/// The lowest and highest constant bit rate (bits per second) [`Encoder::new`] accepts for a +/// stream without ADTS headers: at least 1 kbit/s per channel and a silent frame, at most the +/// 6144 bits per channel and frame of the decoder buffer. +pub(crate) fn cbr_range(sample_rate: u32, channels: usize) -> (u32, u32) { + let (rate, channels) = (u64::from(sample_rate), channels as u64); + let silent = (MIN_FRAME_BITS_PER_CHANNEL * channels * rate).div_ceil(FRAME_LEN as u64); + let most = 6144 * channels * rate / FRAME_LEN as u64; + (u32::try_from(silent.max(1000 * channels)).unwrap_or(u32::MAX), u32::try_from(most).unwrap_or(u32::MAX)) +} + /// AAC-LC encoder. pub struct Encoder { cfg: EncoderConfig, diff --git a/crates/audio/src/aac/mod.rs b/crates/audio/src/aac/mod.rs index 297aa7972..f423a4e22 100644 --- a/crates/audio/src/aac/mod.rs +++ b/crates/audio/src/aac/mod.rs @@ -64,6 +64,8 @@ pub use config::{AdtsHeader, AudioSpecificConfig, ElementType, ProgramConfig, co #[cfg(feature = "aac-decode")] pub use decoder::Decoder; #[cfg(feature = "aac-encode")] +pub(crate) use encoder::cbr_range; +#[cfg(feature = "aac-encode")] pub use encoder::{BitrateMode, Encoder, EncoderConfig, EncoderStats}; #[cfg(feature = "aac-decode")] pub use latm::{LatmConfig, latm_config, latm_split}; diff --git a/crates/audio/src/ac3/mod.rs b/crates/audio/src/ac3/mod.rs index a8e8920d2..6bb19df8d 100644 --- a/crates/audio/src/ac3/mod.rs +++ b/crates/audio/src/ac3/mod.rs @@ -61,7 +61,7 @@ pub enum Error { pub type Result = std::result::Result; /// Data rate in kb/s by frmsizecod / 2 (Table 5.18). -const BITRATES: [u32; 19] = [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640]; +pub(crate) const BITRATES: [u32; 19] = [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640]; /// Full-bandwidth channels per acmod (Table 5.8). const NFCHANS: [usize; 8] = [2, 1, 2, 3, 3, 4, 4, 5]; diff --git a/crates/audio/src/layout.rs b/crates/audio/src/layout.rs index f3cab1b7f..d0c5ae39e 100644 --- a/crates/audio/src/layout.rs +++ b/crates/audio/src/layout.rs @@ -283,6 +283,40 @@ pub(crate) fn flac_assumed_mask(channels: usize) -> u32 { } } +/// The surround speaker a layout may name in place of `speaker`: formats with one surround pair +/// do not tell side from back, so a pair of either kind feeds it. +fn surround_twin(speaker: Speaker) -> Option { + Some(match speaker { + Speaker::SideLeft => Speaker::BackLeft, + Speaker::SideRight => Speaker::BackRight, + Speaker::BackLeft => Speaker::SideLeft, + Speaker::BackRight => Speaker::SideRight, + _ => return None, + }) +} + +/// How audio with `layout` feeds a format whose layout for the channel count is `mask`: for each +/// channel the format takes, the channel of the audio that feeds it. `order` is the format's +/// channel order over `mask` (for each of its channels, the WAV-order channel of `mask`; `None` +/// when it takes WAV order). `None` when `layout` is not the format's layout: it is unordered, or +/// has a speaker the format has not. +pub(crate) fn channel_map(mask: u32, order: Option<&[usize]>, layout: &ChannelLayout) -> Option> { + let speakers = ChannelLayout::from_mask(mask).speakers(); + if speakers.len() != usize::from(layout.channels()) { + return None; + } + let mut map = Vec::with_capacity(speakers.len()); + for j in 0..speakers.len() { + let speaker = *speakers.get(order.and_then(|o| o.get(j).copied()).unwrap_or(j))?; + let at = layout.index_of(speaker).or_else(|| surround_twin(speaker).and_then(|t| layout.index_of(t)))?; + if map.contains(&at) { + return None; + } + map.push(at); + } + Some(map) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 3ed684245..33dcdee3b 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -16,17 +16,18 @@ //! - [`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`]) and FLAC (feature `flac-encode`), whole-buffer or incremental into -//! any `Write + Seek`. Feature `lossless-encode` turns on both; feature `encode` turns on -//! `lossless-encode` and every codec's encoder. +//! 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 +//! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder. //! - [`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. //! - [`peaks`] (feature `peaks`): min/max/RMS pyramid for waveform drawing. //! - Codec modules for packet-level use, each with its own features: [`aac`] (`aac-decode`, -//! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`), [`ac3`] -//! (`ac3-decode`), [`mpa`] (`mpa-decode`), [`mp3`] (`mp3-decode`, `mp3-encode`), -//! [`flac`] (`flac-encode`: the packet encoder). +//! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`, and +//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`), [`mp3`] +//! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-encode`: the packet encoder). //! //! The shared types below build with no features. @@ -42,7 +43,7 @@ mod layout; pub mod mp3; #[cfg(feature = "mpa-decode")] pub mod mpa; -#[cfg(feature = "opus-decode")] +#[cfg(any(feature = "opus-decode", feature = "opus-encode"))] pub mod opus; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] mod pcm; @@ -54,8 +55,19 @@ mod read; mod track; #[cfg(any(feature = "decode-native", feature = "pcm-encode"))] mod wav; -#[cfg(any(feature = "pcm-encode", feature = "flac-encode"))] +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "vorbis-encode" +))] mod write; +#[cfg(feature = "vorbis-encode")] +pub use write::{OGG_BITRATES, encode_ogg}; /// The FLAC packet encoder (RFC 9639), for a caller that muxes FLAC itself (into MP4, Matroska or /// its own `.flac` writer): planar integer samples in, frames out, and the STREAMINFO to patch in @@ -98,10 +110,29 @@ pub use read::{ pub use read::{RawPcm, aiff_pcm, wav_pcm}; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + 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"))] -pub use write::{ENCODE_EXTENSIONS, FileEncoder, encode, encode_format_for}; +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "vorbis-encode" +))] +pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; @@ -207,8 +238,16 @@ impl From for AudioError { } } +#[cfg(feature = "opus-encode")] +impl From for AudioError { + fn from(e: opus::encoder::Error) -> Self { + AudioError::Encode(e.to_string()) + } +} + /// The file formats [`encode`] writes. Each needs its feature: WAV and AIFF `pcm-encode`, FLAC -/// `flac-encode`; asking for one that is not built returns [`AudioError::Unsupported`]. +/// `flac-encode`, AAC `aac-encode`, ALAC `alac-encode`, MP3 `mp3-encode`, AC-3 `ac3-encode` and +/// E-AC-3 `eac3-encode`; asking for one that is not built returns [`AudioError::Unsupported`]. #[non_exhaustive] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -219,20 +258,50 @@ pub enum EncodeFormat { Aiff, /// FLAC (integer depths). Flac, + /// AAC-LC in an M4A (MP4) file, 1–8 channels at one of the 13 AAC sample rates. The edit list + /// skips the encoder's priming and ends at the last frame, so the file decodes to the length + /// that was written. + Aac, + /// Apple Lossless in an M4A (MP4) file (integer depths), 1–8 channels. + Alac, + /// An MP3 stream: mono or stereo at 32, 44.1 or 48 kHz, or 16, 22.05 or 24 kHz. + Mp3, + /// An AC-3 stream: up to 5.1 at 32, 44.1 or 48 kHz. + Ac3, + /// An E-AC-3 stream: up to 7.1 at 32, 44.1 or 48 kHz. + Eac3, + /// Ogg Vorbis, whole-buffer encoding only. + Ogg, } impl EncodeFormat { /// Every format, in the order menus list them. Whether [`encode`] writes one depends on its - /// feature. - pub const ALL: &[EncodeFormat] = &[EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac]; + /// feature ([`EncodeFormat::is_built`]). + pub const ALL: &[EncodeFormat] = &[ + EncodeFormat::Wav, + EncodeFormat::Aiff, + EncodeFormat::Flac, + EncodeFormat::Alac, + EncodeFormat::Aac, + EncodeFormat::Mp3, + EncodeFormat::Ac3, + EncodeFormat::Eac3, + EncodeFormat::Ogg, + ]; /// The extension a new file of this format gets, lower case and without the dot: `"wav"`, - /// `"aif"`, `"flac"`. [`encode_format_for`] maps it back. + /// `"aif"`, `"flac"`, `"m4a"` (AAC and ALAC), `"mp3"`, `"ac3"`, `"eac3"`. + /// [`encode_format_for`] maps it back, `"m4a"` to AAC. pub fn extension(self) -> &'static str { match self { EncodeFormat::Wav => "wav", EncodeFormat::Aiff => "aif", EncodeFormat::Flac => "flac", + EncodeFormat::Aac | EncodeFormat::Alac => "m4a", + EncodeFormat::Mp3 => "mp3", + EncodeFormat::Ac3 => "ac3", + EncodeFormat::Eac3 => "eac3", + EncodeFormat::Ogg => "ogg", } } @@ -242,6 +311,11 @@ impl EncodeFormat { EncodeFormat::Wav => "audio/wav", EncodeFormat::Aiff => "audio/aiff", EncodeFormat::Flac => "audio/flac", + EncodeFormat::Aac | EncodeFormat::Alac => "audio/mp4", + EncodeFormat::Mp3 => "audio/mpeg", + EncodeFormat::Ac3 => "audio/ac3", + EncodeFormat::Eac3 => "audio/eac3", + EncodeFormat::Ogg => "audio/ogg", } } @@ -251,8 +325,159 @@ impl EncodeFormat { EncodeFormat::Wav => Container::Wav, EncodeFormat::Aiff => Container::Aiff, EncodeFormat::Flac => Container::Flac, + EncodeFormat::Aac | EncodeFormat::Alac => Container::Mp4, + EncodeFormat::Mp3 => Container::MpegAudio, + EncodeFormat::Ac3 | EncodeFormat::Eac3 => Container::Ac3, + EncodeFormat::Ogg => Container::Ogg, } } + + /// The codec of the audio this format writes. + pub fn codec(self) -> CodecId { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff => CodecId::Pcm, + EncodeFormat::Flac => CodecId::Flac, + EncodeFormat::Aac => CodecId::Aac, + EncodeFormat::Alac => CodecId::Alac, + EncodeFormat::Mp3 => CodecId::Mp3, + EncodeFormat::Ac3 => CodecId::Ac3, + EncodeFormat::Eac3 => CodecId::Eac3, + EncodeFormat::Ogg => CodecId::Vorbis, + } + } + + /// The feature that builds this format's writer. + pub fn feature(self) -> &'static str { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff => "pcm-encode", + EncodeFormat::Flac => "flac-encode", + EncodeFormat::Aac => "aac-encode", + EncodeFormat::Alac => "alac-encode", + EncodeFormat::Mp3 => "mp3-encode", + EncodeFormat::Ac3 => "ac3-encode", + EncodeFormat::Eac3 => "eac3-encode", + EncodeFormat::Ogg => "vorbis-encode", + } + } + + /// Whether [`encode`] writes this format in this build (its + /// [`feature`](Self::feature) is on): what to filter [`EncodeFormat::ALL`] by for a menu. + pub fn is_built(self) -> bool { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff => cfg!(feature = "pcm-encode"), + EncodeFormat::Flac => cfg!(feature = "flac-encode"), + EncodeFormat::Aac => cfg!(feature = "aac-encode"), + EncodeFormat::Alac => cfg!(feature = "alac-encode"), + EncodeFormat::Mp3 => cfg!(feature = "mp3-encode"), + EncodeFormat::Ac3 => cfg!(feature = "ac3-encode"), + EncodeFormat::Eac3 => cfg!(feature = "eac3-encode"), + EncodeFormat::Ogg => cfg!(all(feature = "vorbis-encode", not(target_arch = "wasm32"))), + } + } + + /// The sample rates the format takes, ascending, or `None` when it has no fixed list (WAV, + /// AIFF, FLAC and ALAC take any rate their headers can hold). + pub fn sample_rates(self) -> Option<&'static [u32]> { + match self { + EncodeFormat::Aac => Some(&[7350, 8000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000, 64_000, 88_200, 96_000]), + EncodeFormat::Mp3 => Some(&[16_000, 22_050, 24_000, 32_000, 44_100, 48_000]), + EncodeFormat::Ac3 | EncodeFormat::Eac3 => Some(&[32_000, 44_100, 48_000]), + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac | EncodeFormat::Alac | EncodeFormat::Ogg => None, + } + } + + /// The most channels a file of this format holds. A WAV's frame size is a 16-bit field, so it + /// holds 65535 / bytes per sample: 32767 at 16 bits (the count given here), 21845 at 24 and + /// 16383 at 32; [`EncodeOptions::check`] answers for the depth chosen. + pub fn max_channels(self) -> u16 { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff => 32_767, + EncodeFormat::Flac | EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Eac3 => 8, + EncodeFormat::Ac3 => 6, + EncodeFormat::Mp3 | EncodeFormat::Ogg => 2, + } + } + + /// The speaker layouts of a format that has a fixed set of them, as WAV masks, for a channel + /// count: one each for AAC, ALAC and MP3, one per coding mode for AC-3 and E-AC-3. Empty for a + /// count the format has not, and for WAV, AIFF and FLAC, which have no such set. + pub(crate) fn layout_masks(self, channels: u16) -> &'static [u32] { + let per_count: &[&[u32]] = match self { + // Channel configurations 1–6, the 6.1 program config element, and configuration 7 + // (7.1 with a front pair left and right of centre). + EncodeFormat::Aac => &[&[0x4], &[0x3], &[0x7], &[0x107], &[0x607], &[0x60F], &[0x70F], &[0xFF]], + // Apple's layout tags for 1–8 channels, surrounds as back speakers. + EncodeFormat::Alac => &[&[0x4], &[0x3], &[0x7], &[0x107], &[0x37], &[0x3F], &[0x13F], &[0xFF]], + EncodeFormat::Mp3 | EncodeFormat::Ogg => &[&[0x4], &[0x3]], + // The coding modes 1/0 to 3/2 with and without an LFE, by channel count. + EncodeFormat::Ac3 => &[&[0x4], &[0x3, 0xC], &[0x7, 0x103, 0xB], &[0x107, 0x603, 0xF, 0x10B], &[0x607, 0x10F, 0x60B], &[0x60F]], + // The same, and 7.1 with backs and sides. + EncodeFormat::Eac3 => { + &[&[0x4], &[0x3, 0xC], &[0x7, 0x103, 0xB], &[0x107, 0x603, 0xF, 0x10B], &[0x607, 0x10F, 0x60B], &[0x60F], &[], &[0x63F]] + } + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac => &[], + }; + usize::from(channels).checked_sub(1).and_then(|i| per_count.get(i)).copied().unwrap_or_default() + } + + /// The speaker layouts a format with a fixed set of them has for `channels` channels: one for + /// AAC, ALAC and MP3, one per coding mode for AC-3 and E-AC-3; empty when the format cannot + /// hold that many channels. `None` for WAV, AIFF and FLAC, which take any layout. Audio in + /// another layout has to be rearranged into one of these before it is written. + /// + /// ``` + /// use craft_audio::{ChannelLayout, EncodeFormat}; + /// + /// assert_eq!(EncodeFormat::Aac.fixed_layouts(6), Some(vec![ChannelLayout::SURROUND_5_1_SIDE])); + /// assert_eq!(EncodeFormat::Mp3.fixed_layouts(6), Some(vec![])); + /// assert_eq!(EncodeFormat::Wav.fixed_layouts(6), None); + /// ``` + pub fn fixed_layouts(self, channels: u16) -> Option> { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac => None, + _ => Some(self.layout_masks(channels).iter().map(|&mask| ChannelLayout::from_mask(mask)).collect()), + } + } + + /// Whether the format holds audio with `layout`: for WAV, AIFF and FLAC any layout of up to + /// [`max_channels`](Self::max_channels) channels, for the others one of + /// [`fixed_layouts`](Self::fixed_layouts), where side and back surrounds stand for each other + /// in a layout with one surround pair. + pub fn supports_layout(self, layout: &ChannelLayout) -> bool { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac => (1..=self.max_channels()).contains(&layout.channels()), + _ => self.layout_masks(layout.channels()).iter().any(|&mask| layout::channel_map(mask, None, layout).is_some()), + } + } + + /// Whether the format takes [`RateControl::Quality`]: AAC. The other lossy formats are + /// written at a constant bit rate only. + pub fn supports_quality(self) -> bool { + self == EncodeFormat::Aac + } + + /// Whether the format loses audio: AAC, MP3, AC-3 and E-AC-3. These take + /// [`EncodeOptions::rate_control`] and ignore the bit depth and dither. + pub fn is_lossy(self) -> bool { + matches!(self, EncodeFormat::Aac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 | EncodeFormat::Ogg) + } +} + +/// How a lossy format spends bits ([`EncodeOptions::rate_control`]). +#[non_exhaustive] +#[derive(Debug, Clone, Copy, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum RateControl { + /// A constant bit rate in bits per second, for all channels together. A format with a fixed + /// set of rates (MP3, AC-3) uses the highest one not above it; a rate outside what the + /// stream can carry is moved to the nearest one inside. AAC is written at 6 kbit/s or a + /// quarter of the sample rate per channel at least: from about half of that down its encoder + /// codes silence. Vorbis treats this as a VBR target (64–500 kbit/s), falling back to + /// a quality preset when that target is unsupported; it does not promise a constant bitrate. + Bitrate(u32), + /// A constant quality from 0.0 (smallest) to 1.0 (best), at whatever bit rate each frame + /// needs. AAC only; values outside the range are clamped, and NaN is an error. + Quality(f32), } /// Stored sample representation. @@ -411,9 +636,9 @@ pub enum BitDepth { pub struct EncodeOptions { /// Output file format. pub format: EncodeFormat, - /// Sample depth to write. + /// Sample depth to write (ignored by the lossy formats). pub bit_depth: BitDepth, - /// Add TPDF dither when quantizing to an integer depth. + /// Add TPDF dither when quantizing to an integer depth (ignored by the lossy formats). pub dither: bool, /// Write a BWF `bext` chunk (WAV only; ignored for other formats). pub bwf: Option, @@ -424,15 +649,27 @@ pub struct EncodeOptions { /// the count (they read 5 and 6 channels with side surrounds and 7 as 6.1 with sides, so the /// usual layouts for those counts get one; see the README's limits); AIFF has a fixed channel /// order and ignores it. It must have as many channels as the audio. + /// + /// AAC, ALAC, MP3, AC-3 and E-AC-3 store channels in their own order, so here the layout says + /// which speaker each channel of the audio (in WAV order) is, and the channels are reordered + /// to match. Each of these formats has a fixed set of layouts (AAC and ALAC one per channel + /// count, AC-3 one per coding mode); a layout outside it is [`AudioError::Unsupported`]. Side + /// and back surrounds are taken as the same pair where the format has only one. pub layout: Option, /// Write WAV in the RF64 layout even below 4 GiB (WAV only; ignored for other formats). pub force_rf64: bool, + /// The bit rate or quality of a lossy format (ignored by the others). `None` is a constant + /// 64 kbit/s per channel for AAC, 96 kbit/s per channel for MP3, and 96 kbit/s per + /// full-bandwidth channel (the LFE not counted) for AC-3 and E-AC-3, moved to the nearest rate + /// the stream can carry. + pub rate_control: Option, } impl EncodeOptions { - /// Options for `format`: 24-bit, no dither, no BWF chunk, the usual layout. + /// Options for `format`: 24-bit, no dither, no BWF chunk, the usual layout, the format's + /// default bit rate. pub fn new(format: EncodeFormat) -> Self { - Self { format, bit_depth: BitDepth::Int24, dither: false, bwf: None, layout: None, force_rf64: false } + Self { format, bit_depth: BitDepth::Int24, dither: false, bwf: None, layout: None, force_rf64: false, rate_control: None } } /// Sets `format`. @@ -470,6 +707,18 @@ impl EncodeOptions { self.force_rf64 = force_rf64; self } + + /// Sets `rate_control` to a constant bit rate in bits per second ([`RateControl::Bitrate`]). + pub fn with_bitrate(mut self, bits_per_second: u32) -> Self { + self.rate_control = Some(RateControl::Bitrate(bits_per_second)); + self + } + + /// Sets `rate_control` to a constant quality from 0.0 to 1.0 ([`RateControl::Quality`]). + pub fn with_quality(mut self, quality: f32) -> Self { + self.rate_control = Some(RateControl::Quality(quality)); + self + } } impl Default for EncodeOptions { diff --git a/crates/audio/src/opus/encoder/bands.rs b/crates/audio/src/opus/encoder/bands.rs new file mode 100644 index 000000000..604aab595 --- /dev/null +++ b/crates/audio/src/opus/encoder/bands.rs @@ -0,0 +1,497 @@ +//! Band shape coding: PVQ search and codeword indexing, spreading, recursive band splitting +//! (RFC 6716 §4.3.4, encoder direction). +//! +//! The encoder codes 20 ms long-block frames only (no transients, no TF changes), and stereo +//! as dual (independent L/R) stereo, so a band is always coded by `quant_partition` with a single +//! block. Every bit-budget computation mirrors the decoder so both sides take the same +//! split/pulse decisions. + +use crate::opus::encoder::range::{BITRES, RangeEncoder, ilog}; +use crate::opus::encoder::rate::{Mode, QTHETA_OFFSET, get_pulses}; +use crate::opus::encoder::tables::{EBANDS, NB_EBANDS}; + +pub const SPREAD_NORMAL: usize = 2; + +#[inline] +fn frac_mul16(a: i32, b: i32) -> i32 { + (16384 + (a as i16 as i32) * (b as i16 as i32)) >> 15 +} + +fn bitexact_cos(x: i32) -> i32 { + let tmp = (4096 + x * x) >> 13; + let x2 = tmp; + let x2 = (32767 - x2) + frac_mul16(x2, -7651 + frac_mul16(x2, 8277 + frac_mul16(-626, x2))); + 1 + x2 +} + +fn bitexact_log2tan(isin: i32, icos: i32) -> i32 { + let lc = ilog(icos as u32); + let ls = ilog(isin as u32); + let icos = icos << (15 - lc); + let isin = isin << (15 - ls); + (ls - lc) * (1 << 11) + frac_mul16(isin, frac_mul16(isin, -2597) + 7932) - frac_mul16(icos, frac_mul16(icos, -2597) + 7932) +} + +fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 { + const EXP2_TABLE8: [i32; 8] = [16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048]; + let mut n2 = 2 * n - 1; + if stereo && n == 2 { + n2 -= 1; + } + let mut qb = (b + n2 * offset) / n2; + qb = qb.min(b - pulse_cap - (4 << BITRES)); + qb = qb.min(8 << BITRES); + if qb < (1 << BITRES >> 1) { + 1 + } else { + let qn = EXP2_TABLE8[(qb & 0x7) as usize] >> (14 - (qb >> BITRES)); + (qn + 1) >> 1 << 1 + } +} + +/// One elementary pass of the spreading rotation, inverted (the decoder applies the forward +/// pass; the encoder undoes it before the pulse search). +fn exp_rotation1_inv(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) { + if len <= stride { + return; + } + if len >= 2 * stride + 1 { + for i in 0..=len - 2 * stride - 1 { + let x1 = x[i]; + let x2 = x[i + stride]; + x[i + stride] = c * x2 - s * x1; + x[i] = c * x1 + s * x2; + } + } + for i in (0..len - stride).rev() { + let x1 = x[i]; + let x2 = x[i + stride]; + x[i + stride] = c * x2 - s * x1; + x[i] = c * x1 + s * x2; + } +} + +/// Inverse of the decoder's spreading rotation (§4.3.4.3) for one block of `len` samples. +pub fn exp_rotation_inv(x: &mut [f32], len: usize, k: usize, spread: usize) { + const SPREAD_FACTOR: [usize; 3] = [15, 10, 5]; + if 2 * k >= len || spread == 0 { + return; + } + let factor = SPREAD_FACTOR[spread - 1]; + let gain = len as f32 / (len + factor * k) as f32; + let theta = 0.5 * gain * gain; + let c = (0.5 * std::f32::consts::PI * theta).cos(); + let s = (0.5 * std::f32::consts::PI * (1.0 - theta)).cos(); + let mut stride2 = 0; + if len >= 8 { + stride2 = 1; + while stride2 * stride2 + stride2 < len { + stride2 += 1; + } + } + // The decoder applies (stride2: s, c) then (1: c, s); undo in reverse order. + exp_rotation1_inv(x, len, 1, c, s); + if stride2 != 0 { + exp_rotation1_inv(x, len, stride2, s, c); + } +} + +/// Greedy PVQ search: the integer vector `y` with `sum |y| = k` closest in direction to `x`. +pub fn pvq_search(x: &[f32], k: usize, y: &mut [i32]) { + let n = x.len(); + y[..n].fill(0); + let abs: Vec = x.iter().map(|v| v.abs()).collect(); + let sum: f32 = abs.iter().sum(); + if !sum.is_finite() || sum <= 1e-15 { + y[0] = k as i32; + return; + } + let mut placed = 0usize; + let mut xy = 0f32; + let mut yy = 0f32; + if k > n / 2 { + // Pre-project onto the pyramid (rounding down) and place the rest greedily. + let r = (k as f32 - 1.0) / sum; + for j in 0..n { + let p = (abs[j] * r).floor() as i32; + y[j] = p; + placed += p as usize; + xy += abs[j] * p as f32; + yy += (p * p) as f32; + } + } + while placed < k { + let mut best = 0usize; + let mut best_num = -1f32; + let mut best_den = 1f32; + for j in 0..n { + let num = xy + abs[j]; + let num = num * num; + let den = yy + 2.0 * y[j] as f32 + 1.0; + if num * best_den > best_num * den { + best_num = num; + best_den = den; + best = j; + } + } + xy += abs[best]; + yy += 2.0 * y[best] as f32 + 1.0; + y[best] += 1; + placed += 1; + } + for j in 0..n { + if x[j] < 0.0 { + y[j] = -y[j]; + } + } +} + +/// Encodes the PVQ codeword `y` (`sum |y| = k`) as the index the RFC 6716 §4.3.4.2 decoder maps +/// back to `y`. +pub fn encode_pulses(y: &[i32], k: usize, enc: &mut RangeEncoder, v: &mut Vec) { + let n = y.len(); + let w = k + 1; + v.clear(); + v.resize((n + 1) * w, 0); + v[0] = 1; + for nn in 1..=n { + v[nn * w] = 1; + for kk in 1..=k { + let a = v[(nn - 1) * w + kk]; + let b = v[nn * w + kk - 1]; + let c = v[(nn - 1) * w + kk - 1]; + v[nn * w + kk] = a.saturating_add(b).saturating_add(c); + } + } + let total = v[n * w + k]; + let vv = |nn: usize, kx: usize| v[nn * w + kx]; + let mut index = 0u64; + let mut kk = k; + for j in 0..n { + if kk == 0 { + break; + } + let rem = n - j; + let t = y[j].unsigned_abs() as usize; + // Codewords with |y_j| = t start at sum_{m < kk - t} V(rem-1, m) within their sign half. + let mut base: u64 = (0..kk - t).map(|m| vv(rem - 1, m)).sum(); + if y[j] < 0 { + base += (vv(rem - 1, kk) + vv(rem, kk)) / 2; + } + index += base; + kk -= t; + } + debug_assert!(total <= u32::MAX as u64); + if total >= 2 { + enc.uint(index as u32, total as u32); + } +} + +pub struct BandEnc<'m, 'e> { + pub m: &'m Mode, + pub enc: &'e mut RangeEncoder, + pub i: usize, + pub spread: usize, + pub remaining_bits: i32, + pvq_v: Vec, + iy: Vec, + tmp: Vec, +} + +impl BandEnc<'_, '_> { + /// `compute_theta` for a mono split (single block): measures the energy split between the + /// two halves and codes the quantised angle with the triangular pdf. + fn compute_theta_split(&mut self, xa: &[f32], xb: &[f32], b: &mut i32, lm: i32) -> (i32, i32, i32) { + let n = xa.len() as i32; + let i = self.i; + let pulse_cap = self.m.log_n[i] + lm * (1 << BITRES); + let offset = (pulse_cap >> 1) - QTHETA_OFFSET; + let qn = compute_qn(n, *b, offset, pulse_cap, false); + let tell = self.enc.tell_frac(); + let mut itheta = 0i32; + if qn != 1 { + let mid = xa.iter().map(|v| v * v).sum::().sqrt(); + let side = xb.iter().map(|v| v * v).sum::().sqrt(); + let ang = (side as f64).atan2(mid as f64) * std::f64::consts::FRAC_2_PI; + let it = ((ang * qn as f64 + 0.5).floor() as i32).clamp(0, qn) as u32; + let q = qn as u32; + let half = q >> 1; + let ft = (half + 1) * (half + 1); + let (fl, fs) = if it <= half { (it * (it + 1) >> 1, it + 1) } else { (ft - ((q + 1 - it) * (q + 2 - it) >> 1), q + 1 - it) }; + self.enc.encode(fl, fl + fs, ft); + itheta = ((it * 16384) / q) as i32; + } + let qalloc = self.enc.tell_frac() - tell; + *b -= qalloc; + let delta = if itheta == 0 { + -16384 + } else if itheta == 16384 { + 16384 + } else { + let imid = bitexact_cos(itheta); + let iside = bitexact_cos(16384 - itheta); + frac_mul16((n - 1) << 7, bitexact_log2tan(iside, imid)) + }; + (itheta, delta, qalloc) + } + + /// `quant_partition` (single block, encoder side). + pub fn quant_partition(&mut self, x: &[f32], mut b: i32, mut lm: i32) { + let n = x.len(); + let i = self.i; + let cache = self.m.cache(lm, i); + let cache_max = cache[cache[0] as usize] as i32; + if lm != -1 && b > cache_max + 12 && n > 2 { + let half = n >> 1; + let (xa, xb) = x.split_at(half); + lm -= 1; + let (itheta, delta, qalloc) = self.compute_theta_split(xa, xb, &mut b, lm); + let mut mbits = 0.max(b.min((b - delta) / 2)); + let mut sbits = b - mbits; + self.remaining_bits -= qalloc; + let mut rebalance = self.remaining_bits; + if mbits >= sbits { + self.quant_partition(xa, mbits, lm); + rebalance = mbits - (rebalance - self.remaining_bits); + if rebalance > 3 << BITRES && itheta != 0 { + sbits += rebalance - (3 << BITRES); + } + self.quant_partition(xb, sbits, lm); + } else { + self.quant_partition(xb, sbits, lm); + rebalance = sbits - (rebalance - self.remaining_bits); + if rebalance > 3 << BITRES && itheta != 16384 { + mbits += rebalance - (3 << BITRES); + } + self.quant_partition(xa, mbits, lm); + } + return; + } + let m = self.m; + let mut q = m.bits2pulses(i, lm, b); + let mut curr_bits = m.pulses2bits(i, lm, q); + self.remaining_bits -= curr_bits; + while self.remaining_bits < 0 && q > 0 { + self.remaining_bits += curr_bits; + q -= 1; + curr_bits = m.pulses2bits(i, lm, q); + self.remaining_bits -= curr_bits; + } + if q != 0 { + let k = get_pulses(q) as usize; + let mut tmp = std::mem::take(&mut self.tmp); + tmp.clear(); + tmp.extend_from_slice(x); + exp_rotation_inv(&mut tmp, n, k, self.spread); + let mut iy = std::mem::take(&mut self.iy); + iy.clear(); + iy.resize(n, 0); + pvq_search(&tmp, k, &mut iy); + encode_pulses(&iy, k, self.enc, &mut self.pvq_v); + self.iy = iy; + self.tmp = tmp; + } + } +} + +/// Codes all band shapes (`quant_all_bands`, encoder side, long blocks). `x` holds `c` channels +/// of `n` normalised MDCT coefficients each. +#[allow(clippy::too_many_arguments)] +pub fn quant_all_bands( + m: &Mode, + start: usize, + end: usize, + x: &[f32], + n_total: usize, + c: usize, + pulses: &[i32; NB_EBANDS], + spread: usize, + dual_stereo: bool, + intensity: usize, + total_bits: i32, + mut balance: i32, + enc: &mut RangeEncoder, + lm: usize, + coded_bands: usize, +) { + let mm = 1usize << lm; + debug_assert!(c == 1 || dual_stereo || intensity <= start, "stereo frames are coded as dual stereo"); + let mut ctx = BandEnc { m, enc, i: 0, spread, remaining_bits: 0, pvq_v: Vec::new(), iy: Vec::new(), tmp: Vec::new() }; + for i in start..end { + ctx.i = i; + let xo = mm * EBANDS[i] as usize; + let n = mm * EBANDS[i + 1] as usize - xo; + let tell = ctx.enc.tell_frac(); + if i != start { + balance -= tell; + } + let remaining_bits = total_bits - tell - 1; + ctx.remaining_bits = remaining_bits; + let b = if i < coded_bands { + let curr_balance = balance / 3.min(coded_bands as i32 - i as i32); + 0.max(16383.min((remaining_bits + 1).min(pulses[i] + curr_balance))) + } else { + 0 + }; + // Bands at and above `intensity` (= coded_bands) carry no bits, so they emit no symbols. + if i < coded_bands || c == 1 { + if c == 2 && dual_stereo && i < intensity { + ctx.quant_partition(&x[xo..xo + n], b / 2, lm as i32); + ctx.quant_partition(&x[n_total + xo..n_total + xo + n], b / 2, lm as i32); + } else { + ctx.quant_partition(&x[xo..xo + n], b, lm as i32); + } + } + balance += pulses[i] + tell; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::opus::encoder::range::dec::RangeDecoder; + + fn exp_rotation1(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) { + let ms = -s; + if len <= stride { + return; + } + for i in 0..len - stride { + let x1 = x[i]; + let x2 = x[i + stride]; + x[i + stride] = c * x2 + s * x1; + x[i] = c * x1 + ms * x2; + } + if len >= 2 * stride + 1 { + for i in (0..=len - 2 * stride - 1).rev() { + let x1 = x[i]; + let x2 = x[i + stride]; + x[i + stride] = c * x2 + s * x1; + x[i] = c * x1 + ms * x2; + } + } + } + + /// The decoder's spreading rotation (single block). + fn exp_rotation(x: &mut [f32], len: usize, k: usize, spread: usize) { + const SPREAD_FACTOR: [usize; 3] = [15, 10, 5]; + if 2 * k >= len || spread == 0 { + return; + } + let factor = SPREAD_FACTOR[spread - 1]; + let gain = len as f32 / (len + factor * k) as f32; + let theta = 0.5 * gain * gain; + let c = (0.5 * std::f32::consts::PI * theta).cos(); + let s = (0.5 * std::f32::consts::PI * (1.0 - theta)).cos(); + let mut stride2 = 0; + if len >= 8 { + stride2 = 1; + while stride2 * stride2 + stride2 < len { + stride2 += 1; + } + } + if stride2 != 0 { + exp_rotation1(x, len, stride2, s, c); + } + exp_rotation1(x, len, 1, c, s); + } + + #[test] + fn spreading_inverse_is_exact() { + for &len in &[8usize, 16, 24, 48, 96, 176] { + for k in [1usize, 2, 3, 5] { + let orig: Vec = (0..len).map(|i| ((i * 31 % 17) as f32 - 8.0) / 8.0).collect(); + let mut x = orig.clone(); + exp_rotation_inv(&mut x, len, k, SPREAD_NORMAL); + exp_rotation(&mut x, len, k, SPREAD_NORMAL); + for (a, b) in x.iter().zip(&orig) { + assert!((a - b).abs() < 1e-4, "len={len} k={k}"); + } + } + } + } + + /// PVQ decoder of RFC 6716 §4.3.4.2 (as in FilmCraft's decoder). + fn decode_pulses(n: usize, k: usize, dec: &mut RangeDecoder) -> Vec { + let w = k + 1; + let mut v = vec![0u64; (n + 1) * w]; + v[0] = 1; + for nn in 1..=n { + v[nn * w] = 1; + for kk in 1..=k { + v[nn * w + kk] = v[(nn - 1) * w + kk].saturating_add(v[nn * w + kk - 1]).saturating_add(v[(nn - 1) * w + kk - 1]); + } + } + let total = v[n * w + k]; + let mut i = if total >= 2 { dec.uint(total as u32) as u64 } else { 0 }; + let mut y = vec![0i32; n]; + let mut kk = k; + for j in 0..n { + let rem = n - j; + if kk == 0 { + break; + } + let vv = |nn: usize, kx: usize| v[nn * w + kx]; + let mut p = (vv(rem - 1, kk) + vv(rem, kk)) / 2; + let neg = i >= p; + if neg { + i -= p; + } + let k0 = kk; + p -= vv(rem - 1, kk); + while p > i && kk > 0 { + kk -= 1; + p -= vv(rem - 1, kk); + } + let mag = (k0 - kk) as i32; + y[j] = if neg { -mag } else { mag }; + i -= p.min(i); + } + y + } + + fn all_codewords(n: usize, k: usize) -> Vec> { + if n == 0 { + return if k == 0 { vec![vec![]] } else { vec![] }; + } + let mut out = Vec::new(); + for t in -(k as i32)..=(k as i32) { + for mut rest in all_codewords(n - 1, k - t.unsigned_abs() as usize) { + rest.insert(0, t); + out.push(rest); + } + } + out + } + + #[test] + fn pvq_index_roundtrip_exhaustive() { + let mut v = Vec::new(); + for n in 1..6usize { + for k in 1..6usize { + for y in all_codewords(n, k) { + let mut e = RangeEncoder::new(); + encode_pulses(&y, k, &mut e, &mut v); + let buf = e.done(16); + let mut d = RangeDecoder::new(&buf); + assert_eq!(decode_pulses(n, k, &mut d), y, "n={n} k={k}"); + } + } + } + } + + #[test] + fn pvq_search_finds_good_direction() { + let x: Vec = (0..32).map(|i| ((i as f32) * 0.7).sin()).collect(); + let mut y = vec![0i32; 32]; + for k in [1usize, 4, 16, 64] { + pvq_search(&x, k, &mut y); + assert_eq!(y.iter().map(|v| v.unsigned_abs() as usize).sum::(), k); + let xy: f32 = x.iter().zip(&y).map(|(a, &b)| a * b as f32).sum(); + let yy: f32 = y.iter().map(|&b| (b * b) as f32).sum(); + let xx: f32 = x.iter().map(|a| a * a).sum(); + let corr = xy / (xx * yy).sqrt(); + assert!(corr > if k >= 16 { 0.9 } else { 0.2 }, "k={k} corr={corr}"); + } + } +} diff --git a/crates/audio/src/opus/encoder/energy.rs b/crates/audio/src/opus/encoder/energy.rs new file mode 100644 index 000000000..8d4f357d0 --- /dev/null +++ b/crates/audio/src/opus/encoder/energy.rs @@ -0,0 +1,230 @@ +//! Band energy quantisation: Laplace-coded coarse energy with inter/intra prediction, fine +//! energy and the final refinement bits (RFC 6716 §4.3.2, encoder direction). +//! +//! The quantised energies are updated with exactly the decoder's arithmetic so the prediction +//! state never drifts between encoder and decoder. + +use crate::opus::encoder::range::RangeEncoder; +use crate::opus::encoder::rate::MAX_FINE_BITS; +use crate::opus::encoder::tables::{BETA_COEF, BETA_INTRA, E_PROB_MODEL, NB_EBANDS, PRED_COEF, SMALL_ENERGY_ICDF}; + +const LAPLACE_MINP: u32 = 1; +const LAPLACE_NMIN: u32 = 16; + +fn laplace_get_freq1(fs0: u32, decay: u32) -> u32 { + let ft = 32768 - LAPLACE_MINP * (2 * LAPLACE_NMIN) - fs0; + (ft * (16384 - decay)) >> 15 +} + +/// Encodes a Laplace-distributed integer (`fs` = probability of 0 in Q15, `decay` in Q14). +/// Returns the value actually coded (very large magnitudes are clamped to the representable +/// range). +pub fn laplace_encode(enc: &mut RangeEncoder, value: i32, mut fs: u32, decay: u32) -> i32 { + let mut fl = 0u32; + let mut coded = value; + if value != 0 { + let s: i32 = if value < 0 { -1 } else { 0 }; + let val = value.abs(); + fl = fs; + fs = laplace_get_freq1(fs, decay); + let mut i = 1; + while fs > 0 && i < val { + fs *= 2; + fl += fs + 2 * LAPLACE_MINP; + fs = (fs * decay) >> 15; + i += 1; + } + if fs == 0 { + let ndi_max = (32768 - fl + LAPLACE_MINP - 1) as i32; + let ndi_max = (ndi_max - s) >> 1; + let di = (val - i).min(ndi_max - 1); + fl = (fl as i32 + (2 * di + 1 + s) * LAPLACE_MINP as i32) as u32; + fs = LAPLACE_MINP.min(32768 - fl); + let mag = i + di; + coded = if s < 0 { -mag } else { mag }; + } else { + fs += LAPLACE_MINP; + if s == 0 { + fl += fs; + } + } + } + enc.encode_bin(fl, fl + fs, 15); + coded +} + +/// `quant_coarse_energy` for one prediction mode. `e` holds the target log2 energies (relative +/// to `E_MEANS`), `old_e` the quantised energies, updated in place. `budget` is the frame size in +/// bits. +#[allow(clippy::too_many_arguments)] +pub fn quant_coarse_energy( + start: usize, + end: usize, + e: &[f32; 2 * NB_EBANDS], + old_e: &mut [f32; 2 * NB_EBANDS], + intra: bool, + enc: &mut RangeEncoder, + c: usize, + lm: usize, + budget: i32, +) { + let prob = &E_PROB_MODEL[lm][intra as usize]; + let (coef, beta) = if intra { (0.0, BETA_INTRA) } else { (PRED_COEF[lm], BETA_COEF[lm]) }; + let mut prev = [0f32; 2]; + for i in start..end { + for ch in 0..c { + let idx = i + ch * NB_EBANDS; + let oldc = old_e[idx].max(-9.0); + let x = e[idx]; + let f = x - coef * oldc - prev[ch]; + let mut qi = (f + 0.5).floor().clamp(-64.0, 64.0) as i32; + let tell = enc.tell(); + // Keep a few bits per remaining band in reserve when the budget runs out. + let bits_left = budget - tell - 3 * c as i32 * (end - i) as i32; + if i != start && bits_left < 30 { + if bits_left < 24 { + qi = qi.min(1); + } + if bits_left < 16 { + qi = qi.max(-1); + } + } + if budget - tell >= 15 { + let pi = 2 * i.min(20); + qi = laplace_encode(enc, qi, (prob[pi] as u32) << 7, (prob[pi + 1] as u32) << 6); + } else if budget - tell >= 2 { + qi = qi.clamp(-1, 1); + enc.icdf(if qi < 0 { (-2 * qi - 1) as usize } else { (2 * qi) as usize }, &SMALL_ENERGY_ICDF, 2); + } else if budget - tell >= 1 { + qi = qi.clamp(-1, 0); + enc.bit_logp(qi == -1, 1); + } else { + qi = -1; + } + let q = qi as f32; + old_e[idx] = oldc; + let tmp = coef * old_e[idx] + prev[ch] + q; + old_e[idx] = tmp; + prev[ch] = prev[ch] + q - beta * q; + } + } +} + +/// `quant_fine_energy`: raw bits refining each band's quantised energy. +pub fn quant_fine_energy( + start: usize, + end: usize, + e: &[f32; 2 * NB_EBANDS], + old_e: &mut [f32; 2 * NB_EBANDS], + fine_quant: &[i32; NB_EBANDS], + enc: &mut RangeEncoder, + c: usize, +) { + for i in start..end { + let fq = fine_quant[i]; + if fq <= 0 { + continue; + } + for ch in 0..c { + let idx = i + ch * NB_EBANDS; + let err = e[idx] - old_e[idx]; + let levels = 1i32 << fq; + let q2 = (((err + 0.5) * levels as f32).floor() as i32).clamp(0, levels - 1); + enc.bits(q2 as u32, fq as u32); + let offset = (q2 as f32 + 0.5) * (1 << (14 - fq)) as f32 / 16384.0 - 0.5; + old_e[idx] += offset; + } + } +} + +/// `quant_energy_finalise`: spends the bits left at the end of the frame on one more bit of +/// energy resolution per band, in priority order. +#[allow(clippy::too_many_arguments)] +pub fn quant_energy_finalise( + start: usize, + end: usize, + e: &[f32; 2 * NB_EBANDS], + old_e: &mut [f32; 2 * NB_EBANDS], + fine_quant: &[i32; NB_EBANDS], + fine_priority: &[i32; NB_EBANDS], + mut bits_left: i32, + enc: &mut RangeEncoder, + c: usize, +) { + for prio in 0..2 { + let mut i = start; + while i < end && bits_left >= c as i32 { + if fine_quant[i] >= MAX_FINE_BITS || fine_priority[i] != prio { + i += 1; + continue; + } + for ch in 0..c { + let idx = i + ch * NB_EBANDS; + let q2 = (e[idx] - old_e[idx] >= 0.0) as u32; + enc.bits(q2, 1); + let offset = (q2 as f32 - 0.5) * (1 << (14 - fine_quant[i] - 1)) as f32 / 16384.0; + old_e[idx] += offset; + bits_left -= 1; + } + i += 1; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::opus::encoder::range::dec::RangeDecoder; + + /// Laplace decoder of RFC 6716 §4.3.2.1 (as in FilmCraft's decoder). + fn laplace_decode(dec: &mut RangeDecoder, mut fs: u32, decay: u32) -> i32 { + let mut val = 0i32; + let fm = dec.decode(32768); + let mut fl = 0u32; + if fm >= fs { + val += 1; + fl = fs; + fs = laplace_get_freq1(fs, decay) + LAPLACE_MINP; + while fs > LAPLACE_MINP && fm >= fl + 2 * fs { + fs *= 2; + fl += fs; + fs = (((fs - 2 * LAPLACE_MINP) * decay) >> 15) + LAPLACE_MINP; + val += 1; + } + if fs <= LAPLACE_MINP { + let di = (fm - fl) >> 1; + val += di as i32; + fl += 2 * di * LAPLACE_MINP; + } + if fm < fl + fs { + val = -val; + } else { + fl += fs; + } + } + dec.update(fl, (fl + fs).min(32768), 32768); + val + } + + #[test] + fn laplace_roundtrip_all_models() { + for lm in 0..4 { + for intra in 0..2 { + for band in 0..21 { + let prob = &E_PROB_MODEL[lm][intra]; + let (fs, decay) = ((prob[2 * band] as u32) << 7, (prob[2 * band + 1] as u32) << 6); + let vals: Vec = (-64..=64).collect(); + let mut e = RangeEncoder::new(); + let coded: Vec = vals.iter().map(|&v| laplace_encode(&mut e, v, fs, decay)).collect(); + let size = (e.tell() as usize).div_ceil(8); + let buf = e.done(size); + let mut d = RangeDecoder::new(&buf); + for (&v, &c) in vals.iter().zip(&coded) { + assert!(c == v || (c.signum() == v.signum() && c.abs() < v.abs()), "clamp {v} -> {c}"); + assert_eq!(laplace_decode(&mut d, fs, decay), c, "lm={lm} intra={intra} band={band} v={v}"); + } + } + } + } + } +} diff --git a/crates/audio/src/opus/encoder/mdct.rs b/crates/audio/src/opus/encoder/mdct.rs new file mode 100644 index 000000000..6a42cce96 --- /dev/null +++ b/crates/audio/src/opus/encoder/mdct.rs @@ -0,0 +1,294 @@ +//! Forward MDCT with the CELT low-overlap window (RFC 6716 §4.3.7, run in the analysis +//! direction). +//! +//! A 20 ms frame is a 1920-point MDCT (960 coefficients) whose window is zero for 420 samples, +//! rises over the 120-sample overlap, is flat for 840 samples, falls over the next 120 samples +//! and is zero again for the last 420. The input block is therefore the 120 overlap samples kept +//! from the previous frame followed by the 960 new samples. The MDCT is folded into a DCT-IV, +//! which is computed with an N/2-point complex FFT. + +use crate::opus::encoder::tables::OVERLAP; + +#[derive(Clone, Copy, Default, Debug)] +pub struct Cpx { + pub re: f32, + pub im: f32, +} + +impl Cpx { + #[inline] + fn mul(self, o: Cpx) -> Cpx { + Cpx { re: self.re * o.re - self.im * o.im, im: self.re * o.im + self.im * o.re } + } + #[inline] + fn add(self, o: Cpx) -> Cpx { + Cpx { re: self.re + o.re, im: self.im + o.im } + } +} + +/// Mixed-radix (2, 3, 4, 5) forward complex FFT, unscaled (decimation in time, recursive). +pub struct Fft { + n: usize, + factors: Vec, + twiddle: Vec, +} + +impl Fft { + pub fn new(n: usize) -> Fft { + let mut factors = Vec::new(); + let mut m = n; + for p in [4usize, 2, 3, 5] { + while m.is_multiple_of(p) { + factors.push(p); + m /= p; + } + } + assert_eq!(m, 1, "unsupported FFT size {n}"); + let twiddle = (0..n) + .map(|k| { + let ph = -2.0 * std::f64::consts::PI * k as f64 / n as f64; + Cpx { re: ph.cos() as f32, im: ph.sin() as f32 } + }) + .collect(); + Fft { n, factors, twiddle } + } + + pub fn process(&self, data: &mut [Cpx], scratch: &mut Vec) { + scratch.clear(); + scratch.extend_from_slice(&data[..self.n]); + self.rec(&mut data[..self.n], scratch, 1, self.n, 0, 1); + } + + fn rec(&self, out: &mut [Cpx], inp: &[Cpx], in_stride: usize, n: usize, fi: usize, tw_stride: usize) { + let p = self.factors[fi]; + let m = n / p; + if m == 1 { + for (i, o) in out.iter_mut().enumerate().take(p) { + *o = inp[i * in_stride]; + } + } else { + for q in 0..p { + self.rec(&mut out[q * m..(q + 1) * m], &inp[q * in_stride..], in_stride * p, m, fi + 1, tw_stride * p); + } + } + let big = self.n; + let mut t = [Cpx::default(); 5]; + for k in 0..m { + for (q, tq) in t.iter_mut().enumerate().take(p) { + *tq = out[q * m + k].mul(self.twiddle[(q * k * tw_stride) % big]); + } + for q2 in 0..p { + let mut acc = Cpx::default(); + for (q, tq) in t.iter().enumerate().take(p) { + acc = acc.add(tq.mul(self.twiddle[((q * q2) % p) * (big / p)])); + } + out[q2 * m + k] = acc; + } + } + } +} + +/// Forward MDCT producing `n` coefficients from a block of `n + OVERLAP` samples. +pub struct Mdct { + /// Number of coefficients (half the MDCT length). + n: usize, + fft: Fft, + pre: Vec, + post: Vec, + /// Rising half of the low-overlap window (RFC 6716 §4.3.7). + pub window: [f32; OVERLAP], + scale: f32, + z: Vec, + scratch: Vec, + v: Vec, +} + +impl Mdct { + pub fn new(n: usize) -> Mdct { + let n2 = n / 2; + let pi = std::f64::consts::PI; + let pre = (0..n2) + .map(|m| { + let ph = -pi * m as f64 / n as f64; + Cpx { re: ph.cos() as f32, im: ph.sin() as f32 } + }) + .collect(); + let post = (0..n2) + .map(|p| { + let ph = -pi * (p as f64 + 0.25) / n as f64; + Cpx { re: ph.cos() as f32, im: ph.sin() as f32 } + }) + .collect(); + let mut window = [0f32; OVERLAP]; + for (i, w) in window.iter_mut().enumerate() { + let x = std::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / OVERLAP as f64; + let s = x.sin(); + *w = (std::f64::consts::FRAC_PI_2 * s * s).sin() as f32; + } + Mdct { n, fft: Fft::new(n2), pre, post, window, scale: 2.0 / n as f32, z: Vec::new(), scratch: Vec::new(), v: vec![0.0; n] } + } + + /// Transforms `block` (`n + OVERLAP` samples: the previous frame's last `OVERLAP` samples, then + /// `n` new ones) into `out[..n]`, scaled so that the RFC 6716 decoder's inverse MDCT and + /// overlap-add reproduce the input. + pub fn forward(&mut self, block: &[f32], out: &mut [f32]) { + let n = self.n; + let n2 = n / 2; + debug_assert_eq!(block.len(), n + OVERLAP); + // Place the windowed block into the (virtual) 2n-sample MDCT input u at offset `pad`. + let pad = (n - OVERLAP) / 2; + let w = &self.window; + let u = |t: usize| -> f32 { + if t < pad || t >= pad + n + OVERLAP { + return 0.0; + } + let j = t - pad; + let g = if j < OVERLAP { + w[j] + } else if j >= n { + w[OVERLAP - 1 - (j - n)] + } else { + 1.0 + }; + block[j] * g + }; + // Fold to a DCT-IV input: v = (-c_r - d, a - b_r) over the four quarters of u. + for m in 0..n2 { + self.v[m] = -u(n + n2 - 1 - m) - u(n + n2 + m); + self.v[n2 + m] = u(m) - u(n2 + n2 - 1 - m); + } + // DCT-IV via an n/2-point complex FFT. + self.z.clear(); + for m in 0..n2 { + let wv = Cpx { re: self.v[2 * m], im: self.v[n - 1 - 2 * m] }; + self.z.push(wv.mul(self.pre[m])); + } + self.fft.process(&mut self.z, &mut self.scratch); + for p in 0..n2 { + let y = self.z[p].mul(self.post[p]); + out[2 * p] = y.re * self.scale; + out[n - 1 - 2 * p] = -y.im * self.scale; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Direct MDCT definition X[k] = sum u[t] cos(pi/N (t + 1/2 + N/2)(k + 1/2)). + fn direct(block: &[f32], n: usize, window: &[f32; OVERLAP]) -> Vec { + let pad = (n - OVERLAP) / 2; + let mut u = vec![0f64; 2 * n]; + for (j, &b) in block.iter().enumerate() { + let g = if j < OVERLAP { + window[j] + } else if j >= n { + window[OVERLAP - 1 - (j - n)] + } else { + 1.0 + }; + u[pad + j] = (b * g) as f64; + } + (0..n) + .map(|k| { + (0..2 * n).map(|t| u[t] * (std::f64::consts::PI / n as f64 * (t as f64 + 0.5 + n as f64 / 2.0) * (k as f64 + 0.5)).cos()).sum::() + * 2.0 + / n as f64 + }) + .collect() + } + + #[test] + fn matches_direct_formula() { + for &n in &[240usize, 960] { + let block: Vec = (0..n + OVERLAP).map(|i| ((i * 37 % 101) as f32 - 50.0) / 7.0).collect(); + let mut m = Mdct::new(n); + let mut out = vec![0f32; n]; + m.forward(&block, &mut out); + let d = direct(&block, n, &m.window); + for k in 0..n { + assert!((out[k] as f64 - d[k]).abs() < 1e-2, "n={n} k={k}: {} vs {}", out[k], d[k]); + } + } + } + + // ---- Replica of the RFC 6716 decoder inverse MDCT (as in FilmCraft's decoder) ---- + + fn imdct_backward(n_full: usize, input: &[f32], out: &mut [f32], window: &[f32]) { + let n2 = n_full >> 1; + let n4 = n_full >> 2; + let t: Vec = (0..n2).map(|i| (2.0 * std::f64::consts::PI * (i as f64 + 0.125) / n_full as f64).cos() as f32).collect(); + let fft = Fft::new(n4); + let mut z = Vec::new(); + for i in 0..n4 { + let x1 = input[2 * i]; + let x2 = input[n2 - 1 - 2 * i]; + let yr = x2 * t[i] + x1 * t[n4 + i]; + let yi = x1 * t[i] - x2 * t[n4 + i]; + z.push(Cpx { re: yi, im: yr }); + } + fft.process(&mut z, &mut Vec::new()); + let overlap = OVERLAP; + let base = overlap >> 1; + let y = &mut out[base..base + n2]; + for i in 0..n4.div_ceil(2) { + let front = z[i]; + let back = z[n4 - 1 - i]; + let (re, im) = (front.im, front.re); + let (t0, t1) = (t[i], t[n4 + i]); + let yr0 = re * t0 + im * t1; + let yi0 = re * t1 - im * t0; + let (re, im) = (back.im, back.re); + let (t0, t1) = (t[n4 - i - 1], t[n2 - i - 1]); + let yr1 = re * t0 + im * t1; + let yi1 = re * t1 - im * t0; + y[2 * i] = yr0; + y[n2 - 1 - 2 * i] = yi0; + y[n2 - 2 - 2 * i] = yr1; + y[2 * i + 1] = yi1; + } + for i in 0..overlap / 2 { + let x1 = out[overlap - 1 - i]; + let x2 = out[i]; + let w1 = window[i]; + let w2 = window[overlap - 1 - i]; + out[i] = x2 * w2 - x1 * w1; + out[overlap - 1 - i] = x2 * w1 + x1 * w2; + } + } + + /// MDCT analysis followed by the decoder's IMDCT + TDAC overlap-add reproduces the input + /// delayed by exactly `OVERLAP` samples. + #[test] + fn perfect_reconstruction_through_decoder_imdct() { + let n = 960; + let frames = 5; + let sig: Vec = (0..n * frames).map(|i| (i as f32 * 0.013).sin() * 1000.0 + ((i * 7919) % 211) as f32 - 105.0).collect(); + let mut m = Mdct::new(n); + let mut hist = vec![0f32; OVERLAP]; + // Decoder memory: [frame output n][folded tail OVERLAP/2] laid out like decode_mem. + let mut mem = vec![0f32; n + OVERLAP]; + let mut decoded = Vec::new(); + for f in 0..frames { + let mut block = hist.clone(); + block.extend_from_slice(&sig[f * n..(f + 1) * n]); + hist.copy_from_slice(&block[n..]); + let mut coefs = vec![0f32; n]; + m.forward(&block, &mut coefs); + // Shift: the previous folded tail (at n..n+OVERLAP/2) moves to 0..OVERLAP/2. + mem.copy_within(n..n + OVERLAP / 2, 0); + imdct_backward(2 * n, &coefs, &mut mem, &m.window); + decoded.extend_from_slice(&mem[..n]); + } + let mut err = 0f64; + let mut sum = 0f64; + for t in OVERLAP..n * frames { + let d = decoded[t] as f64 - sig[t - OVERLAP] as f64; + err += d * d; + sum += (sig[t - OVERLAP] as f64).powi(2); + } + let snr = 10.0 * (sum / err).log10(); + assert!(snr > 80.0, "reconstruction SNR {snr:.1} dB"); + } +} diff --git a/crates/audio/src/opus/encoder/mod.rs b/crates/audio/src/opus/encoder/mod.rs new file mode 100644 index 000000000..cbb0d7984 --- /dev/null +++ b/crates/audio/src/opus/encoder/mod.rs @@ -0,0 +1,593 @@ +//! Clean-room pure-Rust Opus encoder (RFC 6716 SILK, hybrid and CELT modes; RFC 7845 `OpusHead`). +//! +//! Produces 20 ms Opus packets from 48 kHz float input, mono or stereo. The coding mode and +//! audio bandwidth are chosen once per stream from the per-channel bitrate and the +//! [`Application`] (see the crate README for the table): +//! +//! - **SILK** (narrowband/mediumband/wideband): linear-predictive speech coding at an internal +//! rate of 8/12/16 kHz; packet sizes vary around the target bitrate. +//! - **Hybrid** (super-wideband/fullband): SILK wideband codes 0–8 kHz and CELT codes the bands +//! above in the same range-coded frame; constant packet size. +//! - **CELT** (fullband): MDCT transform coding; constant packet size. +//! +//! From EffectCraft's `effectcraft-opusenc` (storytold/effectcraft@c618429). Public items keep their +//! names, so EffectCraft can re-export this module. +//! +//! ``` +//! # #[cfg(feature = "opus-encode")] { +//! use craft_audio::opus::encoder::{Application, Mode, Encoder}; +//! let mut enc = Encoder::new(2, 128_000).unwrap(); +//! let pcm = vec![0.0f32; Encoder::FRAME_SIZE * 2]; +//! let packet = enc.encode_float(&pcm).unwrap(); +//! assert_eq!(packet[0] >> 3, 31); // CELT-only, fullband, 20 ms +//! assert_eq!(enc.opus_head().len(), 19); +//! let voip = Encoder::with_application(1, 16_000, Application::Voip).unwrap(); +//! assert_eq!(voip.mode(), Mode::Silk); +//! # } +//! ``` + +// The bit-allocation code mirrors the normative integer arithmetic; keep C-like shift expressions. +#![allow(clippy::precedence, clippy::int_plus_one)] + +mod bands; +mod energy; +mod mdct; +mod range; +mod rate; +mod resample; +mod silk; +mod tables; + +use std::sync::OnceLock; + +use bands::{SPREAD_NORMAL, quant_all_bands}; +use energy::{quant_coarse_energy, quant_energy_finalise, quant_fine_energy}; +use mdct::Mdct; +use range::{BITRES, RangeEncoder}; +use rate::{Mode as CeltMode, compute_allocation}; +use resample::Downsampler; +use silk::SilkEncoder; +use tables::{E_MEANS, EBANDS, NB_EBANDS, OVERLAP, PREEMPH, SPREAD_ICDF, TF_SELECT_TABLE, TRIM_ICDF}; + +/// Samples per channel in one 20 ms frame at 48 kHz. +const N: usize = 960; +/// LM of a 20 ms frame (8 short blocks). +const LM: usize = 3; +/// Smallest CELT payload the encoder produces (bytes). +const MIN_FRAME_BYTES: usize = 16; +/// Largest payload allowed in one frame (RFC 6716 §3.4, R2). +const MAX_FRAME_BYTES: usize = 1275; +/// First CELT band coded in hybrid frames (8 kHz). +const HYBRID_START_BAND: usize = 17; + +fn celt_mode() -> &'static CeltMode { + static MODE: OnceLock = OnceLock::new(); + MODE.get_or_init(CeltMode::new) +} + +/// Why an encoder could not be created or a frame could not be encoded. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// Opus family-0 streams have 1 or 2 channels. + #[error("Opus family-0 streams have 1 or 2 channels, not {0}")] + Channels(u8), + /// The mode cannot code that bandwidth. + #[error("unsupported mode/bandwidth combination {0:?}/{1:?}")] + ModeBandwidth(Mode, Bandwidth), + /// `encode_float` takes exactly `FRAME_SIZE * channels` samples. + #[error("a frame is {expected} interleaved samples, not {got}")] + FrameLength { + /// Interleaved samples a frame takes (`FRAME_SIZE * channels`). + expected: usize, + /// Interleaved samples passed. + got: usize, + }, +} + +/// Intended use of the stream; selects the mode/bandwidth table. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Application { + /// General audio (music, mixed content): CELT unless the bitrate is low. + #[default] + Audio, + /// Speech: SILK and hybrid over a wider bitrate range, narrower bandwidths at low rates. + Voip, +} + +/// Opus coding mode (RFC 6716 §2). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Mode { + /// MDCT transform coding only. + Celt, + /// Linear-prediction coding only. + Silk, + /// SILK below 8 kHz plus CELT above. + Hybrid, +} + +pub use crate::opus::Bandwidth; + +/// Mode and bandwidth for a per-channel bitrate (bits per second per channel). +fn choose_mode(app: Application, per_channel: u32) -> (Mode, Bandwidth) { + match app { + Application::Voip => match per_channel { + 0..10_000 => (Mode::Silk, Bandwidth::Narrowband), + 10_000..12_000 => (Mode::Silk, Bandwidth::Mediumband), + 12_000..18_000 => (Mode::Silk, Bandwidth::Wideband), + 18_000..28_000 => (Mode::Hybrid, Bandwidth::SuperWideband), + 28_000..40_000 => (Mode::Hybrid, Bandwidth::Fullband), + _ => (Mode::Celt, Bandwidth::Fullband), + }, + Application::Audio => match per_channel { + 0..16_000 => (Mode::Silk, Bandwidth::Wideband), + 16_000..36_000 => (Mode::Hybrid, Bandwidth::Fullband), + _ => (Mode::Celt, Bandwidth::Fullband), + }, + } +} + +/// SILK side of a SILK-only or hybrid stream. +struct SilkPath { + enc: SilkEncoder, + down: Vec, + /// Bits per frame aimed at (excluding the TOC byte in SILK-only mode). + target_bits: f64, + /// Bits saved (positive) or overspent by previous frames (SILK-only mode). + reservoir: f64, +} + +/// The name EffectCraft's `effectcraft-opusenc` used, kept so it can re-export this module. +#[doc(hidden)] +pub type OpusEncoder = Encoder; + +/// Opus encoder for one mono or stereo stream at 48 kHz. +pub struct Encoder { + channels: usize, + application: Application, + mode: Mode, + bandwidth: Bandwidth, + /// Requested bitrate (clamped), bits per second. + bitrate_bps: u32, + /// Payload bytes per packet in CELT and hybrid modes (the packet is one byte longer: the + /// TOC). + frame_bytes: usize, + mdct: Mdct, + /// Last input sample of each channel (pre-emphasis filter memory, ×32768). + preemph_mem: [f32; 2], + /// Last `OVERLAP` pre-emphasised samples of each channel. + hist: Vec, + /// Quantised band energies, exactly as the decoder holds them. + old_band_e: [f32; 2 * NB_EBANDS], + block: Vec, + freq: Vec, + silk: Option, +} + +impl Encoder { + /// Samples per channel per packet (20 ms at 48 kHz). + pub const FRAME_SIZE: usize = N; + + /// Creates a general-audio encoder ([`Application::Audio`]) for `channels` (1 or 2) + /// channels of 48 kHz audio at `bitrate_bps` (total for all channels). + pub fn new(channels: u8, bitrate_bps: u32) -> Result { + Self::with_application(channels, bitrate_bps, Application::Audio) + } + + /// Creates an encoder for `channels` (1 or 2) channels of 48 kHz audio at `bitrate_bps` + /// (total for all channels; clamped to 6 kb/s per channel – 510 kb/s), choosing the mode + /// and bandwidth for `application`. + pub fn with_application(channels: u8, bitrate_bps: u32, application: Application) -> Result { + // Checked before the clamp below, whose lower bound passes its upper one from 86 channels. + if channels != 1 && channels != 2 { + return Err(Error::Channels(channels)); + } + let c = channels as u32; + let (mode, bandwidth) = choose_mode(application, bitrate_bps.clamp(6_000 * c, 510_000) / c); + Self::build(channels, bitrate_bps, application, mode, bandwidth) + } + + /// Creates an encoder with an explicit mode and bandwidth instead of the application's + /// table. Valid combinations: SILK with narrowband, mediumband or wideband; hybrid with + /// super-wideband or fullband; CELT with fullband. + /// + /// Any other combination is [`Error::ModeBandwidth`]; `channels` other than 1 or 2 is + /// [`Error::Channels`]. + pub fn with_mode(channels: u8, bitrate_bps: u32, mode: Mode, bandwidth: Bandwidth) -> Result { + let ok = match mode { + Mode::Silk => bandwidth <= Bandwidth::Wideband, + Mode::Hybrid => bandwidth >= Bandwidth::SuperWideband, + Mode::Celt => bandwidth == Bandwidth::Fullband, + }; + if !ok { + return Err(Error::ModeBandwidth(mode, bandwidth)); + } + Self::build(channels, bitrate_bps, Application::Audio, mode, bandwidth) + } + + fn build(channels: u8, bitrate_bps: u32, application: Application, mode: Mode, bandwidth: Bandwidth) -> Result { + if channels != 1 && channels != 2 { + return Err(Error::Channels(channels)); + } + let c = channels as usize; + let bitrate_bps = bitrate_bps.clamp(6_000 * c as u32, 510_000); + let packet_bytes = (bitrate_bps as usize).div_ceil(400); + let frame_bytes = packet_bytes.saturating_sub(1).clamp(MIN_FRAME_BYTES, MAX_FRAME_BYTES); + let silk = match mode { + Mode::Celt => None, + Mode::Silk | Mode::Hybrid => { + let fs_khz = match bandwidth { + Bandwidth::Narrowband => 8, + Bandwidth::Mediumband => 12, + _ => 16, + }; + let target_bits = if mode == Mode::Silk { + bitrate_bps as f64 / 50.0 - 8.0 + } else { + // SILK gets most of a hybrid packet; CELT codes 8 kHz and up with the rest. + let per = (bitrate_bps / c as u32) as f64; + let share = if bandwidth == Bandwidth::SuperWideband { 0.72 } else { 0.62 }; + c as f64 * (per * share).min(per - 6_000.0).max(per * 0.5) / 50.0 + }; + Some(SilkPath { + enc: SilkEncoder::new(fs_khz, c), + down: (0..c).map(|_| Downsampler::new(fs_khz as u32 * 1000)).collect(), + target_bits, + reservoir: 0.0, + }) + } + }; + Ok(Encoder { + channels: c, + application, + mode, + bandwidth, + bitrate_bps, + frame_bytes, + mdct: Mdct::new(N), + preemph_mem: [0.0; 2], + hist: vec![0.0; c * OVERLAP], + old_band_e: [0.0; 2 * NB_EBANDS], + block: vec![0.0; N + OVERLAP], + freq: vec![0.0; c * N], + silk, + }) + } + + /// Number of channels. + pub fn channels(&self) -> u8 { + self.channels as u8 + } + + /// The application the encoder was created for. + pub fn application(&self) -> Application { + self.application + } + + /// Coding mode of every packet of the stream. + pub fn mode(&self) -> Mode { + self.mode + } + + /// Coded audio bandwidth of every packet of the stream. + pub fn bandwidth(&self) -> Bandwidth { + self.bandwidth + } + + /// Bitrate in bits per second: the constant packet size × 50 packets per second in CELT + /// and hybrid modes, the (average) target in SILK mode. + pub fn bitrate(&self) -> u32 { + match self.mode { + Mode::Silk => self.bitrate_bps, + _ => ((self.frame_bytes + 1) * 8 * 50) as u32, + } + } + + /// Samples at 48 kHz the decoder must discard from the start of the stream (the `OpusHead` + /// pre-skip): the encoder's total delay. CELT: the 120-sample MDCT overlap. SILK/hybrid: + /// the decimator (83 samples, 88 for narrowband) plus the decoder's SILK delay (one + /// internal-rate sample and the resampler delay of RFC 6716 Table 54), which also rounds + /// to 120 samples. + pub fn pre_skip(&self) -> u16 { + let (fs, table54_ms) = match (self.mode, self.bandwidth) { + (Mode::Celt, _) => return OVERLAP as u16, + (_, Bandwidth::Narrowband) => (8_000, 0.538), + (_, Bandwidth::Mediumband) => (12_000, 0.692), + _ => (16_000, 0.706), + }; + (resample::delay(fs) as f64 + 48_000.0 / fs as f64 + table54_ms * 48.0).round() as u16 + } + + /// The 19-byte `OpusHead` identification header (RFC 7845 §5.1): version 1, channel count, + /// pre-skip, input sample rate 48000, output gain 0, channel mapping family 0. + pub fn opus_head(&self) -> Vec { + let mut h = Vec::with_capacity(19); + h.extend_from_slice(b"OpusHead"); + h.push(1); + h.push(self.channels as u8); + h.extend_from_slice(&self.pre_skip().to_le_bytes()); + h.extend_from_slice(&48_000u32.to_le_bytes()); + h.extend_from_slice(&0i16.to_le_bytes()); + h.push(0); + h + } + + /// TOC byte (RFC 6716 §3.1, Table 2) of a 20 ms single-frame packet. + fn toc(&self) -> u8 { + let config: u8 = match (self.mode, self.bandwidth) { + (Mode::Silk, Bandwidth::Narrowband) => 1, + (Mode::Silk, Bandwidth::Mediumband) => 5, + (Mode::Silk, _) => 9, + (Mode::Hybrid, Bandwidth::SuperWideband) => 13, + (Mode::Hybrid, _) => 15, + (Mode::Celt, _) => 31, + }; + (config << 3) | if self.channels == 2 { 4 } else { 0 } + } + + /// Encodes one 20 ms frame of interleaved f32 samples in [-1, 1] (exactly + /// `FRAME_SIZE * channels` values) and returns one Opus packet, or + /// [`Error::FrameLength`] for any other length. + pub fn encode_float(&mut self, pcm: &[f32]) -> Result, Error> { + let c = self.channels; + if pcm.len() != N * c { + return Err(Error::FrameLength { expected: N * c, got: pcm.len() }); + } + let mut packet = vec![self.toc()]; + match self.mode { + Mode::Celt => { + let (log_e, silence) = self.celt_analysis(pcm); + let len = self.frame_bytes; + packet.extend_from_slice(&self.encode_celt(RangeEncoder::new(), len, 0, NB_EBANDS, &log_e, silence)); + } + Mode::Silk => { + let x = self.silk_input(pcm); + // The SILK state exists whenever the mode uses SILK (set with the mode). + if let Some(sp) = self.silk.as_mut() { + let target = sp.target_bits + 0.25 * sp.reservoir; + let mut enc = RangeEncoder::new(); + sp.enc.encode(&x, target.max(24.0), (MAX_FRAME_BYTES * 8) as i32, &mut enc); + let bytes = (enc.tell() as usize).div_ceil(8).max(2); + let lim = 4.0 * sp.target_bits; + sp.reservoir = (sp.reservoir + sp.target_bits - (bytes * 8) as f64).clamp(-lim, lim); + packet.extend_from_slice(&enc.done(bytes)); + } + } + Mode::Hybrid => { + let x = self.silk_input(pcm); + let len = self.frame_bytes; + let total = (len * 8) as i32; + let celt_min = (total / 5).max(80); + let mut enc = RangeEncoder::new(); + if let Some(sp) = self.silk.as_mut() { + sp.enc.encode(&x, sp.target_bits, total - celt_min, &mut enc); + } + // No redundancy (RFC 6716 §4.5.1); the flag is present when there is room. + if enc.tell() + 17 + 20 <= total { + enc.bit_logp(false, 12); + } + let (log_e, _) = self.celt_analysis(pcm); + let end = if self.bandwidth == Bandwidth::SuperWideband { 19 } else { NB_EBANDS }; + packet.extend_from_slice(&self.encode_celt(enc, len, HYBRID_START_BAND, end, &log_e, false)); + } + } + Ok(packet) + } + + /// Decimates the input to the SILK internal rate (16-bit scale), one vector per channel. + fn silk_input(&mut self, pcm: &[f32]) -> Vec> { + let c = self.channels; + let Some(sp) = self.silk.as_mut() else { return vec![vec![]; c] }; + let mut out = Vec::with_capacity(c); + let mut tmp = vec![0f32; N]; + for ch in 0..c { + for (j, t) in tmp.iter_mut().enumerate() { + let s = pcm[j * c + ch]; + *t = if s.is_finite() { s.clamp(-1.0, 1.0) * 32768.0 } else { 0.0 }; + } + let mut y = Vec::with_capacity(N / 3); + sp.down[ch].process(&tmp, &mut y); + out.push(y); + } + out + } + + /// Pre-emphasis, the MDCT, band energies (log2, relative to `E_MEANS`) and normalised + /// bands; returns the energies and whether the frame is digital silence. + fn celt_analysis(&mut self, pcm: &[f32]) -> ([f32; 2 * NB_EBANDS], bool) { + let c = self.channels; + let mut log_e = [0f32; 2 * NB_EBANDS]; + let mut peak = 0f32; + for ch in 0..c { + self.block[..OVERLAP].copy_from_slice(&self.hist[ch * OVERLAP..(ch + 1) * OVERLAP]); + let mut mem = self.preemph_mem[ch]; + for j in 0..N { + let s = pcm[j * c + ch]; + let s = if s.is_finite() { s.clamp(-2.0, 2.0) * 32768.0 } else { 0.0 }; + let v = s - PREEMPH * mem; + mem = s; + self.block[OVERLAP + j] = v; + } + self.preemph_mem[ch] = mem; + self.hist[ch * OVERLAP..(ch + 1) * OVERLAP].copy_from_slice(&self.block[N..]); + peak = self.block.iter().fold(peak, |p, v| p.max(v.abs())); + let freq = &mut self.freq[ch * N..(ch + 1) * N]; + self.mdct.forward(&self.block, freq); + for i in 0..NB_EBANDS { + let lo = (EBANDS[i] as usize) << LM; + let hi = (EBANDS[i + 1] as usize) << LM; + let e = (1e-27f32 + freq[lo..hi].iter().map(|v| v * v).sum::()).sqrt(); + log_e[ch * NB_EBANDS + i] = e.log2() - E_MEANS[i]; + let g = 1.0 / e; + for v in freq[lo..hi].iter_mut() { + *v *= g; + } + } + } + (log_e, peak < 1e-4) + } + + /// Codes one CELT frame (RFC 6716 §4.3, in bitstream order) of `len` bytes into `enc` + /// (which already holds the SILK frame in hybrid mode), coding bands `start..end`, and + /// finalises the frame. + #[allow(clippy::too_many_arguments)] + fn encode_celt(&mut self, mut enc: RangeEncoder, len: usize, start: usize, end: usize, log_e: &[f32; 2 * NB_EBANDS], silence: bool) -> Vec { + let m = celt_mode(); + let c = self.channels; + if c == 1 { + for i in 0..NB_EBANDS { + self.old_band_e[i] = self.old_band_e[i].max(self.old_band_e[NB_EBANDS + i]); + } + } + if silence && start == 0 { + // The silence flag; the decoder treats every remaining bit as consumed. + enc.bit_logp(true, 15); + self.old_band_e = [-28.0; 2 * NB_EBANDS]; + return enc.done(2); + } + let total_bits_raw = len as i32 * 8; + if enc.tell() == 1 { + enc.bit_logp(false, 15); + } + // No pitch post-filter (only signalled in CELT-only frames). + if start == 0 && enc.tell() + 16 <= total_bits_raw { + enc.bit_logp(false, 1); + } + // Long blocks only. + if enc.tell() + 3 <= total_bits_raw { + enc.bit_logp(false, 3); + } + // Coarse energy, choosing intra or inter prediction by trial (whichever is cheaper). + if enc.tell() + 3 <= total_bits_raw { + let mut enc_intra = enc.clone(); + let mut old_intra = self.old_band_e; + enc_intra.bit_logp(true, 3); + quant_coarse_energy(start, end, log_e, &mut old_intra, true, &mut enc_intra, c, LM, total_bits_raw); + enc.bit_logp(false, 3); + let mut old_inter = self.old_band_e; + quant_coarse_energy(start, end, log_e, &mut old_inter, false, &mut enc, c, LM, total_bits_raw); + if enc_intra.tell_frac() < enc.tell_frac() { + enc = enc_intra; + self.old_band_e = old_intra; + } else { + self.old_band_e = old_inter; + } + } else { + quant_coarse_energy(start, end, log_e, &mut self.old_band_e, false, &mut enc, c, LM, total_bits_raw); + } + // TF resolution: no changes. + { + let mut budget = total_bits_raw; + let mut tell = enc.tell(); + let mut logp = 4; + let tf_select_rsv = LM > 0 && tell + logp + 1 <= budget; + budget -= tf_select_rsv as i32; + for _ in start..end { + if tell + logp <= budget { + enc.bit_logp(false, logp as u32); + tell = enc.tell(); + } + logp = 5; + } + if tf_select_rsv && TF_SELECT_TABLE[LM][0] != TF_SELECT_TABLE[LM][2] { + enc.bit_logp(false, 1); + } + } + if enc.tell() + 4 <= total_bits_raw { + enc.icdf(SPREAD_NORMAL, &SPREAD_ICDF, 5); + } + // Dynamic allocation: no boosts. + let cap = m.init_caps(LM, c); + let offsets = [0i32; NB_EBANDS]; + let total_bits = total_bits_raw << BITRES; + let mut tellf = enc.tell_frac(); + for &cp in cap.iter().take(end).skip(start) { + if tellf + (6 << BITRES) < total_bits && 0 < cp { + enc.bit_logp(false, 6); + tellf = enc.tell_frac(); + } + } + let alloc_trim = 5; + if tellf + (6 << BITRES) <= total_bits { + enc.icdf(alloc_trim as usize, &TRIM_ICDF, 7); + } + let bits = (total_bits_raw << BITRES) - enc.tell_frac() - 1; + let alloc = compute_allocation(m, start, end, &offsets, &cap, alloc_trim, bits, c, LM, &mut enc); + quant_fine_energy(start, end, log_e, &mut self.old_band_e, &alloc.fine_quant, &mut enc, c); + quant_all_bands( + m, + start, + end, + &self.freq, + N, + c, + &alloc.pulses, + SPREAD_NORMAL, + alloc.dual_stereo, + alloc.intensity, + total_bits_raw << BITRES, + alloc.balance, + &mut enc, + LM, + alloc.coded_bands, + ); + let bits_left = total_bits_raw - enc.tell(); + quant_energy_finalise(start, end, log_e, &mut self.old_band_e, &alloc.fine_quant, &alloc.fine_priority, bits_left, &mut enc, c); + debug_assert!(enc.tell() <= total_bits_raw, "frame overflow: {} > {}", enc.tell(), total_bits_raw); + if c == 1 { + let (a, b) = self.old_band_e.split_at_mut(NB_EBANDS); + b.copy_from_slice(a); + } + // The decoder forgets the energies of bands it did not code. + for ch in 0..2 { + for i in (0..start).chain(end..NB_EBANDS) { + self.old_band_e[ch * NB_EBANDS + i] = 0.0; + } + } + enc.done(len) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn opus_head_layout() { + let e = Encoder::new(2, 96_000).unwrap(); + let h = e.opus_head(); + assert_eq!(&h[..8], b"OpusHead"); + assert_eq!(h[8], 1); + assert_eq!(h[9], 2); + assert_eq!(u16::from_le_bytes([h[10], h[11]]), e.pre_skip()); + assert_eq!(u32::from_le_bytes([h[12], h[13], h[14], h[15]]), 48_000); + assert_eq!(&h[16..], &[0, 0, 0]); + } + + #[test] + fn packet_sizes_follow_bitrate() { + for (ch, rate) in [(1u8, 64_000u32), (2, 128_000), (2, 256_000)] { + let mut e = Encoder::new(ch, rate).unwrap(); + let pcm: Vec = (0..N * ch as usize).map(|i| (i as f32 * 0.05).sin() * 0.5).collect(); + let p = e.encode_float(&pcm).unwrap(); + assert_eq!(p.len(), rate as usize / 400); + assert_eq!(p[0], 0xF8 | if ch == 2 { 4 } else { 0 }); + assert_eq!(e.bitrate(), rate); + } + } + + #[test] + fn silence_is_a_tiny_packet() { + let mut e = Encoder::new(1, 64_000).unwrap(); + let p = e.encode_float(&vec![0.0; N]).unwrap(); + assert_eq!(p.len(), 3); + } + + #[test] + fn wrong_frame_length_is_an_error() { + let mut e = Encoder::new(2, 128_000).unwrap(); + assert_eq!(e.encode_float(&vec![0.0; N]), Err(Error::FrameLength { expected: 2 * N, got: N })); + assert_eq!(e.encode_float(&[]), Err(Error::FrameLength { expected: 2 * N, got: 0 })); + assert!(e.encode_float(&vec![0.0; 2 * N]).is_ok()); + } +} diff --git a/crates/audio/src/opus/encoder/range.rs b/crates/audio/src/opus/encoder/range.rs new file mode 100644 index 000000000..daedd58ae --- /dev/null +++ b/crates/audio/src/opus/encoder/range.rs @@ -0,0 +1,472 @@ +//! Range encoder (RFC 6716 §5.1), the exact inverse of the §4.1 range decoder. +//! +//! Range-coded symbols are written from the front of the buffer and raw bits from the back; the +//! bit accounting ([`RangeEncoder::tell`], [`RangeEncoder::tell_frac`]) matches the decoder's, so +//! every budget decision the decoder takes can be mirrored exactly. + +const SYM_BITS: u32 = 8; +const CODE_BITS: u32 = 32; +const SYM_MAX: u32 = (1 << SYM_BITS) - 1; +const CODE_SHIFT: u32 = CODE_BITS - SYM_BITS - 1; +const CODE_TOP: u32 = 1 << (CODE_BITS - 1); +const CODE_BOT: u32 = CODE_TOP >> SYM_BITS; +/// Bit resolution of [`RangeEncoder::tell_frac`] (1/8 bit). +pub const BITRES: u32 = 3; + +/// Number of bits needed to represent `x` (0 for 0). +#[inline] +pub fn ilog(x: u32) -> i32 { + (32 - x.leading_zeros()) as i32 +} + +#[derive(Clone, Debug)] +pub struct RangeEncoder { + out: Vec, + end: Vec, + end_window: u32, + nend_bits: i32, + nbits_total: i32, + rng: u32, + low: u32, + rem: i32, + ext: u32, +} + +impl Default for RangeEncoder { + fn default() -> Self { + Self::new() + } +} + +impl RangeEncoder { + pub fn new() -> Self { + RangeEncoder { + out: Vec::new(), + end: Vec::new(), + end_window: 0, + nend_bits: 0, + nbits_total: (CODE_BITS + 1) as i32, + rng: CODE_TOP, + low: 0, + rem: -1, + ext: 0, + } + } + + /// Current range (equals the decoder's range after the same symbols). + #[cfg(test)] + pub fn rng(&self) -> u32 { + self.rng + } + + fn carry_out(&mut self, c: u32) { + if c != SYM_MAX { + let carry = c >> SYM_BITS; + if self.rem >= 0 { + self.out.push((self.rem as u32 + carry) as u8); + } + if self.ext > 0 { + let sym = (SYM_MAX + carry) & SYM_MAX; + for _ in 0..self.ext { + self.out.push(sym as u8); + } + self.ext = 0; + } + self.rem = (c & SYM_MAX) as i32; + } else { + self.ext += 1; + } + } + + #[inline] + fn normalize(&mut self) { + while self.rng <= CODE_BOT { + self.carry_out(self.low >> CODE_SHIFT); + self.low = (self.low << SYM_BITS) & (CODE_TOP - 1); + self.rng <<= SYM_BITS; + self.nbits_total += SYM_BITS as i32; + } + } + + /// Encodes the symbol with cumulative range `[fl, fh)` of total `ft`. + pub fn encode(&mut self, fl: u32, fh: u32, ft: u32) { + let r = self.rng / ft; + if fl > 0 { + self.low += self.rng - r * (ft - fl); + self.rng = r * (fh - fl); + } else { + self.rng -= r * (ft - fh); + } + self.normalize(); + } + + /// Like [`Self::encode`] with `ft = 1 << bits`. + pub fn encode_bin(&mut self, fl: u32, fh: u32, bits: u32) { + let r = self.rng >> bits; + let ft = 1u32 << bits; + if fl > 0 { + self.low += self.rng - r * (ft - fl); + self.rng = r * (fh - fl); + } else { + self.rng -= r * (ft - fh); + } + self.normalize(); + } + + /// Encodes a binary symbol whose probability of being 1 is `1/2^logp`. + pub fn bit_logp(&mut self, val: bool, logp: u32) { + let r = self.rng; + let s = r >> logp; + let r2 = r - s; + if val { + self.low += r2; + self.rng = s; + } else { + self.rng = r2; + } + self.normalize(); + } + + /// Encodes symbol `s` with an "inverse CDF" table (`ft = 1 << ftb`). + pub fn icdf(&mut self, s: usize, icdf: &[u8], ftb: u32) { + let r = self.rng >> ftb; + if s > 0 { + self.low += self.rng - r * icdf[s - 1] as u32; + self.rng = r * (icdf[s - 1] as u32 - icdf[s] as u32); + } else { + self.rng -= r * icdf[s] as u32; + } + self.normalize(); + } + + /// Encodes a uniformly distributed integer `fl` in `[0, ft)` (`ft >= 2`). + pub fn uint(&mut self, fl: u32, ft: u32) { + debug_assert!(ft > 1 && fl < ft); + let ft1 = ft - 1; + let ftb = ilog(ft1); + if ftb > 8 { + let ftb = (ftb - 8) as u32; + let top = (ft1 >> ftb) + 1; + let v = fl >> ftb; + self.encode(v, v + 1, top); + self.bits(fl & ((1 << ftb) - 1), ftb); + } else { + self.encode(fl, fl + 1, ft); + } + } + + /// Writes `bits` raw bits (0..=25) to the end of the buffer. + pub fn bits(&mut self, val: u32, bits: u32) { + if bits == 0 { + return; + } + let mut window = self.end_window; + let mut used = self.nend_bits; + if used as u32 + bits > CODE_BITS { + while used >= SYM_BITS as i32 { + self.end.push((window & SYM_MAX) as u8); + window >>= SYM_BITS; + used -= SYM_BITS as i32; + } + } + window |= val << used; + used += bits as i32; + self.end_window = window; + self.nend_bits = used; + self.nbits_total += bits as i32; + } + + /// Number of bits written so far (rounded up), identical to the decoder's `tell`. + #[inline] + pub fn tell(&self) -> i32 { + self.nbits_total - ilog(self.rng) + } + + /// Number of 1/8 bits written so far (rounded up), identical to the decoder's `tell_frac`. + pub fn tell_frac(&self) -> i32 { + let nbits = (self.nbits_total as u32) << BITRES; + let mut l = ilog(self.rng) as u32; + let mut r = self.rng >> (l - 16); + for _ in 0..BITRES { + r = (r * r) >> 15; + let b = r >> 16; + l = (l << 1) | b; + r >>= b; + } + nbits.wrapping_sub(l) as i32 + } + + /// Finalises the stream into a buffer of exactly `size` bytes (range data at the front, raw + /// bits at the back, zero padding in between; a partial raw-bit byte is merged into the byte + /// just before the full raw-bit bytes). + pub fn done(mut self, size: usize) -> Vec { + let mut l = CODE_BITS as i32 - ilog(self.rng); + let mut msk = (CODE_TOP - 1) >> l; + let mut end = (self.low.wrapping_add(msk)) & !msk; + if (end | msk) >= self.low.wrapping_add(self.rng) { + l += 1; + msk >>= 1; + end = (self.low.wrapping_add(msk)) & !msk; + } + while l > 0 { + self.carry_out(end >> CODE_SHIFT); + end = (end << SYM_BITS) & (CODE_TOP - 1); + l -= SYM_BITS as i32; + } + if self.rem >= 0 || self.ext > 0 { + self.carry_out(0); + } + let mut window = self.end_window; + let mut used = self.nend_bits; + while used >= SYM_BITS as i32 { + self.end.push((window & SYM_MAX) as u8); + window >>= SYM_BITS; + used -= SYM_BITS as i32; + } + let mut buf = vec![0u8; size]; + let full = self.end.len().min(size); + let room = size - full; + let n = self.out.len().min(room); + buf[..n].copy_from_slice(&self.out[..n]); + for (k, &b) in self.end.iter().take(full).enumerate() { + buf[size - 1 - k] = b; + } + if used > 0 && room > 0 { + buf[room - 1] |= window as u8; + } + buf + } +} + +#[cfg(test)] +pub(crate) mod dec { + //! Minimal range decoder (RFC 6716 §4.1) used to verify the encoder. + use super::*; + const CODE_EXTRA: u32 = (CODE_BITS - 2) % SYM_BITS + 1; + + pub struct RangeDecoder<'a> { + buf: &'a [u8], + offs: usize, + end_offs: usize, + end_window: u32, + nend_bits: i32, + nbits_total: i32, + rng: u32, + val: u32, + rem: u32, + } + + impl<'a> RangeDecoder<'a> { + pub fn new(buf: &'a [u8]) -> Self { + let mut d = RangeDecoder { + buf, + offs: 0, + end_offs: 0, + end_window: 0, + nend_bits: 0, + nbits_total: (CODE_BITS + 1 - ((CODE_BITS - CODE_EXTRA) / SYM_BITS) * SYM_BITS) as i32, + rng: 1 << CODE_EXTRA, + val: 0, + rem: 0, + }; + d.rem = d.read_byte(); + d.val = d.rng - 1 - (d.rem >> (SYM_BITS - CODE_EXTRA)); + d.normalize(); + d + } + fn read_byte(&mut self) -> u32 { + if self.offs < self.buf.len() { + self.offs += 1; + self.buf[self.offs - 1] as u32 + } else { + 0 + } + } + fn read_byte_from_end(&mut self) -> u32 { + if self.end_offs < self.buf.len() { + self.end_offs += 1; + self.buf[self.buf.len() - self.end_offs] as u32 + } else { + 0 + } + } + fn normalize(&mut self) { + while self.rng <= CODE_BOT { + self.nbits_total += SYM_BITS as i32; + self.rng <<= SYM_BITS; + let sym = self.rem; + self.rem = self.read_byte(); + let sym = ((sym << SYM_BITS) | self.rem) >> (SYM_BITS - CODE_EXTRA); + self.val = ((self.val << SYM_BITS).wrapping_add(SYM_MAX & !sym)) & (CODE_TOP - 1); + } + } + pub fn rng(&self) -> u32 { + self.rng + } + pub fn decode(&mut self, ft: u32) -> u32 { + let ext = self.rng / ft; + let s = self.val / ext; + ft - (s + 1).min(ft) + } + pub fn update(&mut self, fl: u32, fh: u32, ft: u32) { + let ext = self.rng / ft; + let s = ext * (ft - fh); + self.val = self.val.wrapping_sub(s); + self.rng = if fl > 0 { ext * (fh - fl) } else { self.rng - s }; + self.normalize(); + } + pub fn bit_logp(&mut self, logp: u32) -> bool { + let r = self.rng; + let d = self.val; + let s = r >> logp; + let ret = d < s; + if !ret { + self.val = d - s; + } + self.rng = if ret { s } else { r - s }; + self.normalize(); + ret + } + pub fn icdf(&mut self, icdf: &[u8], ftb: u32) -> usize { + let mut s = self.rng; + let d = self.val; + let r = s >> ftb; + let mut ret = 0usize; + let mut t; + loop { + t = s; + s = r * icdf[ret] as u32; + if d >= s { + break; + } + ret += 1; + } + self.val = d - s; + self.rng = t - s; + self.normalize(); + ret + } + pub fn uint(&mut self, ft: u32) -> u32 { + let ft1 = ft - 1; + let ftb = ilog(ft1); + if ftb > 8 { + let ftb = (ftb - 8) as u32; + let top = (ft1 >> ftb) + 1; + let s = self.decode(top); + self.update(s, s + 1, top); + (s << ftb) | self.bits(ftb) + } else { + let s = self.decode(ft); + self.update(s, s + 1, ft); + s + } + } + pub fn bits(&mut self, bits: u32) -> u32 { + let mut window = self.end_window; + let mut available = self.nend_bits; + if (available as u32) < bits { + loop { + window |= self.read_byte_from_end() << available; + available += SYM_BITS as i32; + if available > (CODE_BITS - SYM_BITS) as i32 { + break; + } + } + } + let ret = window & ((1u32 << bits) - 1); + self.end_window = window >> bits; + self.nend_bits = available - bits as i32; + self.nbits_total += bits as i32; + ret + } + pub fn tell(&self) -> i32 { + self.nbits_total - ilog(self.rng) + } + } +} + +#[cfg(test)] +mod tests { + use super::dec::RangeDecoder; + use super::*; + + struct Lcg(u32); + impl Lcg { + fn next(&mut self) -> u32 { + self.0 = self.0.wrapping_mul(1664525).wrapping_add(1013904223); + self.0 >> 8 + } + } + + #[test] + fn starts_at_one_bit() { + let e = RangeEncoder::new(); + assert_eq!(e.tell(), 1); + assert_eq!(e.tell_frac(), 8); + } + + #[test] + fn roundtrip_mixed_symbols_and_tell_matches() { + let mut rng = Lcg(7); + let icdf: [u8; 4] = [200, 120, 30, 0]; + for trial in 0..300 { + let n = 1 + (rng.next() % 300) as usize; + let mut ops = Vec::new(); + for _ in 0..n { + match rng.next() % 5 { + 0 => { + let ft = 2 + rng.next() % 1000; + ops.push((0u8, rng.next() % ft, ft)); + } + 1 => { + let logp = 1 + rng.next() % 15; + ops.push((1, rng.next().is_multiple_of(5) as u32, logp)); + } + 2 => { + let bits = 1 + rng.next() % 24; + ops.push((2, rng.next() & ((1 << bits) - 1), bits)); + } + 3 => { + let ft = 2 + rng.next() % 100_000_000; + ops.push((3, rng.next() % ft, ft)); + } + _ => ops.push((4, rng.next() % 4, 0)), + } + } + let mut e = RangeEncoder::new(); + let mut tells = Vec::new(); + for &(k, v, p) in &ops { + match k { + 0 => e.encode(v, v + 1, p), + 1 => e.bit_logp(v != 0, p), + 2 => e.bits(v, p), + 3 => e.uint(v, p), + _ => e.icdf(v as usize, &icdf, 8), + } + tells.push(e.tell()); + } + // Exactly the number of bytes `tell` says were used must suffice. + let size = (e.tell() as usize).div_ceil(8); + let final_rng = e.rng(); + let buf = e.done(size); + assert_eq!(buf.len(), size); + let mut d = RangeDecoder::new(&buf); + for (i, &(k, v, p)) in ops.iter().enumerate() { + let got = match k { + 0 => { + let s = d.decode(p); + d.update(s, s + 1, p); + s + } + 1 => d.bit_logp(p) as u32, + 2 => d.bits(p), + 3 => d.uint(p), + _ => d.icdf(&icdf, 8) as u32, + }; + assert_eq!(got, v, "trial {trial} op {i} kind {k}"); + assert_eq!(d.tell(), tells[i], "tell mismatch trial {trial} op {i}"); + } + assert_eq!(d.rng(), final_rng); + } + } +} diff --git a/crates/audio/src/opus/encoder/rate.rs b/crates/audio/src/opus/encoder/rate.rs new file mode 100644 index 000000000..c360f9da7 --- /dev/null +++ b/crates/audio/src/opus/encoder/rate.rs @@ -0,0 +1,561 @@ +//! Pulse cache and bit allocation (RFC 6716 §4.3.3, §4.3.4.1). +//! +//! The allocation must be bit-identical to the decoder's, so this mirrors FilmCraft's +//! spec-derived `filmcraft-opus` decoder (first-party, MIT OR Apache-2.0) step by step; the only +//! difference is that the encoder *writes* the band-skip, intensity and dual-stereo symbols. + +use crate::opus::encoder::range::{BITRES, RangeEncoder, ilog}; +use crate::opus::encoder::tables::{ALLOC, EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS}; + +const MAX_PSEUDO: i32 = 40; +const LOG_MAX_PSEUDO: i32 = 6; +pub const MAX_FINE_BITS: i32 = 8; +const FINE_OFFSET: i32 = 21; +pub const QTHETA_OFFSET: i32 = 4; +pub const QTHETA_OFFSET_TWOPHASE: i32 = 16; +const ALLOC_STEPS: i32 = 6; + +/// Number of pulses represented by pseudo-pulse index `i`. +pub fn get_pulses(i: i32) -> i32 { + if i < 8 { i } else { (8 + (i & 7)) << ((i >> 3) - 1) } +} + +/// Conservative (rounded up) log2 of `val` with `frac` fractional bits. +pub fn log2_frac(mut val: u32, mut frac: u32) -> i32 { + let mut l = ilog(val); + if val & val.wrapping_sub(1) != 0 { + if l > 16 { + val = ((val - 1) >> (l - 16)) + 1; + } else { + val <<= 16 - l; + } + let mut l = (l - 1) << frac; + loop { + let b = (val >> 16) as i32; + l += b << frac; + val = (val + b as u32) >> b; + val = (val * val + 0x7FFF) >> 15; + if frac == 0 { + break; + } + frac -= 1; + } + l + (val > 0x8000) as i32 + } else { + l -= 1; + l << frac + } +} + +/// PVQ codebook size V(N, K) (saturating far above 2^32). +pub fn pvq_v(n: usize, k: usize) -> u128 { + if k == 0 { + return 1; + } + if n == 0 { + return 0; + } + let mut row = vec![0u128; k + 1]; + row[0] = 1; + for _ in 0..n { + let mut prev_diag = row[0]; + for kk in 1..=k { + let up = row[kk]; + let v = up.saturating_add(row[kk - 1]).saturating_add(prev_diag); + prev_diag = up; + row[kk] = v.min(u128::MAX >> 8); + } + row[0] = 1; + } + row[k] +} + +fn fits_in32(n: usize, k: i32) -> bool { + pvq_v(n, k as usize) <= u32::MAX as u128 +} + +/// Precomputed per-mode data. +pub struct Mode { + /// log2 of band width in 1/8 bits. + pub log_n: [i32; NB_EBANDS], + cache_index: Vec, + cache_bits: Vec, + caps: Vec, +} + +impl Mode { + pub fn new() -> Mode { + let mut log_n = [0i32; NB_EBANDS]; + for (i, l) in log_n.iter_mut().enumerate() { + *l = log2_frac((EBANDS[i + 1] - EBANDS[i]) as u32, BITRES); + } + let (cache_index, cache_bits) = compute_pulse_cache(MAX_LM as i32); + let mut m = Mode { log_n, cache_index, cache_bits, caps: Vec::new() }; + m.caps = compute_caps(&m); + m + } + + #[inline] + pub fn cache(&self, lm: i32, band: usize) -> &[u8] { + let idx = self.cache_index[((lm + 1) as usize) * NB_EBANDS + band]; + &self.cache_bits[idx.max(0) as usize..] + } + + pub fn bits2pulses(&self, band: usize, lm: i32, bits: i32) -> i32 { + let cache = self.cache(lm, band); + let mut lo = 0i32; + let mut hi = cache[0] as i32; + let bits = bits - 1; + for _ in 0..LOG_MAX_PSEUDO { + let mid = (lo + hi + 1) >> 1; + if cache[mid as usize] as i32 >= bits { + hi = mid; + } else { + lo = mid; + } + } + let lo_bits = if lo == 0 { -1 } else { cache[lo as usize] as i32 }; + if bits - lo_bits <= cache[hi as usize] as i32 - bits { lo } else { hi } + } + + pub fn pulses2bits(&self, band: usize, lm: i32, pulses: i32) -> i32 { + if pulses == 0 { 0 } else { self.cache(lm, band)[pulses as usize] as i32 + 1 } + } + + /// Per-band allocation caps for this frame (`init_caps`). + pub fn init_caps(&self, lm: usize, c: usize) -> [i32; NB_EBANDS] { + let mut cap = [0i32; NB_EBANDS]; + for (i, cp) in cap.iter_mut().enumerate() { + let n = (EBANDS[i + 1] - EBANDS[i]) << lm; + *cp = (self.caps[NB_EBANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * n >> 2; + } + cap + } +} + +fn compute_pulse_cache(lm_max: i32) -> (Vec, Vec) { + let nb = NB_EBANDS; + let rows = (lm_max + 2) as usize; + let mut index = vec![-1i16; nb * rows]; + let mut entries: Vec<(usize, i32, usize)> = Vec::new(); + let mut curr = 0usize; + for i in 0..rows { + for j in 0..nb { + let n = (((EBANDS[j + 1] - EBANDS[j]) << i) >> 1) as usize; + index[i * nb + j] = -1; + 'search: for k in 0..=i { + for nn in 0..nb { + if k == i && nn >= j { + break; + } + if n == (((EBANDS[nn + 1] - EBANDS[nn]) << k) >> 1) as usize { + index[i * nb + j] = index[k * nb + nn]; + break 'search; + } + } + } + if index[i * nb + j] == -1 && n != 0 { + let mut k = 0; + while k < MAX_PSEUDO && fits_in32(n, get_pulses(k + 1)) { + k += 1; + } + index[i * nb + j] = curr as i16; + entries.push((n, k, curr)); + curr += (k + 1) as usize; + } + } + } + let mut bits = vec![0u8; curr]; + for &(n, k, off) in &entries { + let maxk = get_pulses(k) as usize; + let tmp = required_bits(n, maxk, BITRES); + for j in 1..=k { + bits[off + j as usize] = (tmp[get_pulses(j) as usize] - 1) as u8; + } + bits[off] = k as u8; + } + (index, bits) +} + +fn required_bits(n: usize, maxk: usize, frac: u32) -> Vec { + let mut out = vec![0i32; maxk + 1]; + if n == 1 { + for o in out.iter_mut().skip(1) { + *o = 1 << frac; + } + } else { + for (k, o) in out.iter_mut().enumerate().skip(1) { + *o = log2_frac(pvq_v(n, k) as u32, frac); + } + } + out +} + +fn compute_caps(m: &Mode) -> Vec { + let nb = NB_EBANDS; + let mut caps = vec![0u8; (MAX_LM + 1) * 2 * nb]; + for i in 0..=MAX_LM as i32 { + for c in 1..=2i32 { + for j in 0..nb { + let mut n0 = EBANDS[j + 1] - EBANDS[j]; + + let max_bits = if n0 << i == 1 { + c * (1 + MAX_FINE_BITS) << BITRES + } else { + let mut lm0 = 0; + if n0 > 2 { + n0 >>= 1; + lm0 -= 1; + } else if n0 <= 1 { + lm0 = i.min(1); + n0 <<= lm0; + } + let pcache = m.cache(lm0, j); + let mut mb = pcache[pcache[0] as usize] as i32 + 1; + let mut n = n0; + for k in 0..(i - lm0) { + mb <<= 1; + let offset = ((m.log_n[j] + ((lm0 + k) << BITRES)) >> 1) - QTHETA_OFFSET; + let num = 459 * ((2 * n - 1) * offset + mb); + let den = ((2 * n - 1) << 9) - 459; + let qb = ((num + (den >> 1)) / den).min(57); + mb += qb; + n <<= 1; + } + if c == 2 { + mb <<= 1; + let offset = ((m.log_n[j] + (i << BITRES)) >> 1) - if n == 2 { QTHETA_OFFSET_TWOPHASE } else { QTHETA_OFFSET }; + let ndof = 2 * n - 1 - (n == 2) as i32; + let p = if n == 2 { 512 } else { 487 }; + let num = p * (mb + ndof * offset); + let den = (ndof << 9) - p; + let qb = ((num + (den >> 1)) / den).min(if n == 2 { 64 } else { 61 }); + mb += qb; + } + let ndof = c * n + if c == 2 && n > 2 { 1 } else { 0 }; + let mut offset = ((m.log_n[j] + (i << BITRES)) >> 1) - FINE_OFFSET; + if n == 2 { + offset += (1 << BITRES) >> 2; + } + let num = mb + ndof * offset; + let den = (ndof - 1) << BITRES; + let qb = ((num + (den >> 1)) / den).min(MAX_FINE_BITS); + mb += c * qb << BITRES; + mb + }; + let w = c * ((EBANDS[j + 1] - EBANDS[j]) << i); + let v = (4 * max_bits / w) - 64; + caps[((i * 2 + c - 1) as usize) * nb + j] = v.clamp(0, 255) as u8; + } + } + } + caps +} + +/// Result of the allocation process. +pub struct Allocation { + pub coded_bands: usize, + pub intensity: usize, + pub dual_stereo: bool, + pub balance: i32, + pub pulses: [i32; NB_EBANDS], + pub fine_quant: [i32; NB_EBANDS], + pub fine_priority: [i32; NB_EBANDS], +} + +/// `clt_compute_allocation`, encoder side. Stereo frames are always coded as dual (L/R) stereo +/// with no intensity bands, and no band is skipped voluntarily. +#[allow(clippy::too_many_arguments)] +pub fn compute_allocation( + m: &Mode, + start: usize, + end: usize, + offsets: &[i32; NB_EBANDS], + cap: &[i32; NB_EBANDS], + alloc_trim: i32, + total: i32, + c: usize, + lm: usize, + enc: &mut RangeEncoder, +) -> Allocation { + let ci = c as i32; + let lmi = lm as i32; + let mut total = total.max(0); + let mut skip_start = start; + let skip_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; + total -= skip_rsv; + let mut intensity_rsv = 0; + let mut dual_stereo_rsv = 0; + if c == 2 { + intensity_rsv = LOG2_FRAC_TABLE[end - start]; + if intensity_rsv > total { + intensity_rsv = 0; + } else { + total -= intensity_rsv; + dual_stereo_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; + total -= dual_stereo_rsv; + } + } + let mut bits1 = [0i32; NB_EBANDS]; + let mut bits2 = [0i32; NB_EBANDS]; + let mut thresh = [0i32; NB_EBANDS]; + let mut trim_offset = [0i32; NB_EBANDS]; + for j in start..end { + let w = EBANDS[j + 1] - EBANDS[j]; + thresh[j] = (ci << BITRES).max((3 * w << lmi << BITRES) >> 4); + trim_offset[j] = ci * w * (alloc_trim - 5 - lmi) * (end as i32 - j as i32 - 1) * (1 << (lmi + BITRES as i32)) >> 6; + if w << lmi == 1 { + trim_offset[j] -= ci << BITRES; + } + } + let nb_alloc = ALLOC.len() as i32; + let mut lo = 1; + let mut hi = nb_alloc - 1; + loop { + let mut done = false; + let mut psum = 0; + let mid = (lo + hi) >> 1; + for j in (start..end).rev() { + let n = EBANDS[j + 1] - EBANDS[j]; + let mut bitsj = ci * n * (ALLOC[mid as usize][j] as i32) << lmi >> 2; + if bitsj > 0 { + bitsj = (bitsj + trim_offset[j]).max(0); + } + bitsj += offsets[j]; + if bitsj >= thresh[j] || done { + done = true; + psum += bitsj.min(cap[j]); + } else if bitsj >= ci << BITRES { + psum += ci << BITRES; + } + } + if psum > total { + hi = mid - 1; + } else { + lo = mid + 1; + } + if lo > hi { + break; + } + } + hi = lo; + lo -= 1; + for j in start..end { + let n = EBANDS[j + 1] - EBANDS[j]; + let mut bits1j = ci * n * (ALLOC[lo as usize][j] as i32) << lmi >> 2; + let mut bits2j = if hi >= nb_alloc { cap[j] } else { ci * n * (ALLOC[hi as usize][j] as i32) << lmi >> 2 }; + if bits1j > 0 { + bits1j = (bits1j + trim_offset[j]).max(0); + } + if bits2j > 0 { + bits2j = (bits2j + trim_offset[j]).max(0); + } + if lo > 0 { + bits1j += offsets[j]; + } + bits2j += offsets[j]; + if offsets[j] > 0 { + skip_start = j; + } + bits2j = (bits2j - bits1j).max(0); + bits1[j] = bits1j; + bits2[j] = bits2j; + } + interp_bits2pulses(m, start, end, skip_start, &bits1, &bits2, &thresh, cap, total, skip_rsv, intensity_rsv, dual_stereo_rsv, c, lm, enc) +} + +#[allow(clippy::too_many_arguments)] +fn interp_bits2pulses( + m: &Mode, + start: usize, + end: usize, + skip_start: usize, + bits1: &[i32; NB_EBANDS], + bits2: &[i32; NB_EBANDS], + thresh: &[i32; NB_EBANDS], + cap: &[i32; NB_EBANDS], + mut total: i32, + skip_rsv: i32, + mut intensity_rsv: i32, + mut dual_stereo_rsv: i32, + c: usize, + lm: usize, + enc: &mut RangeEncoder, +) -> Allocation { + let ci = c as i32; + let alloc_floor = ci << BITRES; + let stereo = (c > 1) as i32; + let log_m = (lm as i32) << BITRES; + let mut lo = 0; + let mut hi = 1 << ALLOC_STEPS; + for _ in 0..ALLOC_STEPS { + let mid = (lo + hi) >> 1; + let mut psum = 0; + let mut done = false; + for j in (start..end).rev() { + let tmp = bits1[j] + (mid * bits2[j] >> ALLOC_STEPS); + if tmp >= thresh[j] || done { + done = true; + psum += tmp.min(cap[j]); + } else if tmp >= alloc_floor { + psum += alloc_floor; + } + } + if psum > total { + hi = mid; + } else { + lo = mid; + } + } + let mut bits = [0i32; NB_EBANDS]; + let mut psum = 0; + let mut done = false; + for j in (start..end).rev() { + let mut tmp = bits1[j] + (lo * bits2[j] >> ALLOC_STEPS); + if tmp < thresh[j] && !done { + tmp = if tmp >= alloc_floor { alloc_floor } else { 0 }; + } else { + done = true; + } + tmp = tmp.min(cap[j]); + bits[j] = tmp; + psum += tmp; + } + let s = start; + let mut coded_bands = end; + loop { + let j = coded_bands - 1; + if j <= skip_start { + total += skip_rsv; + break; + } + let mut left = total - psum; + let span = EBANDS[coded_bands] - EBANDS[s]; + let percoeff = left / span; + left -= span * percoeff; + let rem = (left - (EBANDS[j] - EBANDS[s])).max(0); + let band_width = EBANDS[coded_bands] - EBANDS[j]; + let band_bits = bits[j] + percoeff * band_width + rem; + if band_bits >= thresh[j].max(alloc_floor + (1 << BITRES)) { + // Keep this band (and every band below it). + enc.bit_logp(true, 1); + break; + } + psum -= bits[j] + intensity_rsv; + if intensity_rsv > 0 { + intensity_rsv = LOG2_FRAC_TABLE[j - s]; + } + psum += intensity_rsv; + if band_bits >= alloc_floor { + psum += alloc_floor; + bits[j] = alloc_floor; + } else { + bits[j] = 0; + } + coded_bands -= 1; + } + let intensity = if intensity_rsv > 0 { + // No intensity stereo: every coded band is coded in full. + enc.uint((coded_bands - s) as u32, (coded_bands + 1 - s) as u32); + coded_bands + } else { + 0 + }; + if intensity <= s { + total += dual_stereo_rsv; + dual_stereo_rsv = 0; + } + let dual_stereo = if dual_stereo_rsv > 0 { + enc.bit_logp(true, 1); + true + } else { + false + }; + let mut left = total - psum; + let span = EBANDS[coded_bands] - EBANDS[s]; + let percoeff = left / span; + left -= span * percoeff; + for j in s..coded_bands { + bits[j] += percoeff * (EBANDS[j + 1] - EBANDS[j]); + } + for j in s..coded_bands { + let tmp = left.min(EBANDS[j + 1] - EBANDS[j]); + bits[j] += tmp; + left -= tmp; + } + let mut ebits = [0i32; NB_EBANDS]; + let mut fine_priority = [0i32; NB_EBANDS]; + let mut balance = 0; + for j in s..coded_bands { + let n0 = EBANDS[j + 1] - EBANDS[j]; + let n = n0 << lm; + let bit = bits[j] + balance; + let mut excess; + if n > 1 { + excess = (bit - cap[j]).max(0); + bits[j] = bit - excess; + let den = ci * n + if c == 2 && n > 2 && !dual_stereo && j < intensity { 1 } else { 0 }; + let nclogn = den * (m.log_n[j] + log_m); + let mut offset = (nclogn >> 1) - den * FINE_OFFSET; + if n == 2 { + offset += (den << BITRES) >> 2; + } + if bits[j] + offset < den * 2 << BITRES { + offset += nclogn >> 2; + } else if bits[j] + offset < den * 3 << BITRES { + offset += nclogn >> 3; + } + let mut eb = (bits[j] + offset + (den << (BITRES - 1))).max(0); + eb = (eb / den) >> BITRES; + if ci * eb > (bits[j] >> BITRES) { + eb = bits[j] >> stereo >> BITRES; + } + eb = eb.min(MAX_FINE_BITS); + ebits[j] = eb; + fine_priority[j] = (eb * (den << BITRES) >= bits[j] + offset) as i32; + bits[j] -= ci * eb << BITRES; + } else { + excess = (bit - (ci << BITRES)).max(0); + bits[j] = bit - excess; + ebits[j] = 0; + fine_priority[j] = 1; + } + if excess > 0 { + let extra_fine = (excess >> (stereo + BITRES as i32)).min(MAX_FINE_BITS - ebits[j]); + ebits[j] += extra_fine; + let extra_bits = extra_fine * ci << BITRES; + fine_priority[j] = (extra_bits >= excess - balance) as i32; + excess -= extra_bits; + } + balance = excess; + } + for j in coded_bands..end { + ebits[j] = bits[j] >> stereo >> BITRES; + bits[j] = 0; + fine_priority[j] = (ebits[j] < 1) as i32; + } + Allocation { coded_bands, intensity, dual_stereo, balance, pulses: bits, fine_quant: ebits, fine_priority } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn caps_match_decoder_reference() { + let m = Mode::new(); + let first_rows: [u8; 42] = [ + 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224, + 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, + ]; + assert_eq!(&m.caps[..42], &first_rows[..]); + } + + #[test] + fn pvq_counts() { + assert_eq!(pvq_v(5, 1), 10); + assert_eq!(pvq_v(1, 7), 2); + assert_eq!(pvq_v(2, 9), 36); + assert_eq!(pvq_v(3, 2), 18); + } +} diff --git a/crates/audio/src/opus/encoder/resample.rs b/crates/audio/src/opus/encoder/resample.rs new file mode 100644 index 000000000..9045cb86d --- /dev/null +++ b/crates/audio/src/opus/encoder/resample.rs @@ -0,0 +1,131 @@ +//! 48 kHz → 8/12/16 kHz decimator feeding the SILK layer (own design). +//! +//! A linear-phase low-pass FIR (Kaiser-windowed sinc at 48 kHz) evaluated only at the retained +//! output phases. Its group delay ([`delay`]) is a whole number of 48 kHz samples, chosen so +//! that the SILK path (this filter + the decoder's internal-rate delay and resampler, RFC 6716 +//! Table 54) lands within a fraction of a sample of the CELT path's 120-sample MDCT overlap. + +/// Group delay of the decimator to `fs_out` in 48 kHz samples (the filter has `2 * delay + 1` +/// taps). +pub fn delay(fs_out: u32) -> usize { + if fs_out == 8_000 { 88 } else { 83 } +} + +/// Zeroth-order modified Bessel function of the first kind (power series). +fn bessel_i0(x: f64) -> f64 { + let mut sum = 1.0; + let mut term = 1.0; + let q = x * x / 4.0; + for k in 1..64 { + term *= q / (k * k) as f64; + sum += term; + if term < sum * 1e-17 { + break; + } + } + sum +} + +/// Windowed-sinc low-pass with cutoff `fc` (Hz at 48 kHz), unit DC gain. +fn design(fc: f64, beta: f64, delay: usize) -> Vec { + let wc = 2.0 * std::f64::consts::PI * fc / 48_000.0; + let i0b = bessel_i0(beta); + let mut h: Vec = (0..2 * delay + 1) + .map(|k| { + let m = k as f64 - delay as f64; + let sinc = if m == 0.0 { wc / std::f64::consts::PI } else { (wc * m).sin() / (std::f64::consts::PI * m) }; + let r = m / delay as f64; + sinc * bessel_i0(beta * (1.0 - r * r).max(0.0).sqrt()) / i0b + }) + .collect(); + let s: f64 = h.iter().sum(); + for v in h.iter_mut() { + *v /= s; + } + h.iter().map(|&v| v as f32).collect() +} + +/// Decimates one channel of 48 kHz audio by 3, 4 or 6. +#[derive(Clone)] +pub struct Downsampler { + factor: usize, + h: Vec, + taps: usize, + /// The last `taps - 1` input samples followed by the current frame. + buf: Vec, +} + +impl Downsampler { + /// `fs_out` is 8000, 12000 or 16000. + pub fn new(fs_out: u32) -> Self { + let factor = (48_000 / fs_out) as usize; + // Cutoff at 95 % of the output Nyquist frequency (pass band to ~88 %, stop band from ~110 %). + let fc = 0.95 * fs_out as f64 / 2.0; + let d = delay(fs_out); + let taps = 2 * d + 1; + Downsampler { factor, h: design(fc, 6.5, d), taps, buf: vec![0.0; taps - 1] } + } + + /// Decimates `input` (a multiple of the factor long), appending to `out`. Output sample `j` + /// is the filtered input at frame position `factor * j`, delayed by [`delay`]. + pub fn process(&mut self, input: &[f32], out: &mut Vec) { + debug_assert!(input.len().is_multiple_of(self.factor)); + let taps = self.taps; + self.buf.truncate(taps - 1); + self.buf.extend_from_slice(input); + for j in 0..input.len() / self.factor { + let t = taps - 1 + self.factor * j; + let win = &self.buf[t + 1 - taps..=t]; + // h is symmetric, so the window can be taken in forward order. + out.push(win.iter().zip(&self.h).map(|(a, b)| a * b).sum()); + } + let n = self.buf.len(); + self.buf.copy_within(n - (taps - 1).., 0); + self.buf.truncate(taps - 1); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tone(f: f64, n: usize) -> Vec { + (0..n).map(|i| (2.0 * std::f64::consts::PI * f * i as f64 / 48_000.0).sin() as f32).collect() + } + + fn rms(x: &[f32]) -> f64 { + (x.iter().map(|&v| (v as f64).powi(2)).sum::() / x.len() as f64).sqrt() + } + + #[test] + fn passes_band_and_rejects_aliases() { + for &(fs, pass, stop) in &[(16_000u32, 6_000.0, 8_600.0), (12_000, 4_500.0, 6_500.0), (8_000, 3_000.0, 4_500.0)] { + for &(f, want_pass) in &[(pass, true), (stop, false)] { + let mut d = Downsampler::new(fs); + let x = tone(f, 9600); + let mut y = Vec::new(); + for c in x.chunks(960) { + d.process(c, &mut y); + } + let r = rms(&y[y.len() / 2..]) * std::f64::consts::SQRT_2; + if want_pass { + assert!((r - 1.0).abs() < 0.02, "{fs}: {f} Hz gain {r}"); + } else { + assert!(r < 0.01, "{fs}: {f} Hz leaks {r}"); + } + } + } + } + + #[test] + fn delay_is_exact() { + let mut d = Downsampler::new(16_000); + let mut x = vec![0f32; 960]; + x[300] = 1.0; + let mut y = Vec::new(); + d.process(&x, &mut y); + // The impulse at 300 shows up centred at 48 kHz time 300 + 83 = 383 (output 127.67). + let peak = y.iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1)).map(|(i, _)| i).unwrap_or(0); + assert!((peak as f64 - (300.0 + delay(16_000) as f64) / 3.0).abs() < 1.0, "peak at {peak}"); + } +} diff --git a/crates/audio/src/opus/encoder/silk/analysis.rs b/crates/audio/src/opus/encoder/silk/analysis.rs new file mode 100644 index 000000000..439331076 --- /dev/null +++ b/crates/audio/src/opus/encoder/silk/analysis.rs @@ -0,0 +1,322 @@ +//! Encoder-side signal analysis for SILK (own design): windowed autocorrelation LPC, LPC → NLSF +//! conversion, open-loop pitch search and LTP codebook search. + +use super::tables::{CB_NB_20, CB_WB_20, LTP_FILTER, LTP_PERIODICITY, LTP_TAPS_0, LTP_TAPS_1, LTP_TAPS_2}; + +/// Short-term prediction coefficients `a` (prediction `x[n] ≈ Σ a[j] x[n-1-j]`) from the +/// windowed segment `x`, with a Gaussian lag window and white-noise correction. +pub fn lpc(x: &[f32], order: usize, fs_khz: usize) -> Vec { + let n = x.len(); + // Asymmetric window: sin² rise over the first half, flat, cos fall over the last 1/8. + let rise = n / 2; + let fall = n / 8; + let w = |i: usize| -> f64 { + if i < rise { + let s = (std::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / rise as f64).sin(); + s * s + } else if i >= n - fall { + (std::f64::consts::FRAC_PI_2 * (i + fall - n) as f64 / fall as f64 + 0.0).cos() + } else { + 1.0 + } + }; + let xw: Vec = x.iter().enumerate().map(|(i, &v)| v as f64 * w(i)).collect(); + let mut r = vec![0f64; order + 1]; + for (k, rk) in r.iter_mut().enumerate() { + *rk = xw[k..].iter().zip(&xw).map(|(a, b)| a * b).sum(); + } + if r[0] <= 1e-6 { + return vec![0.0; order]; + } + // White-noise correction (-40 dB) and a 50 Hz Gaussian lag window. + r[0] *= 1.0 + 1e-4; + let f0 = 2.0 * std::f64::consts::PI * 50.0 / (fs_khz as f64 * 1000.0); + for (k, rk) in r.iter_mut().enumerate().skip(1) { + *rk *= (-0.5 * (f0 * k as f64).powi(2)).exp(); + } + let mut a = levinson(&r, order); + // Mild bandwidth expansion keeps the NLSFs apart. + let mut g = 1.0; + for v in a.iter_mut() { + g *= 0.996; + *v *= g; + } + a +} + +/// Levinson-Durbin recursion on autocorrelation `r` (predictor convention as in [`lpc`]). +pub fn levinson(r: &[f64], order: usize) -> Vec { + let mut a = vec![0f64; order]; + let mut err = r[0]; + let mut tmp = vec![0f64; order]; + for i in 0..order { + let mut acc = r[i + 1]; + for j in 0..i { + acc -= a[j] * r[i - j]; + } + let k = (acc / err).clamp(-0.9999, 0.9999); + tmp[..i].copy_from_slice(&a[..i]); + for j in 0..i { + a[j] = tmp[j] - k * tmp[i - 1 - j]; + } + a[i] = k; + err *= 1.0 - k * k; + if err <= 0.0 { + break; + } + } + a +} + +/// Evaluates the symmetric polynomial `p` (length `d + 1`, `d` even) as the cosine series +/// `e^{jωd/2} P(e^{jω})`. +fn cos_series(p: &[f64], w: f64) -> f64 { + let h = (p.len() - 1) / 2; + let mut s = p[h]; + for k in 0..h { + s += 2.0 * p[k] * ((h - k) as f64 * w).cos(); + } + s +} + +fn roots(p: &[f64], out: &mut Vec) { + const GRID: usize = 1024; + let mut w0 = 0.0; + let mut f0 = cos_series(p, w0); + for g in 1..=GRID { + let w1 = std::f64::consts::PI * g as f64 / GRID as f64; + let f1 = cos_series(p, w1); + if f0 == 0.0 { + out.push(w0); + } else if f0 * f1 < 0.0 { + let (mut lo, mut hi, mut flo) = (w0, w1, f0); + for _ in 0..40 { + let mid = 0.5 * (lo + hi); + let fm = cos_series(p, mid); + if fm * flo <= 0.0 { + hi = mid; + } else { + lo = mid; + flo = fm; + } + } + out.push(0.5 * (lo + hi)); + } + w0 = w1; + f0 = f1; + } +} + +/// LPC → normalised line spectral frequencies in radians (ascending, `order` values), or `None` +/// when the root search fails (unstable or degenerate filter). +pub fn a2nlsf(a: &[f64]) -> Option> { + let d = a.len(); + let mut c = vec![0f64; d + 2]; + c[0] = 1.0; + for k in 0..d { + c[k + 1] = -a[k]; + } + let mut p = vec![0f64; d + 2]; + let mut q = vec![0f64; d + 2]; + for k in 0..d + 2 { + p[k] = c[k] + c[d + 1 - k]; + q[k] = c[k] - c[d + 1 - k]; + } + // Remove the trivial roots at z = -1 (P) and z = +1 (Q). + let mut p1 = vec![0f64; d + 1]; + let mut q1 = vec![0f64; d + 1]; + p1[0] = p[0]; + q1[0] = q[0]; + for k in 1..=d { + p1[k] = p[k] - p1[k - 1]; + q1[k] = q[k] + q1[k - 1]; + } + let mut r = Vec::with_capacity(d); + roots(&p1, &mut r); + roots(&q1, &mut r); + if r.len() != d { + return None; + } + r.sort_by(f64::total_cmp); + Some(r) +} + +/// Normalised cross-correlation of `x[n]` and `x[n - lag]` over `n` in `range`. +fn ncorr(x: &[f32], range: std::ops::Range, lag: usize) -> f64 { + let (mut xy, mut xx, mut yy) = (0f64, 0f64, 0f64); + for n in range { + let a = x[n] as f64; + let b = x[n - lag] as f64; + xy += a * b; + xx += a * a; + yy += b * b; + } + if xy <= 0.0 { 0.0 } else { xy / (xx * yy + 1e-9).sqrt() } +} + +pub struct Pitch { + pub lag_index: i32, + pub contour: usize, + pub lags: [i32; 4], + pub score: f64, +} + +/// Open-loop pitch search on `x` (history followed by the frame starting at `start`, `len` +/// samples, four subframes) at `fs_khz`. +pub fn pitch_search(x: &[f32], start: usize, len: usize, fs_khz: usize) -> Pitch { + let fs = fs_khz as i32; + let min_lag = 2 * fs; + let max_lag = 18 * fs - 1; + let sub = len / 4; + let nl = (max_lag - min_lag + 1) as usize; + // Whole-frame score per lag. + let full: Vec = (0..nl).map(|i| ncorr(x, start..start + len, min_lag as usize + i)).collect(); + let mut best = 0usize; + for i in 0..nl { + // Slight preference for shorter lags. + if full[i] * (1.0 - 0.0004 * i as f64) > full[best] * (1.0 - 0.0004 * best as f64) { + best = i; + } + } + let mut lag = min_lag + best as i32; + // Prefer a sub-multiple when it explains the signal almost as well (octave errors). + for div in [4, 3, 2] { + let cand = (lag as f64 / div as f64).round() as i32; + let mut cbest = (0.0, 0); + for c in cand - 1..=cand + 1 { + if c >= min_lag && c <= max_lag { + let s = full[(c - min_lag) as usize]; + if s > cbest.0 { + cbest = (s, c); + } + } + } + if cbest.1 != 0 && cbest.0 > 0.9 * full[(lag - min_lag) as usize] { + lag = cbest.1; + break; + } + } + let score = full[(lag - min_lag) as usize]; + // Contour: per-subframe lag offsets around the chosen lag. + let cb: &[[i32; 4]] = if fs_khz == 8 { &CB_NB_20 } else { &CB_WB_20 }; + let sub_score = |k: usize, l: i32| -> f64 { + let l = l.clamp(min_lag, 18 * fs); + ncorr(x, start + k * sub..start + (k + 1) * sub, l as usize) + }; + let mut best = (f64::MIN, lag, 0usize); + for l0 in (lag - 2).max(min_lag)..=(lag + 2).min(max_lag) { + for (ci, offs) in cb.iter().enumerate() { + let s: f64 = (0..4).map(|k| sub_score(k, l0 + offs[k])).sum::() - 0.002 * ci as f64; + if s > best.0 { + best = (s, l0, ci); + } + } + } + let (_, l0, ci) = best; + let mut lags = [0i32; 4]; + for k in 0..4 { + lags[k] = (l0 + cb[ci][k]).clamp(min_lag, 18 * fs); + } + Pitch { lag_index: l0 - min_lag, contour: ci, lags, score } +} + +/// Result of the LTP codebook search. +pub struct Ltp { + pub per_index: usize, + pub ltp_index: [usize; 4], + /// Residual energy after LTP prediction / before, per subframe. + pub err: [f64; 4], + pub energy: [f64; 4], +} + +fn icdf_bits(icdf: &[u8], s: usize) -> f64 { + let hi = if s == 0 { 256 } else { icdf[s - 1] as u32 }; + let p = (hi - icdf[s] as u32).max(1) as f64 / 256.0; + -p.log2() +} + +/// Searches the three LTP codebooks (RFC 6716 Tables 39–42) for the taps that best predict the +/// residual `r` (history + frame starting at `start`) from its past at the per-subframe `lags`. +pub fn ltp_search(r: &[f64], start: usize, sub: usize, lags: &[i32; 4]) -> Ltp { + let mut rr = [[0f64; 25]; 4]; + let mut cv = [[0f64; 5]; 4]; + let mut e = [0f64; 4]; + for k in 0..4 { + let s0 = start + k * sub; + let lag = lags[k] as usize; + for n in s0..s0 + sub { + let t = r[n]; + e[k] += t * t; + let base = n + 2 - lag; + for i in 0..5 { + let vi = r[base - i]; + cv[k][i] += t * vi; + for j in 0..5 { + rr[k][i * 5 + j] += vi * r[base - j]; + } + } + } + } + let books: [&[[i32; 5]]; 3] = [<P_TAPS_0, <P_TAPS_1, <P_TAPS_2]; + let mut best = (f64::MAX, 0usize, [0usize; 4], [0f64; 4]); + for (p, book) in books.iter().enumerate() { + let mut total = icdf_bits(<P_PERIODICITY, p) * 1e-3 * e.iter().sum::() / 4.0; + let mut idx = [0usize; 4]; + let mut errs = [0f64; 4]; + for k in 0..4 { + let mut bk = (f64::MAX, 0usize, 0f64); + for (i, taps) in book.iter().enumerate() { + let b: [f64; 5] = std::array::from_fn(|j| taps[j] as f64 / 128.0); + let mut err = e[k]; + for a in 0..5 { + err -= 2.0 * b[a] * cv[k][a]; + for c in 0..5 { + err += b[a] * b[c] * rr[k][a * 5 + c]; + } + } + let cost = err + icdf_bits(LTP_FILTER[p], i) * 1e-3 * e[k]; + if cost < bk.0 { + bk = (cost, i, err.max(0.0)); + } + } + total += bk.0; + idx[k] = bk.1; + errs[k] = bk.2; + } + if total < best.0 { + best = (total, p, idx, errs); + } + } + Ltp { per_index: best.1, ltp_index: best.2, err: best.3, energy: e } +} + +#[cfg(test)] +mod tests { + use super::super::lpc::nlsf2a; + use super::*; + + #[test] + fn nlsf_roundtrip_through_decoder_conversion() { + // A resonant 10th/16th-order predictor from a synthetic signal. + for &(order, fs) in &[(10usize, 8usize), (16, 16)] { + let mut st = [0f64; 4]; + let mut seed = 1u32; + let x: Vec = (0..400) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let w = (seed >> 9) as f64 / (1u32 << 23) as f64 - 1.0; + let y = w + 1.6 * st[0] - 0.9 * st[1] + 0.3 * st[2] - 0.2 * st[3]; + st = [y, st[0], st[1], st[2]]; + (y * 1000.0) as f32 + }) + .collect(); + let a = lpc(&x, order, fs); + let nlsf = a2nlsf(&a).expect("roots"); + let q15: Vec = nlsf.iter().map(|w| (w / std::f64::consts::PI * 32768.0).round() as i32).collect(); + let a_q12 = nlsf2a(&q15); + for j in 0..order { + assert!((a_q12[j] as f64 / 4096.0 - a[j]).abs() < 0.02, "order {order} coef {j}: {} vs {}", a_q12[j] as f64 / 4096.0, a[j]); + } + } + } +} diff --git a/crates/audio/src/opus/encoder/silk/lpc.rs b/crates/audio/src/opus/encoder/silk/lpc.rs new file mode 100644 index 000000000..e4e9ae624 --- /dev/null +++ b/crates/audio/src/opus/encoder/silk/lpc.rs @@ -0,0 +1,370 @@ +//! Fixed-point NLSF decoding, NLSF→LPC conversion and filter stabilisation +//! (RFC 6716 §4.2.7.5, with the RFC 8251 §6/§7 overflow fixes). +//! +//! This is the decoder's normative arithmetic, mirrored from FilmCraft's first-party, +//! spec-derived `filmcraft-opus` decoder (MIT OR Apache-2.0): the encoder must reconstruct the +//! quantised NLSFs and LPC coefficients bit-exactly as the decoder does. + +use super::tables::{ + COS_Q12, LSF_ORDER_NBMB, LSF_ORDER_WB, NLSF_CB_NBMB, NLSF_CB_WB, NLSF_MIN_SPACING_NBMB, NLSF_MIN_SPACING_WB, NLSF_PRED_NBMB, NLSF_PRED_WB, + NLSF_PSEL_NBMB, NLSF_PSEL_WB, +}; + +pub const MAX_LPC_ORDER: usize = 16; + +#[inline] +pub fn smulwb(a: i32, b: i32) -> i32 { + ((a as i64 * (b as i16) as i64) >> 16) as i32 +} +#[inline] +pub fn smlawb(a: i32, b: i32, c: i32) -> i32 { + a.wrapping_add(smulwb(b, c)) +} +#[inline] +pub fn smulww(a: i32, b: i32) -> i32 { + ((a as i64 * b as i64) >> 16) as i32 +} +#[inline] +pub fn smmul(a: i32, b: i32) -> i32 { + ((a as i64 * b as i64) >> 32) as i32 +} +#[inline] +pub fn rshift_round(a: i32, s: u32) -> i32 { + if s == 1 { (a >> 1) + (a & 1) } else { ((a >> (s - 1)) + 1) >> 1 } +} +#[inline] +pub fn rshift_round64(a: i64, s: u32) -> i64 { + if s == 1 { (a >> 1) + (a & 1) } else { ((a >> (s - 1)) + 1) >> 1 } +} +#[inline] +pub fn sat16(a: i32) -> i32 { + a.clamp(-32768, 32767) +} + +/// `silk_INVERSE32_varQ`: approximation of `(1 << q_res) / b32`. +pub fn inverse32_varq(b32: i32, q_res: i32) -> i32 { + let b_headrm = b32.unsigned_abs().leading_zeros() as i32 - 1; + let b32_nrm = b32.wrapping_shl(b_headrm as u32); + let b32_inv = (i32::MAX >> 2) / (b32_nrm >> 16); + let mut result = b32_inv << 16; + let err_q32 = ((1i32 << 29).wrapping_sub(smulwb(b32_nrm, b32_inv))).wrapping_shl(3); + result = result.wrapping_add(((err_q32 as i64 * b32_inv as i64) >> 16) as i32); + let lshift = 61 - b_headrm - q_res; + if lshift <= 0 { + let s = (-lshift) as u32; + let lim_hi = i32::MAX >> s; + let lim_lo = i32::MIN >> s; + result.clamp(lim_lo, lim_hi) << s + } else if lshift < 32 { + result >> lshift + } else { + 0 + } +} + +/// `silk_DIV32_varQ`: approximation of `(a32 << q_res) / b32`. +pub fn div32_varq(a32: i32, b32: i32, q_res: i32) -> i32 { + let a_headrm = a32.unsigned_abs().leading_zeros() as i32 - 1; + let a32_nrm = a32.wrapping_shl(a_headrm as u32); + let b_headrm = b32.unsigned_abs().leading_zeros() as i32 - 1; + let b32_nrm = b32.wrapping_shl(b_headrm as u32); + let b32_inv = (i32::MAX >> 2) / (b32_nrm >> 16); + let mut result = smulwb(a32_nrm, b32_inv); + let a32_nrm = a32_nrm.wrapping_sub(((smmul(b32_nrm, result) as i64) << 3) as i32); + result = smlawb(result, a32_nrm, b32_inv); + let lshift = 29 + a_headrm - b_headrm - q_res; + if lshift < 0 { + let s = (-lshift) as u32; + let lim_hi = i32::MAX >> s; + let lim_lo = i32::MIN >> s; + result.clamp(lim_lo, lim_hi) << s + } else if lshift < 32 { + result >> lshift + } else { + 0 + } +} + +pub fn sqrt_approx(x: i32) -> i32 { + if x <= 0 { + return 0; + } + let lz = x.leading_zeros() as i32; + let frac = (x.rotate_right((24 - lz).rem_euclid(32) as u32)) & 0x7f; + let mut y = if lz & 1 != 0 { 32768 } else { 46214 }; + y >>= lz >> 1; + smlawb(y, y, 213 * frac) +} + +/// Decodes the stage-1/stage-2 indices into stabilised NLSFs (Q15). +pub fn nlsf_decode(indices: &[i32], wb: bool) -> [i32; MAX_LPC_ORDER] { + let order = if wb { 16 } else { 10 }; + let i1 = indices[0] as usize; + let cb1: &[i32] = if wb { &NLSF_CB_WB[i1] } else { &NLSF_CB_NBMB[i1] }; + let qstep = if wb { 9830 } else { 11796 }; + // Residual dequantisation with backwards prediction. + let mut res_q10 = [0i32; MAX_LPC_ORDER]; + let mut out_q10 = 0i32; + for i in (0..order).rev() { + let pred = if i + 1 < order { + let sel = if wb { NLSF_PSEL_WB[i1][i] } else { NLSF_PSEL_NBMB[i1][i] } as usize; + let w = if wb { NLSF_PRED_WB[sel][i] } else { NLSF_PRED_NBMB[sel][i] }; + (out_q10 * w) >> 8 + } else { + 0 + }; + let mut v = indices[i + 1] << 10; + if v > 0 { + v -= 102; + } else if v < 0 { + v += 102; + } + out_q10 = smlawb(pred, v, qstep); + res_q10[i] = out_q10; + } + // Laroia weights. + let mut nlsf = [0i32; MAX_LPC_ORDER]; + for k in 0..order { + let prev = if k == 0 { 0 } else { cb1[k - 1] }; + let next = if k + 1 == order { 256 } else { cb1[k + 1] }; + let w = (1024 / (cb1[k] - prev).max(1) + 1024 / (next - cb1[k]).max(1)).min(32767); + let w_q9 = sqrt_approx(w << 16); + let v = (cb1[k] << 7) + (res_q10[k] << 14) / w_q9.max(1); + nlsf[k] = v.clamp(0, 32767); + } + let dmin: &[i32] = if wb { &NLSF_MIN_SPACING_WB } else { &NLSF_MIN_SPACING_NBMB }; + nlsf_stabilize(&mut nlsf[..order], dmin); + nlsf +} + +pub fn nlsf_stabilize(nlsf: &mut [i32], dmin: &[i32]) { + let l = nlsf.len(); + for _ in 0..20 { + let mut min_diff = nlsf[0] - dmin[0]; + let mut idx = 0; + for i in 1..l { + let d = nlsf[i] - (nlsf[i - 1] + dmin[i]); + if d < min_diff { + min_diff = d; + idx = i; + } + } + let d = 32768 - (nlsf[l - 1] + dmin[l]); + if d < min_diff { + min_diff = d; + idx = l; + } + if min_diff >= 0 { + return; + } + if idx == 0 { + nlsf[0] = dmin[0]; + } else if idx == l { + nlsf[l - 1] = 32768 - dmin[l]; + } else { + let mut min_center = dmin[..idx].iter().sum::(); + min_center += dmin[idx] >> 1; + let mut max_center = 32768 - dmin[idx + 1..=l].iter().sum::(); + max_center -= dmin[idx] >> 1; + let c = rshift_round(nlsf[idx - 1] + nlsf[idx], 1); + let c = if min_center > max_center { c.clamp(max_center, min_center) } else { c.clamp(min_center, max_center) }; + nlsf[idx - 1] = c - (dmin[idx] >> 1); + nlsf[idx] = nlsf[idx - 1] + dmin[idx]; + } + } + // Fallback. + nlsf.sort_unstable(); + nlsf[0] = nlsf[0].max(dmin[0]); + for i in 1..l { + nlsf[i] = nlsf[i].max(sat16(nlsf[i - 1] + dmin[i])); + } + nlsf[l - 1] = nlsf[l - 1].min(32768 - dmin[l]); + for i in (0..l - 1).rev() { + nlsf[i] = nlsf[i].min(nlsf[i + 1] - dmin[i + 1]); + } +} + +fn bwexpander_32(ar: &mut [i32], mut chirp_q16: i32) { + let d = ar.len(); + let chirp_minus_one = chirp_q16 - 65536; + for v in ar.iter_mut().take(d - 1) { + *v = smulww(chirp_q16, *v); + chirp_q16 += rshift_round(chirp_q16.wrapping_mul(chirp_minus_one), 16); + } + ar[d - 1] = smulww(chirp_q16, ar[d - 1]); +} + +fn lpc_inverse_pred_gain(a_q12: &[i32]) -> i32 { + const QA: u32 = 24; + const A_LIMIT: i32 = 16_773_022; + let order = a_q12.len(); + let mut a = [0i32; MAX_LPC_ORDER]; + let mut dc = 0; + for k in 0..order { + dc += a_q12[k]; + a[k] = a_q12[k] << (QA - 12); + } + if dc >= 4096 { + return 0; + } + let mut inv_gain: i32 = 1 << 30; + let mul32_frac_q31 = |x: i32, y: i32| rshift_round64(x as i64 * y as i64, 31) as i32; + for k in (1..order).rev() { + if a[k] > A_LIMIT || a[k] < -A_LIMIT { + return 0; + } + let rc_q31 = -(a[k] << (31 - QA)); + let rc_mult1 = (1i32 << 30) - smmul(rc_q31, rc_q31); + inv_gain = smmul(inv_gain, rc_mult1) << 2; + if inv_gain < 107_374 { + return 0; + } + let mult2q = 32 - rc_mult1.unsigned_abs().leading_zeros() as i32; + let rc_mult2 = inverse32_varq(rc_mult1, mult2q + 30); + for n in 0..(k + 1) >> 1 { + let t1 = a[n]; + let t2 = a[k - n - 1]; + let v1 = rshift_round64(t1.saturating_sub(mul32_frac_q31(t2, rc_q31)) as i64 * rc_mult2 as i64, mult2q as u32); + if v1 > i32::MAX as i64 || v1 < i32::MIN as i64 { + return 0; + } + let v2 = rshift_round64(t2.saturating_sub(mul32_frac_q31(t1, rc_q31)) as i64 * rc_mult2 as i64, mult2q as u32); + if v2 > i32::MAX as i64 || v2 < i32::MIN as i64 { + return 0; + } + a[n] = v1 as i32; + a[k - n - 1] = v2 as i32; + } + } + if a[0] > A_LIMIT || a[0] < -A_LIMIT { + return 0; + } + let rc_q31 = -(a[0] << (31 - QA)); + let rc_mult1 = (1i32 << 30) - smmul(rc_q31, rc_q31); + inv_gain = smmul(inv_gain, rc_mult1) << 2; + if inv_gain < 107_374 { + return 0; + } + inv_gain +} + +/// Converts NLSFs (Q15) to stable Q12 LPC coefficients (`silk_NLSF2A`). +pub fn nlsf2a(nlsf: &[i32]) -> [i32; MAX_LPC_ORDER] { + let d = nlsf.len(); + let ordering: &[usize] = if d == 16 { &LSF_ORDER_WB } else { &LSF_ORDER_NBMB }; + let mut c_q17 = [0i32; MAX_LPC_ORDER]; + for k in 0..d { + let i = (nlsf[k] >> 8) as usize; + let f = nlsf[k] & 255; + let c0 = COS_Q12[i]; + let c1 = COS_Q12[(i + 1).min(128)]; + c_q17[ordering[k]] = (c0 * 256 + (c1 - c0) * f + 4) >> 3; + } + let d2 = d / 2; + let find_poly = |off: usize| -> [i64; 10] { + let mut out = [0i64; 10]; + out[0] = 1 << 16; + out[1] = -(c_q17[off] as i64); + for k in 1..d2 { + let ftmp = c_q17[2 * k + off] as i64; + out[k + 1] = 2 * out[k - 1] - ((ftmp * out[k] + 32768) >> 16); + for n in (2..=k).rev() { + out[n] += out[n - 2] - ((ftmp * out[n - 1] + 32768) >> 16); + } + out[1] -= ftmp; + } + out + }; + let p = find_poly(0); + let q = find_poly(1); + let mut a32 = [0i32; MAX_LPC_ORDER]; + for k in 0..d2 { + let ptmp = p[k + 1] + p[k]; + let qtmp = q[k + 1] - q[k]; + a32[k] = (-qtmp - ptmp) as i32; + a32[d - k - 1] = (qtmp - ptmp) as i32; + } + let a32 = &mut a32[..d]; + // Limit the dynamic range (silk_LPC_fit with QIN = 17, QOUT = 12). + let mut a_q12 = [0i32; MAX_LPC_ORDER]; + let mut i = 0; + while i < 10 { + let mut maxabs = 0i32; + let mut idx = 0; + for (k, &v) in a32.iter().enumerate() { + let av = v.saturating_abs(); + if av > maxabs { + maxabs = av; + idx = k; + } + } + let maxabs = rshift_round(maxabs, 5); + if maxabs > 32767 { + let maxabs = maxabs.min(163_838); + let chirp = 65470 - ((maxabs - 32767) << 14) / ((maxabs * (idx as i32 + 1)) >> 2); + bwexpander_32(a32, chirp); + } else { + break; + } + i += 1; + } + if i == 10 { + for k in 0..d { + a_q12[k] = sat16(rshift_round(a32[k], 5)); + a32[k] = a_q12[k] << 5; + } + } else { + for k in 0..d { + a_q12[k] = rshift_round(a32[k], 5); + } + } + for i in 0..16 { + if lpc_inverse_pred_gain(&a_q12[..d]) == 0 { + bwexpander_32(a32, 65536 - (2 << i)); + for k in 0..d { + a_q12[k] = rshift_round(a32[k], 5); + } + } else { + break; + } + } + a_q12 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flat_nlsf_gives_small_lpc() { + // Uniformly spaced NLSFs correspond to an (almost) flat spectrum. + let nlsf: Vec = (1..=16).map(|k| k * 32768 / 17).collect(); + let a = nlsf2a(&nlsf); + assert!(a.iter().all(|v| v.abs() < 600), "{a:?}"); + let nlsf: Vec = (1..=10).map(|k| k * 32768 / 11).collect(); + let a = nlsf2a(&nlsf); + assert!(a[..10].iter().all(|v| v.abs() < 600), "{a:?}"); + } + + #[test] + fn stabilize_enforces_spacing() { + let mut v = [100, 90, 80, 30000, 30001, 30002, 31000, 32000, 32700, 32760]; + nlsf_stabilize(&mut v, &NLSF_MIN_SPACING_NBMB); + assert!(v[0] >= NLSF_MIN_SPACING_NBMB[0]); + for i in 1..10 { + assert!(v[i] - v[i - 1] >= NLSF_MIN_SPACING_NBMB[i], "{v:?}"); + } + assert!(32768 - v[9] >= NLSF_MIN_SPACING_NBMB[10]); + } + + #[test] + fn inverse_approximations() { + for &b in &[65536, 100_000, 1 << 20, 81920, 1_686_110_208] { + let inv = inverse32_varq(b, 47) as f64; + let exact = 2f64.powi(47) / b as f64; + assert!((inv - exact).abs() / exact < 1e-3, "{b}"); + } + let q = div32_varq(65536, 131072, 16) as f64; + assert!((q - 32768.0).abs() < 2.0); + } +} diff --git a/crates/audio/src/opus/encoder/silk/mod.rs b/crates/audio/src/opus/encoder/silk/mod.rs new file mode 100644 index 000000000..d82e537e0 --- /dev/null +++ b/crates/audio/src/opus/encoder/silk/mod.rs @@ -0,0 +1,714 @@ +//! SILK layer encoder (RFC 6716 §4.2, encoder direction), 20 ms frames at 8, 12 or 16 kHz. +//! +//! Each frame is analysed (VAD, open-loop pitch, windowed-autocorrelation LPC, LTP codebook +//! search), its NLSFs are quantised, and the excitation is chosen sample by sample by running +//! the decoder's exact fixed-point reconstruction (LTP and LPC synthesis with the dequantised +//! Q12/Q14 coefficients, quantisation offsets and the pseudo-random sign sequence), so the +//! encoder always holds the decoder's state and there is no drift. A noise-feedback loop +//! shapes the coding noise with a bandwidth-expanded LPC envelope, and a per-frame search over +//! a gain offset hits the bit budget. Stereo input is coded as mid/side with the decoder's +//! stereo prediction (§4.2.8). No LBRR, no NLSF interpolation. + +pub(crate) mod analysis; +pub(crate) mod lpc; +mod nlsf; +mod pulses; +#[allow(dead_code)] +pub(crate) mod tables; + +use lpc::{MAX_LPC_ORDER, div32_varq, inverse32_varq, nlsf2a, rshift_round, sat16, smlawb, smulwb, smulww}; +use tables::{ + DELTA_GAIN, GAIN_MSB, LTP_FILTER, LTP_PERIODICITY, LTP_SCALE, LTP_TAPS_0, LTP_TAPS_1, LTP_TAPS_2, MID_ONLY, NLSF_EXT, NLSF_INTERP, NLSF_SEL_NBMB, + NLSF_SEL_WB, NLSF_STAGE1, NLSF_STAGE2, PITCH_CONTOUR, PITCH_HIGH, PITCH_LOW, STEREO_PRED_JOINT, STEREO_WEIGHTS_Q13, TYPE_ACTIVE, TYPE_INACTIVE, + UNIFORM3, UNIFORM4, UNIFORM5, UNIFORM8, +}; + +use crate::opus::encoder::range::RangeEncoder; + +const MAX_FRAME: usize = 320; +const LTP_ORDER: usize = 5; +/// Frame RMS (16-bit scale) below which a frame is coded as inactive (VAD off). +const VAD_RMS: f32 = 30.0; +/// Normalised pitch correlation above which a frame is a voicing candidate. +const VOICING_THRESHOLD: f64 = 0.45; +/// Minimum LTP prediction gain (energy ratio) for a frame to be coded as voiced. +const MIN_LTP_GAIN: f64 = 1.3; +/// Rate penalty (squared pulse units per unit magnitude) of the excitation quantiser. +const RD_LAMBDA: f64 = 0.15; +/// Extra gain offset (log2) for inactive frames. +const INACTIVE_OFFSET: f64 = 1.0; +/// Noise feedback: the coding noise is shaped by `1 / A(z/γ)` (A the short-term predictor). +/// γ = 0 leaves it white (closed-loop DPCM, best waveform SNR at high rates), γ = 1 shapes it +/// like the spectral envelope (open-loop residual coding, needed at low rates). γ grows with the +/// gain offset, i.e. as the quantisation gets coarser. +fn nf_gamma(offset: f64) -> f64 { + (0.75 + 0.05 * offset).clamp(0.75, 0.9) +} + +/// `silk_log2lin` (decoder arithmetic). +fn log2lin(in_log_q7: i32) -> i32 { + if in_log_q7 < 0 { + return 0; + } + if in_log_q7 >= 3967 { + return i32::MAX; + } + let out = 1i32 << (in_log_q7 >> 7); + let frac = in_log_q7 & 0x7F; + if in_log_q7 < 2048 { + out + ((out * smlawb(frac, frac * (128 - frac), -174)) >> 7) + } else { + out + (out >> 7) * smlawb(frac, frac * (128 - frac), -174) + } +} + +fn gain_q16(index: i32) -> i32 { + log2lin((smulwb(0x1D1C71, index) + 2090).min(3967)) +} + +/// The decoder's LPC analysis filter on 16-bit samples. +fn lpc_analysis_filter(out: &mut [i16], input: &[i16], b: &[i32], d: usize) { + let len = out.len(); + for ix in d..len { + let mut acc: i32 = 0; + for j in 0..d { + acc = acc.wrapping_add((input[ix - 1 - j] as i32).wrapping_mul(b[j])); + } + let v = ((input[ix] as i32) << 12).wrapping_sub(acc); + out[ix] = sat16(rshift_round(v, 12)) as i16; + } + for v in out.iter_mut().take(d.min(len)) { + *v = 0; + } +} + +/// The part of the decoder's channel state that the reconstruction depends on. +#[derive(Clone)] +struct DecState { + prev_gain_q16: i32, + s_lpc_q14: [i32; MAX_LPC_ORDER], + out_buf: [i16; MAX_FRAME], + last_gain_index: i32, +} + +impl DecState { + fn new() -> Self { + DecState { prev_gain_q16: 65536, s_lpc_q14: [0; MAX_LPC_ORDER], out_buf: [0; MAX_FRAME], last_gain_index: 10 } + } + + /// The decoder's reset of the side channel when it is coded again after mid-only frames. + fn reset_side(&mut self) { + self.out_buf = [0; MAX_FRAME]; + self.s_lpc_q14 = [0; MAX_LPC_ORDER]; + self.last_gain_index = 10; + } +} + +/// Coded parameters of one frame (everything except gains and pulses). +#[derive(Clone, Default)] +struct Params { + vad: bool, + signal_type: usize, + quant_offset_type: usize, + nlsf_ix: [i32; 17], + a_q12: [i32; MAX_LPC_ORDER], + lag_index: i32, + contour: usize, + per_index: usize, + ltp_index: [usize; 4], + pitch_l: [i32; 4], + /// RMS (16-bit scale) of the open-loop prediction residual per subframe. + res_rms: [f32; 4], +} + +/// Gains, seed and pulses chosen by the quantiser. +struct Coded { + gain_ix: [i32; 4], + gains_q16: [i32; 4], + seed: usize, + pulses: Vec, +} + +#[derive(Clone)] +struct Channel { + fs_khz: usize, + len: usize, + sub: usize, + order: usize, + dec: DecState, + /// The last two frames of input (internal rate, 16-bit scale). + hist: Vec, + /// Recent output errors (decoded − input), most recent first, for noise feedback. + nf: [f64; MAX_LPC_ORDER], +} + +impl Channel { + fn new(fs_khz: usize) -> Self { + let len = 20 * fs_khz; + Channel { + fs_khz, + len, + sub: 5 * fs_khz, + order: if fs_khz == 16 { 16 } else { 10 }, + dec: DecState::new(), + hist: vec![0.0; 2 * len], + nf: [0.0; MAX_LPC_ORDER], + } + } + + fn push_history(&mut self, x: &[f32]) { + let l = self.len; + self.hist.copy_within(l.., 0); + self.hist[l..].copy_from_slice(x); + } + + /// Frame analysis: VAD, signal type, pitch, LPC/NLSF quantisation and LTP taps. + fn analyze(&self, x: &[f32]) -> Params { + let l = self.len; + let sub = self.sub; + let order = self.order; + let wb = order == 16; + let mut buf = self.hist.clone(); + buf.extend_from_slice(x); + let start = 2 * l; + let rms = (x.iter().map(|v| v * v).sum::() / l as f32).sqrt(); + let vad = rms > VAD_RMS; + let pitch = if vad { Some(analysis::pitch_search(&buf, start, l, self.fs_khz)) } else { None }; + let mut voiced = pitch.as_ref().is_some_and(|p| p.score > VOICING_THRESHOLD); + + let a = analysis::lpc(&buf[start - l / 4..], order, self.fs_khz); + let target: Vec = match analysis::a2nlsf(&a) { + Some(w) => w.iter().map(|v| v / std::f64::consts::PI * 32768.0).collect(), + None => (1..=order).map(|k| k as f64 * 32768.0 / (order + 1) as f64).collect(), + }; + let quant = |signal_type: usize| { + let (ix, nlsf) = nlsf::quantize(&target, signal_type, wb); + (ix, nlsf2a(&nlsf[..order])) + }; + let mut p = Params { vad, ..Default::default() }; + let (mut ix, mut a_q12) = quant(if voiced { 2 } else { 1 }); + // Open-loop residual with the quantised predictor. + let mut r = vec![0f64; buf.len()]; + for n in order..buf.len() { + let mut acc = buf[n] as f64; + for j in 0..order { + acc -= a_q12[j] as f64 / 4096.0 * buf[n - 1 - j] as f64; + } + r[n] = acc; + } + if voiced && let Some(pitch) = &pitch { + let ltp = analysis::ltp_search(&r, start, sub, &pitch.lags); + let gain = ltp.energy.iter().sum::() / ltp.err.iter().sum::().max(1e-9); + if gain >= MIN_LTP_GAIN { + p.lag_index = pitch.lag_index; + p.contour = pitch.contour; + p.pitch_l = pitch.lags; + p.per_index = ltp.per_index; + p.ltp_index = ltp.ltp_index; + } else { + voiced = false; + (ix, a_q12) = quant(1); + } + } + // Gains follow the short-term residual level (the long-term predictor then only + // reduces the number of pulses), which keeps the noise-to-signal ratio steady. + for k in 0..4 { + let e: f64 = r[start + k * sub..start + (k + 1) * sub].iter().map(|v| v * v).sum(); + p.res_rms[k] = (e / sub as f64).sqrt() as f32; + } + p.signal_type = if !vad { + 0 + } else if voiced { + 2 + } else { + 1 + }; + p.quant_offset_type = 0; + p.nlsf_ix = ix; + p.a_q12 = a_q12; + p + } + + /// Chooses gains and pulses for target `x` by running the decoder's reconstruction, and + /// advances the mirrored decoder state. `offset` scales the gains (log2), `floor` gives + /// minimum gains (Q16) per subframe. Returns the coded values and the decoded frame. + fn quantize(&mut self, p: &Params, x: &[f32], offset: f64, floor: Option<&[i32; 4]>, seed: usize) -> (Coded, Vec) { + let l = self.len; + let sub = self.sub; + let order = self.order; + let st = &mut self.dec; + let nf = &mut self.nf; + let off = if p.signal_type == 0 { offset + INACTIVE_OFFSET } else { offset }; + let gamma = nf_gamma(off); + let mut nf_c = [0f64; MAX_LPC_ORDER]; + let mut gpow = 1.0; + for j in 0..order { + gpow *= gamma; + nf_c[j] = p.a_q12[j] as f64 / 4096.0 * gpow; + } + // Gains (independent coding of the first subframe, deltas for the rest). + let mut gain_ix = [0i32; 4]; + let mut gains_q16 = [0i32; 4]; + let mut prev = st.last_gain_index; + for k in 0..4 { + let mut g = p.res_rms[k] as f64 * off.exp2(); + if let Some(f) = floor { + g = g.max(f[k] as f64 / 65536.0); + } + let want = (((g * 65536.0).max(1.0).log2() * 128.0 - 2090.0) / (1_907_825.0 / 65536.0)).round().clamp(0.0, 63.0) as i32; + if k == 0 { + gain_ix[0] = want; + prev = want.max(prev - 16).clamp(0, 63); + } else { + let mut best = (i32::MAX, 0i32, prev); + for ind in 0..41 { + let tmp = ind - 4; + let thr = 2 * 36 - 64 + prev; + let d = if tmp > thr { prev + (tmp << 1) - thr } else { prev + tmp }.clamp(0, 63); + let e = (d - want).abs(); + if e < best.0 { + best = (e, ind, d); + } + } + gain_ix[k] = best.1; + prev = best.2; + } + gains_q16[k] = gain_q16(prev); + } + st.last_gain_index = prev; + + // Analysis-by-synthesis excitation quantisation through the decoder's exact synthesis. + let voiced = p.signal_type == 2; + let offset_q10 = [[100, 240], [32, 100]][p.signal_type >> 1][p.quant_offset_type]; + let off16 = offset_q10 << 4; + let mut seed_v = seed as i32; + let mut pulses = vec![0i32; l]; + let mut xq = vec![0i16; l]; + let mut s_lpc = [0i32; MAX_FRAME / 4 + MAX_LPC_ORDER]; + s_lpc[..MAX_LPC_ORDER].copy_from_slice(&st.s_lpc_q14); + let mut s_ltp = [0i16; MAX_FRAME]; + let mut s_ltp_q15 = [0i32; 2 * MAX_FRAME]; + let ltp_mem = l; + let mut ltp_buf_idx = ltp_mem; + let a_q12 = &p.a_q12; + let ltp_scale_q14 = 15565; + for k in 0..4 { + let mut b_q14 = [0i32; LTP_ORDER]; + if voiced { + let ix = p.ltp_index[k]; + let taps = match p.per_index { + 0 => LTP_TAPS_0[ix], + 1 => LTP_TAPS_1[ix], + _ => LTP_TAPS_2[ix], + }; + for i in 0..LTP_ORDER { + b_q14[i] = taps[i] << 7; + } + } + let gain_q10 = gains_q16[k] >> 6; + let mut inv_gain_q31 = inverse32_varq(gains_q16[k], 47); + let gain_adj_q16 = if gains_q16[k] != st.prev_gain_q16 { + let g = div32_varq(st.prev_gain_q16, gains_q16[k], 16); + for v in s_lpc[..MAX_LPC_ORDER].iter_mut() { + *v = smulww(g, *v); + } + g + } else { + 1 << 16 + }; + st.prev_gain_q16 = gains_q16[k]; + let lag = p.pitch_l[k]; + if voiced { + let lag_u = lag as usize; + if k == 0 { + let start_idx = (ltp_mem as isize - lag as isize - order as isize - (LTP_ORDER / 2) as isize).max(0) as usize; + lpc_analysis_filter(&mut s_ltp[start_idx..ltp_mem], &st.out_buf[start_idx..ltp_mem], a_q12, order); + inv_gain_q31 = smulwb(inv_gain_q31, ltp_scale_q14) << 2; + for i in 0..(lag_u + LTP_ORDER / 2).min(ltp_mem) { + s_ltp_q15[ltp_buf_idx - i - 1] = smulwb(inv_gain_q31, s_ltp[ltp_mem - i - 1] as i32); + } + } else if gain_adj_q16 != 1 << 16 { + for i in 0..(lag_u + LTP_ORDER / 2).min(ltp_buf_idx) { + let q = ltp_buf_idx - i - 1; + s_ltp_q15[q] = smulww(gain_adj_q16, s_ltp_q15[q]); + } + } + } + let inv_g = 16_777_216.0 / gain_q10.max(1) as f64; + for i in 0..sub { + let n = k * sub + i; + seed_v = seed_v.wrapping_mul(196_314_165).wrapping_add(907_633_515); + let ltp_q14 = if voiced { + let base = ltp_buf_idx as isize - lag as isize + (LTP_ORDER / 2) as isize; + let g = |o: isize| -> i32 { if base - o >= 0 { s_ltp_q15[(base - o) as usize] } else { 0 } }; + let mut pred = 2i32; + for o in 0..LTP_ORDER { + pred = smlawb(pred, g(o as isize), b_q14[o]); + } + pred << 1 + } else { + 0 + }; + let mut lpc_pred = (order >> 1) as i32; + for j in 0..order { + lpc_pred = smlawb(lpc_pred, s_lpc[MAX_LPC_ORDER + i - 1 - j], a_q12[j]); + } + let lpc_q14 = lpc_pred.saturating_mul(16); + // Target excitation (Q14) for this sample. + let fb: f64 = (0..order).map(|j| nf_c[j] * nf[j]).sum(); + let tgt = (x[n] as f64 + fb).clamp(-32768.0, 32767.0) * inv_g - lpc_q14 as f64 - ltp_q14 as f64; + let sgn = if seed_v < 0 { -1.0 } else { 1.0 }; + let u = sgn * tgt; + let pf = (u - off16 as f64) / 16384.0; + let p0 = if pf > 0.0 { (pf + 0.078_125).round() } else { (pf - 0.078_125).round() } as i32; + let level = |q: i32| -> i32 { + let mut e = q << 14; + if e > 0 { + e -= 80 << 4; + } else if e < 0 { + e += 80 << 4; + } + e + off16 + }; + let mut best = (f64::MAX, 0i32); + for q in [p0 - 1, p0, p0 + 1, 0] { + let q = q.clamp(-pulses::MAX_PULSE, pulses::MAX_PULSE); + let d = (level(q) as f64 - u) / 16384.0; + let cost = d * d + RD_LAMBDA * q.abs() as f64; + if cost < best.0 { + best = (cost, q); + } + } + let q = best.1; + pulses[n] = q; + let mut e = level(q); + if seed_v < 0 { + e = -e; + } + seed_v = seed_v.wrapping_add(q); + let res = e.wrapping_add(ltp_q14); + if voiced { + s_ltp_q15[ltp_buf_idx] = res << 1; + ltp_buf_idx += 1; + } + let v = res.saturating_add(lpc_q14); + s_lpc[MAX_LPC_ORDER + i] = v; + xq[n] = sat16(rshift_round(smulww(v, gain_q10), 8)) as i16; + nf.copy_within(0..MAX_LPC_ORDER - 1, 1); + nf[0] = xq[n] as f64 - x[n] as f64; + } + s_lpc.copy_within(sub..sub + MAX_LPC_ORDER, 0); + } + st.s_lpc_q14.copy_from_slice(&s_lpc[..MAX_LPC_ORDER]); + st.out_buf[..l].copy_from_slice(&xq); + (Coded { gain_ix, gains_q16, seed, pulses }, xq) + } + + /// Writes the frame's indices and pulses (`decode_indices` + `decode_pulses` order, coded + /// independently). + fn write(&self, enc: &mut RangeEncoder, p: &Params, c: &Coded) { + let ix = p.signal_type * 2 + p.quant_offset_type; + if p.vad { + enc.icdf(ix - 2, &TYPE_ACTIVE, 8); + } else { + enc.icdf(ix, &TYPE_INACTIVE, 8); + } + enc.icdf((c.gain_ix[0] >> 3) as usize, GAIN_MSB[p.signal_type], 8); + enc.icdf((c.gain_ix[0] & 7) as usize, &UNIFORM8, 8); + for k in 1..4 { + enc.icdf(c.gain_ix[k] as usize, &DELTA_GAIN, 8); + } + let wb = self.order == 16; + let i1 = p.nlsf_ix[0] as usize; + enc.icdf(i1, NLSF_STAGE1[(p.signal_type >> 1) + if wb { 2 } else { 0 }], 8); + for i in 0..self.order { + let cb = if wb { 8 + NLSF_SEL_WB[i1][i] as usize } else { NLSF_SEL_NBMB[i1][i] as usize }; + let v = p.nlsf_ix[i + 1] + 4; + if v <= 0 { + enc.icdf(0, NLSF_STAGE2[cb], 8); + enc.icdf((-v) as usize, &NLSF_EXT, 8); + } else if v >= 8 { + enc.icdf(8, NLSF_STAGE2[cb], 8); + enc.icdf((v - 8) as usize, &NLSF_EXT, 8); + } else { + enc.icdf(v as usize, NLSF_STAGE2[cb], 8); + } + } + // No NLSF interpolation. + enc.icdf(4, &NLSF_INTERP, 8); + if p.signal_type == 2 { + let half = (self.fs_khz >> 1) as i32; + enc.icdf((p.lag_index / half) as usize, &PITCH_HIGH, 8); + let low = match self.fs_khz { + 8 => PITCH_LOW[0], + 12 => PITCH_LOW[1], + _ => PITCH_LOW[2], + }; + enc.icdf((p.lag_index % half) as usize, low, 8); + enc.icdf(p.contour, if self.fs_khz == 8 { PITCH_CONTOUR[1] } else { PITCH_CONTOUR[3] }, 8); + enc.icdf(p.per_index, <P_PERIODICITY, 8); + for k in 0..4 { + enc.icdf(p.ltp_index[k], LTP_FILTER[p.per_index], 8); + } + // LTP scaling index 0 (15565 in Q14), matching `quantize`. + enc.icdf(0, <P_SCALE, 8); + } + enc.icdf(c.seed, &UNIFORM4, 8); + pulses::encode(enc, &c.pulses, p.signal_type, p.quant_offset_type); + } +} + +/// Quantises a stereo prediction weight (Q13) to the decoder's grid (§4.2.7.1): returns the +/// (UNIFORM3, UNIFORM5, joint) indices and the reconstructed value. +fn quant_pred(w: f64) -> ([usize; 3], i32) { + let mut best = (f64::MAX, [0usize; 3], 0i32); + for i in 0..15 { + let low = STEREO_WEIGHTS_Q13[i]; + let step = smulwb(STEREO_WEIGHTS_Q13[i + 1] - low, 6554); + for j in 0..5 { + let v = low + step * (2 * j as i32 + 1); + let e = (v as f64 - w).abs(); + if e < best.0 { + best = (e, [i % 3, j, i / 3], v); + } + } + } + (best.1, best.2) +} + +/// Per-frame preparation shared by every rate-loop trial. +struct Prep { + x: [Vec; 2], + params: [Params; 2], + mid_only: bool, + pred_ix: [[usize; 3]; 2], + pred_q13: [i32; 2], +} + +/// SILK encoder for one mono or stereo (mid/side) stream. +#[derive(Clone)] +pub struct SilkEncoder { + fs_khz: usize, + channels: usize, + ch: [Channel; 2], + pred_prev_q13: [i32; 2], + prev_mid_only: bool, + /// Last mid sample of the previous frame (for the stereo predictor's low-pass). + prev_mid: f32, + frame: usize, + /// Gain offset chosen for the previous frame (search starting point). + pub last_offset: f64, +} + +impl SilkEncoder { + pub fn new(fs_khz: usize, channels: usize) -> Self { + SilkEncoder { + fs_khz, + channels, + ch: [Channel::new(fs_khz), Channel::new(fs_khz)], + pred_prev_q13: [0; 2], + prev_mid_only: false, + prev_mid: 0.0, + frame: 0, + last_offset: 1.0, + } + } + + /// Samples per channel of one 20 ms frame at the internal rate. + pub fn frame_len(&self) -> usize { + 20 * self.fs_khz + } + + fn prepare(&self, input: &[Vec]) -> Prep { + let l = self.frame_len(); + if self.channels == 1 { + let x = input[0].clone(); + let p = self.ch[0].analyze(&x); + return Prep { x: [x, vec![0.0; l]], params: [p, Params::default()], mid_only: true, pred_ix: [[0; 3]; 2], pred_q13: [0; 2] }; + } + let mid: Vec = (0..l).map(|i| 0.5 * (input[0][i] + input[1][i])).collect(); + let side: Vec = (0..l).map(|i| 0.5 * (input[0][i] - input[1][i])).collect(); + let lp = |j: usize| -> f64 { + let a = if j == 0 { self.prev_mid } else { mid[j - 1] }; + let c = if j + 1 < l { mid[j + 1] } else { mid[l - 1] }; + (a as f64 + 2.0 * mid[j] as f64 + c as f64) / 4.0 + }; + // Least-squares prediction of the side from the low-passed mid and the mid. + let (mut r00, mut r01, mut r11, mut c0, mut c1, mut ss, mut mm) = (0f64, 0f64, 0f64, 0f64, 0f64, 0f64, 0f64); + for j in 0..l { + let (a, b, s) = (lp(j), mid[j] as f64, side[j] as f64); + r00 += a * a; + r01 += a * b; + r11 += b * b; + c0 += a * s; + c1 += b * s; + ss += s * s; + mm += b * b; + } + // Ridge regularisation: the low-passed mid and the mid are nearly collinear. + let lam = 0.02 * 0.5 * (r00 + r11) + 1e-9; + let (a00, a11) = (r00 + lam, r11 + lam); + let det = a00 * a11 - r01 * r01; + let (p0, p1) = ((c0 * a11 - c1 * r01) / det, (c1 * a00 - c0 * r01) / det); + let lim = 13732.0; + let quant = |p0: f64, p1: f64| { + let (ix0, q0) = quant_pred(((p0 + p1) * 8192.0).clamp(-lim, lim)); + let (ix1, q1) = quant_pred((p1 * 8192.0).clamp(-lim, lim)); + ([ix0, ix1], [q0 - q1, q1]) + }; + // Side residual with the decoder's interpolated predictor. + let fs = self.fs_khz as i32; + let denom_q16 = (1 << 16) / (8 * fs); + let interp = 8 * self.fs_khz; + let residual = |pred_q13: [i32; 2]| -> Vec { + let d0 = rshift_round((pred_q13[0] - self.pred_prev_q13[0]) as i16 as i32 * denom_q16 as i16 as i32, 16); + let d1 = rshift_round((pred_q13[1] - self.pred_prev_q13[1]) as i16 as i32 * denom_q16 as i16 as i32, 16); + let (mut pp0, mut pp1) = (self.pred_prev_q13[0] + d0, self.pred_prev_q13[1] + d1); + (0..l) + .map(|j| { + if j + 1 < interp { + pp0 += d0; + pp1 += d1; + } else { + pp0 = pred_q13[0]; + pp1 = pred_q13[1]; + } + (side[j] as f64 - (pp0 as f64 * lp(j) + pp1 as f64 * mid[j] as f64) / 8192.0) as f32 + }) + .collect() + }; + let energy = |v: &[f32]| -> f64 { v.iter().map(|&x| (x as f64).powi(2)).sum() }; + let (mut pred_ix, mut pred_q13) = quant(p0, p1); + let mut res = residual(pred_q13); + let mut res_e = energy(&res); + // Never predict worse than not predicting at all. + if res_e > ss { + (pred_ix, pred_q13) = quant(0.0, 0.0); + res = residual(pred_q13); + res_e = energy(&res); + } + let res_rms = (res_e / l as f64).sqrt(); + let mid_rms = (mm / l as f64).sqrt(); + let mid_only = res_rms < 0.01 * mid_rms + 1.0; + let pm = self.ch[0].analyze(&mid); + let ps = if mid_only { Params::default() } else { self.ch[1].analyze(&res) }; + Prep { x: [mid, res], params: [pm, ps], mid_only, pred_ix, pred_q13 } + } + + /// Codes one frame into `enc` with gain offset `offset`. + fn code(&mut self, prep: &Prep, offset: f64, enc: &mut RangeEncoder) { + let stereo = self.channels == 2; + let side_vad = stereo && !prep.mid_only && prep.params[1].vad; + enc.bit_logp(prep.params[0].vad, 1); + enc.bit_logp(false, 1); + if stereo { + enc.bit_logp(side_vad, 1); + enc.bit_logp(false, 1); + let [a, b] = prep.pred_ix; + enc.icdf(5 * a[2] + b[2], &STEREO_PRED_JOINT, 8); + enc.icdf(a[0], &UNIFORM3, 8); + enc.icdf(a[1], &UNIFORM5, 8); + enc.icdf(b[0], &UNIFORM3, 8); + enc.icdf(b[1], &UNIFORM5, 8); + if !side_vad { + enc.icdf(prep.mid_only as usize, &MID_ONLY, 8); + } + } + let seed = self.frame & 3; + let (cm, _) = self.ch[0].quantize(&prep.params[0], &prep.x[0], offset, None, seed); + self.ch[0].write(enc, &prep.params[0], &cm); + if stereo { + if !prep.mid_only { + if self.prev_mid_only { + self.ch[1].dec.reset_side(); + } + let (cs, _) = self.ch[1].quantize(&prep.params[1], &prep.x[1], offset, Some(&cm.gains_q16), seed); + self.ch[1].write(enc, &prep.params[1], &cs); + } + self.pred_prev_q13 = prep.pred_q13; + self.prev_mid_only = prep.mid_only; + } + } + + /// Encodes one 20 ms frame (`input`: one internal-rate, 16-bit-scale vector per channel) + /// into `enc`, aiming at `target_bits` total and never exceeding `max_bits`. + pub fn encode(&mut self, input: &[Vec], target_bits: f64, max_bits: i32, enc: &mut RangeEncoder) { + let prep = self.prepare(input); + let start_bits = enc.tell(); + let trial = |s: &Self, o: f64| -> i32 { + let mut t = s.clone(); + let mut e = enc.clone(); + t.code(&prep, o, &mut e); + e.tell() - start_bits + }; + // Bisection on the gain offset: the smallest offset (finest quantisation) within budget. + let target = target_bits.min(max_bits as f64); + // Bits are not strictly monotonic in the offset (very coarse quantisation feeds large + // errors back), so walk an integer grid from the previous frame's offset to find a + // bracket [infeasible, feasible], then bisect inside it. + const MIN_O: f64 = -3.0; + const MAX_O: f64 = 6.0; + let mut best_any = (i32::MAX, MAX_O); + let mut probe = |o: f64| -> bool { + let b = trial(self, o); + if b < best_any.0 { + best_any = (b, o); + } + b as f64 <= target + }; + let g0 = self.last_offset.round().clamp(MIN_O, MAX_O); + let mut bracket = None; + if probe(g0) { + let mut hi = g0; + loop { + if hi - 1.0 < MIN_O { + bracket = Some((None, hi)); + break; + } + if probe(hi - 1.0) { + hi -= 1.0; + } else { + bracket = Some((Some(hi - 1.0), hi)); + break; + } + } + } else { + let mut lo = g0; + while lo + 1.0 <= MAX_O { + if probe(lo + 1.0) { + bracket = Some((Some(lo), lo + 1.0)); + break; + } + lo += 1.0; + } + } + let mut o = match bracket { + Some((Some(mut lo), mut hi)) => { + for _ in 0..4 { + let m = 0.5 * (lo + hi); + if probe(m) { + hi = m; + } else { + lo = m; + } + } + hi + } + Some((None, hi)) => hi, + None => best_any.1, + }; + // Hard limit (hybrid packets must leave room for CELT). + while trial(self, o) > max_bits && o < 12.0 { + o += 1.0; + } + self.last_offset = o; + self.code(&prep, o, enc); + for ch in 0..self.channels { + self.ch[ch].push_history(&prep.x[ch]); + } + if self.channels == 2 { + self.prev_mid = prep.x[0][self.frame_len() - 1]; + } + self.frame += 1; + } +} diff --git a/crates/audio/src/opus/encoder/silk/nlsf.rs b/crates/audio/src/opus/encoder/silk/nlsf.rs new file mode 100644 index 000000000..59fca68cb --- /dev/null +++ b/crates/audio/src/opus/encoder/silk/nlsf.rs @@ -0,0 +1,131 @@ +//! NLSF quantisation (encoder side of RFC 6716 §4.2.7.5): stage-1 vector codebook preselection +//! and a backwards-predictive stage-2 scalar quantiser that reproduces the decoder's residual +//! dequantisation exactly. The search strategy is our own. + +use super::lpc::{MAX_LPC_ORDER, nlsf_decode, smlawb, sqrt_approx}; +use super::tables::{ + NLSF_CB_NBMB, NLSF_CB_WB, NLSF_EXT, NLSF_PRED_NBMB, NLSF_PRED_WB, NLSF_PSEL_NBMB, NLSF_PSEL_WB, NLSF_SEL_NBMB, NLSF_SEL_WB, NLSF_STAGE1, + NLSF_STAGE2, +}; + +/// Number of stage-1 candidates refined with stage 2. +const SURVIVORS: usize = 8; +/// Rate weight (weighted squared Q15 error per bit). +const LAMBDA: f64 = 60.0; + +fn icdf_bits(icdf: &[u8], s: usize) -> f64 { + let hi = if s == 0 { 256 } else { icdf[s - 1] as u32 }; + let p = (hi - icdf[s] as u32).max(1) as f64 / 256.0; + -p.log2() +} + +/// Bits of a stage-2 index `q` (-10..=10) with stage-2 table `tab`. +fn stage2_bits(tab: &[u8], q: i32) -> f64 { + let v = q + 4; + if v <= 0 { + icdf_bits(tab, 0) + icdf_bits(&NLSF_EXT, (-v) as usize) + } else if v >= 8 { + icdf_bits(tab, 8) + icdf_bits(&NLSF_EXT, (v - 8) as usize) + } else { + icdf_bits(tab, v as usize) + } +} + +/// Quantises target NLSFs (`target`, Q15 as f64, ascending) and returns the 1 + order indices +/// in the decoder's layout (`[stage1, stage2...]`) together with the reconstructed NLSFs. +pub fn quantize(target: &[f64], signal_type: usize, wb: bool) -> ([i32; 17], [i32; MAX_LPC_ORDER]) { + let order = target.len(); + // Laroia-style weights. + let w: Vec = (0..order) + .map(|k| { + let prev = if k == 0 { 0.0 } else { target[k - 1] }; + let next = if k + 1 == order { 32768.0 } else { target[k + 1] }; + 1.0 / (target[k] - prev).max(50.0) + 1.0 / (next - target[k]).max(50.0) + }) + .collect(); + let s1_tab = NLSF_STAGE1[(signal_type >> 1) + if wb { 2 } else { 0 }]; + let n_cb = 32; + let mut cands: Vec<(f64, usize)> = (0..n_cb) + .map(|i1| { + let cb: &[i32] = if wb { &NLSF_CB_WB[i1] } else { &NLSF_CB_NBMB[i1] }; + let d: f64 = (0..order).map(|k| w[k] * ((cb[k] << 7) as f64 - target[k]).powi(2)).sum(); + (d + LAMBDA * icdf_bits(s1_tab, i1), i1) + }) + .collect(); + cands.sort_by(|a, b| a.0.total_cmp(&b.0)); + let qstep = if wb { 9830 } else { 11796 }; + let mut best = (f64::MAX, [0i32; 17], [0i32; MAX_LPC_ORDER]); + for &(_, i1) in cands.iter().take(SURVIVORS) { + let cb1: &[i32] = if wb { &NLSF_CB_WB[i1] } else { &NLSF_CB_NBMB[i1] }; + let mut ix = [0i32; 17]; + ix[0] = i1 as i32; + let mut bits = icdf_bits(s1_tab, i1); + // Exact decoder weights per coefficient. + let w_q9: Vec = (0..order) + .map(|k| { + let prev = if k == 0 { 0 } else { cb1[k - 1] }; + let next = if k + 1 == order { 256 } else { cb1[k + 1] }; + let ww = (1024 / (cb1[k] - prev).max(1) + 1024 / (next - cb1[k]).max(1)).min(32767); + sqrt_approx(ww << 16).max(1) + }) + .collect(); + let mut out_q10 = 0i32; + for i in (0..order).rev() { + let pred = if i + 1 < order { + let sel = if wb { NLSF_PSEL_WB[i1][i] } else { NLSF_PSEL_NBMB[i1][i] } as usize; + let wp = if wb { NLSF_PRED_WB[sel][i] } else { NLSF_PRED_NBMB[sel][i] }; + (out_q10 * wp) >> 8 + } else { + 0 + }; + let cb = if wb { 8 + NLSF_SEL_WB[i1][i] as usize } else { NLSF_SEL_NBMB[i1][i] as usize }; + let tab = NLSF_STAGE2[cb]; + let want_q10 = (target[i] - (cb1[i] << 7) as f64) * w_q9[i] as f64 / 16384.0; + let step = qstep as f64 * 1024.0 / 65536.0; + let q0 = ((want_q10 - pred as f64) / step).round() as i32; + let mut bq = (f64::MAX, 0i32, 0i32); + for q in (q0 - 1).max(-10)..=(q0 + 1).min(10) { + let mut v = q << 10; + if v > 0 { + v -= 102; + } else if v < 0 { + v += 102; + } + let o = smlawb(pred, v, qstep); + let nl = (cb1[i] << 7) as f64 + ((o << 14) / w_q9[i]) as f64; + let cost = w[i] * (nl - target[i]).powi(2) + LAMBDA * stage2_bits(tab, q); + if cost < bq.0 { + bq = (cost, q, o); + } + } + ix[i + 1] = bq.1; + out_q10 = bq.2; + bits += stage2_bits(tab, bq.1); + } + let nlsf = nlsf_decode(&ix, wb); + let d: f64 = (0..order).map(|k| w[k] * (nlsf[k] as f64 - target[k]).powi(2)).sum(); + let cost = d + LAMBDA * bits; + if cost < best.0 { + best = (cost, ix, nlsf); + } + } + (best.1, best.2) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn quantised_nlsfs_track_the_target() { + for wb in [false, true] { + let order = if wb { 16 } else { 10 }; + // A smooth, plausible NLSF vector. + let target: Vec = (0..order).map(|k| 32768.0 * (k as f64 + 0.8 + 0.3 * (k as f64).sin()) / (order as f64 + 1.0)).collect(); + let (ix, nlsf) = quantize(&target, 1, wb); + assert!(ix[1..=order].iter().all(|v| (-10..=10).contains(v))); + let max_err = (0..order).map(|k| (nlsf[k] as f64 - target[k]).abs()).fold(0.0, f64::max); + assert!(max_err < 1200.0, "wb={wb} max err {max_err}: {:?} vs {target:?}", &nlsf[..order]); + } + } +} diff --git a/crates/audio/src/opus/encoder/silk/pulses.rs b/crates/audio/src/opus/encoder/silk/pulses.rs new file mode 100644 index 000000000..7ec4fa6bf --- /dev/null +++ b/crates/audio/src/opus/encoder/silk/pulses.rs @@ -0,0 +1,113 @@ +//! Excitation coding (encoder side of RFC 6716 §4.2.7.8): rate level, per-block pulse counts +//! with LSB escapes, the recursive shell code, LSBs and signs, written in exactly the order the +//! decoder reads them. + +use super::tables::{EXC_LSB, EXC_SIGN, PULSE_COUNT, RATE_LEVEL, SHELL_2, SHELL_4, SHELL_8, SHELL_16}; +use crate::opus::encoder::range::RangeEncoder; + +/// Largest pulse magnitude the quantiser produces (keeps every 16-sample block codable). +pub const MAX_PULSE: i32 = 500; + +pub fn icdf_bits(icdf: &[u8], s: usize) -> f32 { + let hi = if s == 0 { 256 } else { icdf[s - 1] as u32 }; + let p = (hi - icdf[s] as u32).max(1) as f32 / 256.0; + -p.log2() +} + +fn count_table(nls: usize) -> &'static [u8] { + if nls == 10 { PULSE_COUNT[10] } else { PULSE_COUNT[9] } +} + +fn shell(enc: &mut RangeEncoder, v: &[i32], count: i32) { + let n = v.len(); + if n == 1 || count == 0 { + return; + } + let tab = match n { + 16 => SHELL_16[(count - 1) as usize], + 8 => SHELL_8[(count - 1) as usize], + 4 => SHELL_4[(count - 1) as usize], + _ => SHELL_2[(count - 1) as usize], + }; + let (a, b) = v.split_at(n / 2); + let left: i32 = a.iter().sum(); + enc.icdf(left as usize, tab, 8); + shell(enc, a, left); + shell(enc, b, count - left); +} + +/// Codes the frame's pulses (`len` a multiple of 16). +pub fn encode(enc: &mut RangeEncoder, pulses: &[i32], signal_type: usize, quant_offset_type: usize) { + let nblk = pulses.len() / 16; + let mut nls = vec![0usize; nblk]; + let mut sums = vec![0i32; nblk]; + let mut hi = vec![0i32; pulses.len()]; + for b in 0..nblk { + let blk = &pulses[b * 16..(b + 1) * 16]; + let mut s = 0usize; + loop { + let sum: i32 = blk.iter().map(|p| p.abs() >> s).sum(); + if sum <= 16 || s == 10 { + sums[b] = sum.min(16); + break; + } + s += 1; + } + nls[b] = s; + for (h, p) in hi[b * 16..(b + 1) * 16].iter_mut().zip(blk) { + *h = p.abs() >> s; + } + } + // Rate level with the cheapest pulse-count symbols. + let rl_tab = RATE_LEVEL[signal_type >> 1]; + let mut best = (f32::MAX, 0usize); + for rl in 0..9 { + let mut bits = icdf_bits(rl_tab, rl); + for b in 0..nblk { + bits += if nls[b] == 0 { icdf_bits(PULSE_COUNT[rl], sums[b] as usize) } else { icdf_bits(PULSE_COUNT[rl], 17) }; + } + if bits < best.0 { + best = (bits, rl); + } + } + let rl = best.1; + enc.icdf(rl, rl_tab, 8); + for b in 0..nblk { + if nls[b] == 0 { + enc.icdf(sums[b] as usize, PULSE_COUNT[rl], 8); + } else { + enc.icdf(17, PULSE_COUNT[rl], 8); + for j in 1..nls[b] { + enc.icdf(17, count_table(j), 8); + } + enc.icdf(sums[b] as usize, count_table(nls[b]), 8); + } + } + for b in 0..nblk { + if sums[b] > 0 { + shell(enc, &hi[b * 16..(b + 1) * 16], sums[b]); + } + } + for b in 0..nblk { + if nls[b] > 0 { + for p in &pulses[b * 16..(b + 1) * 16] { + let a = p.abs(); + for j in (0..nls[b]).rev() { + enc.icdf(((a >> j) & 1) as usize, &EXC_LSB, 8); + } + } + } + } + let base = 7 * (quant_offset_type + (signal_type << 1)); + for b in 0..nblk { + let p = sums[b] | ((nls[b] as i32) << 5); + if p > 0 { + let tab = EXC_SIGN[base + ((p & 0x1F) as usize).min(6)]; + for &q in &pulses[b * 16..(b + 1) * 16] { + if q != 0 { + enc.icdf((q > 0) as usize, tab, 8); + } + } + } + } +} diff --git a/crates/audio/src/opus/encoder/silk/tables.rs b/crates/audio/src/opus/encoder/silk/tables.rs new file mode 100644 index 000000000..a4789a414 --- /dev/null +++ b/crates/audio/src/opus/encoder/silk/tables.rs @@ -0,0 +1,543 @@ +//! SILK probability tables and codebooks, transcribed from RFC 6716 §4.2 (Tables 4–53). +//! +//! PDFs are written as in the RFC (`{...}/256`) and converted at compile time to the inverse-CDF +//! form consumed by the range coder. +//! +//! Copied from FilmCraft's first-party, spec-derived `filmcraft-opus` decoder (MIT OR +//! Apache-2.0) so encoder and decoder share exactly the same values. + +/// Converts a PDF (summing to 256) into an inverse CDF (`256 - cdf[i+1]`). +pub const fn icdf(pdf: &[u8; N]) -> [u8; N] { + let mut out = [0u8; N]; + let mut acc: u32 = 0; + let mut i = 0; + while i < N { + acc += pdf[i] as u32; + out[i] = (256 - acc) as u8; + i += 1; + } + out +} + +pub const STEREO_PRED_JOINT: [u8; 25] = icdf(&[7, 2, 1, 1, 1, 10, 24, 8, 1, 1, 3, 23, 92, 23, 3, 1, 1, 8, 24, 10, 1, 1, 1, 2, 7]); +pub const UNIFORM3: [u8; 3] = icdf(&[85, 86, 85]); +pub const UNIFORM5: [u8; 5] = icdf(&[51, 51, 52, 51, 51]); +pub const STEREO_WEIGHTS_Q13: [i32; 16] = [-13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732]; +pub const MID_ONLY: [u8; 2] = icdf(&[192, 64]); +pub const TYPE_INACTIVE: [u8; 2] = icdf(&[26, 230]); +pub const TYPE_ACTIVE: [u8; 4] = icdf(&[24, 74, 148, 10]); +pub const GAIN_MSB: [&[u8]; 3] = + [&icdf::<8>(&[32, 112, 68, 29, 12, 1, 1, 1]), &icdf::<8>(&[2, 17, 45, 60, 62, 47, 19, 4]), &icdf::<8>(&[1, 3, 26, 71, 94, 50, 9, 2])]; +pub const UNIFORM8: [u8; 8] = icdf(&[32, 32, 32, 32, 32, 32, 32, 32]); +pub const DELTA_GAIN: [u8; 41] = + icdf(&[6, 5, 11, 31, 132, 21, 8, 4, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]); +pub const NLSF_STAGE1: [&[u8]; 4] = [ + &icdf::<32>(&[44, 34, 30, 19, 21, 12, 11, 3, 3, 2, 16, 2, 2, 1, 5, 2, 1, 3, 3, 1, 1, 2, 2, 2, 3, 1, 9, 9, 2, 7, 2, 1]), + &icdf::<32>(&[1, 10, 1, 8, 3, 8, 8, 14, 13, 14, 1, 14, 12, 13, 11, 11, 12, 11, 10, 10, 11, 8, 9, 8, 7, 8, 1, 1, 6, 1, 6, 5]), + &icdf::<32>(&[31, 21, 3, 17, 1, 8, 17, 4, 1, 18, 16, 4, 2, 3, 1, 10, 1, 3, 16, 11, 16, 2, 2, 3, 2, 11, 1, 4, 9, 8, 7, 3]), + &icdf::<32>(&[1, 4, 16, 5, 18, 11, 5, 14, 15, 1, 3, 12, 13, 14, 14, 6, 14, 12, 2, 6, 1, 12, 12, 11, 10, 3, 10, 5, 1, 1, 1, 3]), +]; +pub const NLSF_STAGE2: [&[u8]; 16] = [ + &icdf::<9>(&[1, 1, 1, 15, 224, 11, 1, 1, 1]), + &icdf::<9>(&[1, 1, 2, 34, 183, 32, 1, 1, 1]), + &icdf::<9>(&[1, 1, 4, 42, 149, 55, 2, 1, 1]), + &icdf::<9>(&[1, 1, 8, 52, 123, 61, 8, 1, 1]), + &icdf::<9>(&[1, 3, 16, 53, 101, 74, 6, 1, 1]), + &icdf::<9>(&[1, 3, 17, 55, 90, 73, 15, 1, 1]), + &icdf::<9>(&[1, 7, 24, 53, 74, 67, 26, 3, 1]), + &icdf::<9>(&[1, 1, 18, 63, 78, 58, 30, 6, 1]), + &icdf::<9>(&[1, 1, 1, 9, 232, 9, 1, 1, 1]), + &icdf::<9>(&[1, 1, 2, 28, 186, 35, 1, 1, 1]), + &icdf::<9>(&[1, 1, 3, 42, 152, 53, 2, 1, 1]), + &icdf::<9>(&[1, 1, 10, 49, 126, 65, 2, 1, 1]), + &icdf::<9>(&[1, 4, 19, 48, 100, 77, 5, 1, 1]), + &icdf::<9>(&[1, 1, 14, 54, 100, 72, 12, 1, 1]), + &icdf::<9>(&[1, 1, 15, 61, 87, 61, 25, 4, 1]), + &icdf::<9>(&[1, 7, 21, 50, 77, 81, 17, 1, 1]), +]; +pub const NLSF_SEL_NBMB: [[u8; 10]; 32] = [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 3, 1, 2, 2, 1, 2, 1, 1, 1], + [2, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 2, 2, 2, 2, 1, 2, 1, 1, 1], + [2, 3, 3, 3, 3, 2, 2, 2, 2, 2], + [0, 5, 3, 3, 2, 2, 2, 2, 1, 1], + [0, 2, 2, 2, 2, 2, 2, 2, 2, 1], + [2, 3, 6, 4, 4, 4, 5, 4, 5, 5], + [2, 4, 5, 5, 4, 5, 4, 6, 4, 4], + [2, 4, 4, 7, 4, 5, 4, 5, 5, 4], + [4, 3, 3, 3, 2, 3, 2, 2, 2, 2], + [1, 5, 5, 6, 4, 5, 4, 5, 5, 5], + [2, 7, 4, 6, 5, 5, 5, 5, 5, 5], + [2, 7, 5, 5, 5, 5, 5, 6, 5, 4], + [3, 3, 5, 4, 4, 5, 4, 5, 4, 4], + [2, 3, 3, 5, 5, 4, 4, 4, 4, 4], + [2, 4, 4, 6, 4, 5, 4, 5, 5, 5], + [2, 5, 4, 6, 5, 5, 5, 4, 5, 4], + [2, 7, 4, 5, 4, 5, 4, 5, 5, 5], + [2, 5, 4, 6, 7, 6, 5, 6, 5, 4], + [3, 6, 7, 4, 6, 5, 5, 6, 4, 5], + [2, 7, 6, 4, 4, 4, 5, 4, 5, 5], + [4, 5, 5, 4, 6, 6, 5, 6, 5, 4], + [2, 5, 5, 6, 5, 6, 4, 6, 4, 4], + [4, 5, 5, 5, 3, 7, 4, 5, 5, 4], + [2, 3, 4, 5, 5, 6, 4, 5, 5, 4], + [2, 3, 2, 3, 3, 4, 2, 3, 3, 3], + [1, 1, 2, 2, 2, 2, 2, 3, 2, 2], + [4, 5, 5, 6, 6, 6, 5, 6, 4, 5], + [3, 5, 5, 4, 4, 4, 4, 3, 3, 2], + [2, 5, 3, 7, 5, 5, 4, 4, 5, 4], + [4, 4, 5, 4, 5, 6, 5, 6, 5, 4], +]; +pub const NLSF_SEL_WB: [[u8; 16]; 32] = [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [2, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 0, 3], + [2, 5, 5, 3, 7, 4, 4, 5, 2, 5, 4, 5, 5, 4, 3, 3], + [0, 2, 1, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1], + [0, 6, 5, 4, 6, 4, 7, 5, 4, 4, 4, 5, 5, 4, 4, 3], + [0, 3, 5, 5, 4, 3, 3, 5, 3, 3, 3, 3, 3, 3, 2, 4], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 2, 6, 3, 7, 2, 5, 3, 4, 5, 5, 4, 3, 3, 2, 3], + [0, 6, 2, 6, 6, 4, 5, 4, 6, 5, 4, 4, 5, 3, 3, 3], + [2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [2, 2, 3, 4, 5, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1, 3], + [2, 2, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 3], + [3, 4, 4, 4, 6, 4, 4, 5, 3, 5, 4, 4, 5, 4, 3, 4], + [0, 6, 4, 5, 4, 7, 5, 2, 6, 5, 7, 4, 4, 3, 5, 3], + [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0], + [1, 6, 5, 7, 5, 4, 5, 3, 4, 5, 4, 4, 4, 3, 3, 4], + [1, 3, 3, 4, 4, 3, 3, 5, 2, 3, 3, 5, 5, 5, 3, 4], + [2, 3, 3, 2, 2, 2, 3, 2, 1, 2, 1, 2, 1, 1, 1, 4], + [0, 2, 3, 5, 3, 3, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0], + [3, 4, 3, 5, 3, 3, 2, 2, 1, 1, 1, 1, 1, 2, 2, 4], + [2, 6, 3, 7, 7, 4, 5, 4, 5, 3, 5, 3, 3, 2, 3, 3], + [2, 3, 5, 6, 6, 3, 5, 3, 4, 4, 3, 3, 3, 3, 2, 4], + [1, 3, 3, 4, 4, 4, 4, 3, 5, 5, 5, 3, 1, 1, 1, 1], + [2, 5, 3, 6, 6, 4, 7, 4, 4, 5, 3, 4, 4, 3, 3, 3], + [0, 6, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 6, 6, 3, 5, 2, 5, 5, 3, 4, 4, 7, 7, 4, 4, 4], + [3, 3, 7, 3, 5, 4, 3, 3, 3, 2, 2, 3, 3, 3, 2, 3], + [0, 0, 1, 0, 0, 0, 2, 1, 2, 1, 1, 2, 2, 2, 1, 1], + [0, 3, 2, 5, 3, 3, 2, 3, 2, 1, 0, 0, 1, 0, 0, 1], + [3, 5, 5, 4, 7, 5, 3, 3, 2, 3, 2, 2, 1, 0, 1, 0], + [2, 3, 5, 3, 4, 3, 3, 3, 2, 1, 2, 6, 4, 0, 0, 0], +]; +pub const NLSF_EXT: [u8; 7] = icdf(&[156, 60, 24, 9, 4, 2, 1]); +pub const NLSF_PRED_NBMB: [[i32; 9]; 2] = [[179, 138, 140, 148, 151, 149, 153, 151, 163], [116, 67, 82, 59, 92, 72, 100, 89, 92]]; +pub const NLSF_PRED_WB: [[i32; 15]; 2] = [ + [175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182], + [68, 62, 66, 60, 72, 117, 85, 90, 118, 136, 151, 142, 160, 142, 155], +]; +pub const NLSF_PSEL_NBMB: [[u8; 9]; 32] = [ + [0, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 0, 1, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 0, 1, 0, 1, 1], + [0, 0, 1, 1, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0], + [1, 0, 1, 1, 0, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0, 1, 0], + [0, 0, 1, 1, 0, 1, 0, 1, 0], + [0, 0, 1, 1, 1, 0, 1, 1, 1], + [0, 1, 1, 0, 0, 1, 1, 1, 0], + [0, 0, 0, 1, 1, 1, 0, 1, 0], + [0, 1, 1, 0, 0, 1, 0, 1, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 1], + [0, 0, 1, 1, 0, 0, 0, 1, 1], + [0, 0, 0, 1, 0, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 1, 1, 0, 1, 0], + [1, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0, 1, 0, 1], + [1, 0, 1, 1, 0, 1, 1, 1, 1], +]; +pub const NLSF_PSEL_WB: [[u8; 15]; 32] = [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], + [0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1], + [0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], + [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], + [0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0], +]; +pub const NLSF_CB_NBMB: [[i32; 10]; 32] = [ + [12, 35, 60, 83, 108, 132, 157, 180, 206, 228], + [15, 32, 55, 77, 101, 125, 151, 175, 201, 225], + [19, 42, 66, 89, 114, 137, 162, 184, 209, 230], + [12, 25, 50, 72, 97, 120, 147, 172, 200, 223], + [26, 44, 69, 90, 114, 135, 159, 180, 205, 225], + [13, 22, 53, 80, 106, 130, 156, 180, 205, 228], + [15, 25, 44, 64, 90, 115, 142, 168, 196, 222], + [19, 24, 62, 82, 100, 120, 145, 168, 190, 214], + [22, 31, 50, 79, 103, 120, 151, 170, 203, 227], + [21, 29, 45, 65, 106, 124, 150, 171, 196, 224], + [30, 49, 75, 97, 121, 142, 165, 186, 209, 229], + [19, 25, 52, 70, 93, 116, 143, 166, 192, 219], + [26, 34, 62, 75, 97, 118, 145, 167, 194, 217], + [25, 33, 56, 70, 91, 113, 143, 165, 196, 223], + [21, 34, 51, 72, 97, 117, 145, 171, 196, 222], + [20, 29, 50, 67, 90, 117, 144, 168, 197, 221], + [22, 31, 48, 66, 95, 117, 146, 168, 196, 222], + [24, 33, 51, 77, 116, 134, 158, 180, 200, 224], + [21, 28, 70, 87, 106, 124, 149, 170, 194, 217], + [26, 33, 53, 64, 83, 117, 152, 173, 204, 225], + [27, 34, 65, 95, 108, 129, 155, 174, 210, 225], + [20, 26, 72, 99, 113, 131, 154, 176, 200, 219], + [34, 43, 61, 78, 93, 114, 155, 177, 205, 229], + [23, 29, 54, 97, 124, 138, 163, 179, 209, 229], + [30, 38, 56, 89, 118, 129, 158, 178, 200, 231], + [21, 29, 49, 63, 85, 111, 142, 163, 193, 222], + [27, 48, 77, 103, 133, 158, 179, 196, 215, 232], + [29, 47, 74, 99, 124, 151, 176, 198, 220, 237], + [33, 42, 61, 76, 93, 121, 155, 174, 207, 225], + [29, 53, 87, 112, 136, 154, 170, 188, 208, 227], + [24, 30, 52, 84, 131, 150, 166, 186, 203, 229], + [37, 48, 64, 84, 104, 118, 156, 177, 201, 230], +]; +pub const NLSF_CB_WB: [[i32; 16]; 32] = [ + [7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239], + [13, 25, 41, 55, 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236], + [15, 21, 34, 51, 61, 78, 92, 106, 126, 136, 152, 167, 185, 205, 225, 240], + [10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, 189, 205, 221, 237], + [17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240], + [10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236], + [8, 21, 37, 51, 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218], + [12, 15, 34, 55, 63, 78, 87, 108, 118, 131, 148, 167, 185, 203, 219, 236], + [16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, 186, 204, 220, 237], + [11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241], + [6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225], + [11, 19, 30, 44, 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234], + [12, 19, 29, 46, 57, 71, 88, 100, 120, 132, 148, 165, 182, 199, 216, 233], + [17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, 185, 204, 222, 237], + [14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240], + [9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237], + [16, 19, 36, 48, 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236], + [12, 17, 29, 54, 71, 81, 94, 104, 126, 136, 149, 164, 182, 201, 221, 237], + [15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, 194, 208, 223, 238], + [8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239], + [17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235], + [14, 19, 36, 45, 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238], + [12, 18, 31, 45, 60, 76, 91, 107, 123, 138, 154, 171, 187, 204, 221, 236], + [13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, 185, 203, 220, 237], + [17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240], + [8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239], + [13, 16, 41, 66, 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241], + [17, 25, 37, 52, 63, 75, 92, 102, 119, 132, 144, 160, 175, 191, 212, 231], + [19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, 200, 213, 227, 242], + [18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239], + [16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240], + [15, 21, 35, 50, 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237], +]; +pub const NLSF_MIN_SPACING_NBMB: [i32; 11] = [250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461]; +pub const NLSF_MIN_SPACING_WB: [i32; 17] = [100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347]; +pub const NLSF_INTERP: [u8; 5] = icdf(&[13, 22, 29, 11, 181]); +pub const LSF_ORDER_NBMB: [usize; 10] = [0, 9, 6, 3, 4, 5, 8, 1, 2, 7]; +pub const LSF_ORDER_WB: [usize; 16] = [0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1]; +pub const COS_Q12: [i32; 129] = [ + 4096, 4095, 4091, 4085, 4076, 4065, 4052, 4036, 4017, 3997, 3973, 3948, 3920, 3889, 3857, 3822, 3784, 3745, 3703, 3659, 3613, 3564, 3513, 3461, + 3406, 3349, 3290, 3229, 3166, 3102, 3035, 2967, 2896, 2824, 2751, 2676, 2599, 2520, 2440, 2359, 2276, 2191, 2106, 2019, 1931, 1842, 1751, 1660, + 1568, 1474, 1380, 1285, 1189, 1093, 995, 897, 799, 700, 601, 501, 401, 301, 201, 101, 0, -101, -201, -301, -401, -501, -601, -700, -799, -897, + -995, -1093, -1189, -1285, -1380, -1474, -1568, -1660, -1751, -1842, -1931, -2019, -2106, -2191, -2276, -2359, -2440, -2520, -2599, -2676, -2751, + -2824, -2896, -2967, -3035, -3102, -3166, -3229, -3290, -3349, -3406, -3461, -3513, -3564, -3613, -3659, -3703, -3745, -3784, -3822, -3857, + -3889, -3920, -3948, -3973, -3997, -4017, -4036, -4052, -4065, -4076, -4085, -4091, -4095, -4096, +]; +pub const PITCH_HIGH: [u8; 32] = icdf(&[3, 3, 6, 11, 21, 30, 32, 19, 11, 10, 12, 13, 13, 12, 11, 9, 8, 7, 6, 4, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]); +pub const PITCH_LOW: [&[u8]; 3] = + [&icdf::<4>(&[64, 64, 64, 64]), &icdf::<6>(&[43, 42, 43, 43, 42, 43]), &icdf::<8>(&[32, 32, 32, 32, 32, 32, 32, 32])]; +pub const PITCH_DELTA: [u8; 21] = icdf(&[46, 2, 2, 3, 4, 6, 10, 15, 26, 38, 30, 22, 15, 10, 7, 6, 4, 4, 2, 2, 2]); +pub const PITCH_CONTOUR: [&[u8]; 4] = [ + &icdf::<3>(&[143, 50, 63]), + &icdf::<11>(&[68, 12, 21, 17, 19, 22, 30, 24, 17, 16, 10]), + &icdf::<12>(&[91, 46, 39, 19, 14, 12, 8, 7, 6, 5, 5, 4]), + &icdf::<34>(&[33, 22, 18, 16, 15, 14, 14, 13, 13, 10, 9, 9, 8, 6, 6, 6, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1]), +]; +pub const CB_NB_10: [[i32; 2]; 3] = [[0, 0], [1, 0], [0, 1]]; +pub const CB_NB_20: [[i32; 4]; 11] = [ + [0, 0, 0, 0], + [2, 1, 0, -1], + [-1, 0, 1, 2], + [-1, 0, 0, 1], + [-1, 0, 0, 0], + [0, 0, 0, 1], + [0, 0, 1, 1], + [1, 1, 0, 0], + [1, 0, 0, 0], + [0, 0, 0, -1], + [1, 0, 0, -1], +]; +pub const CB_WB_10: [[i32; 2]; 12] = [[0, 0], [0, 1], [1, 0], [-1, 1], [1, -1], [-1, 2], [2, -1], [-2, 2], [2, -2], [-2, 3], [3, -2], [-3, 3]]; +pub const CB_WB_20: [[i32; 4]; 34] = [ + [0, 0, 0, 0], + [0, 0, 1, 1], + [1, 1, 0, 0], + [-1, 0, 0, 0], + [0, 0, 0, 1], + [1, 0, 0, 0], + [-1, 0, 0, 1], + [0, 0, 0, -1], + [-1, 0, 1, 2], + [1, 0, 0, -1], + [-2, -1, 1, 2], + [2, 1, 0, -1], + [-2, 0, 0, 2], + [-2, 0, 1, 3], + [2, 1, -1, -2], + [-3, -1, 1, 3], + [2, 0, 0, -2], + [3, 1, 0, -2], + [-3, -1, 2, 4], + [-4, -1, 1, 4], + [3, 1, -1, -3], + [-4, -1, 2, 5], + [4, 2, -1, -3], + [4, 1, -1, -4], + [-5, -1, 2, 6], + [5, 2, -1, -4], + [-6, -2, 2, 6], + [-5, -2, 2, 5], + [6, 2, -1, -5], + [-7, -2, 3, 8], + [6, 2, -2, -6], + [5, 2, -2, -5], + [8, 3, -2, -7], + [-9, -3, 3, 9], +]; +pub const LTP_PERIODICITY: [u8; 3] = icdf(&[77, 80, 99]); +pub const LTP_FILTER: [&[u8]; 3] = [ + &icdf::<8>(&[185, 15, 13, 13, 9, 9, 6, 6]), + &icdf::<16>(&[57, 34, 21, 20, 15, 13, 12, 13, 10, 10, 9, 10, 9, 8, 7, 8]), + &icdf::<32>(&[15, 16, 14, 12, 12, 12, 11, 11, 11, 10, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 6, 6, 5, 4, 5, 4, 4, 4, 3, 4, 3, 2]), +]; +pub const LTP_TAPS_0: [[i32; 5]; 8] = [ + [4, 6, 24, 7, 5], + [0, 0, 2, 0, 0], + [12, 28, 41, 13, -4], + [-9, 15, 42, 25, 14], + [1, -2, 62, 41, -9], + [-10, 37, 65, -4, 3], + [-6, 4, 66, 7, -8], + [16, 14, 38, -3, 33], +]; +pub const LTP_TAPS_1: [[i32; 5]; 16] = [ + [13, 22, 39, 23, 12], + [-1, 36, 64, 27, -6], + [-7, 10, 55, 43, 17], + [1, 1, 8, 1, 1], + [6, -11, 74, 53, -9], + [-12, 55, 76, -12, 8], + [-3, 3, 93, 27, -4], + [26, 39, 59, 3, -8], + [2, 0, 77, 11, 9], + [-8, 22, 44, -6, 7], + [40, 9, 26, 3, 9], + [-7, 20, 101, -7, 4], + [3, -8, 42, 26, 0], + [-15, 33, 68, 2, 23], + [-2, 55, 46, -2, 15], + [3, -1, 21, 16, 41], +]; +pub const LTP_TAPS_2: [[i32; 5]; 32] = [ + [-6, 27, 61, 39, 5], + [-11, 42, 88, 4, 1], + [-2, 60, 65, 6, -4], + [-1, -5, 73, 56, 1], + [-9, 19, 94, 29, -9], + [0, 12, 99, 6, 4], + [8, -19, 102, 46, -13], + [3, 2, 13, 3, 2], + [9, -21, 84, 72, -18], + [-11, 46, 104, -22, 8], + [18, 38, 48, 23, 0], + [-16, 70, 83, -21, 11], + [5, -11, 117, 22, -8], + [-6, 23, 117, -12, 3], + [3, -8, 95, 28, 4], + [-10, 15, 77, 60, -15], + [-1, 4, 124, 2, -4], + [3, 38, 84, 24, -25], + [2, 13, 42, 13, 31], + [21, -4, 56, 46, -1], + [-1, 35, 79, -13, 19], + [-7, 65, 88, -9, -14], + [20, 4, 81, 49, -29], + [20, 0, 75, 3, -17], + [5, -9, 44, 92, -8], + [1, -3, 22, 69, 31], + [-6, 95, 41, -12, 5], + [39, 67, 16, -4, 1], + [0, -6, 120, 55, -36], + [-13, 44, 122, 4, -24], + [81, 5, 11, 3, 7], + [2, 0, 9, 10, 88], +]; +pub const LTP_SCALE: [u8; 3] = icdf(&[128, 64, 64]); +pub const UNIFORM4: [u8; 4] = icdf(&[64, 64, 64, 64]); +pub const RATE_LEVEL: [&[u8]; 2] = [&icdf::<9>(&[15, 51, 12, 46, 45, 13, 33, 27, 14]), &icdf::<9>(&[33, 30, 36, 17, 34, 49, 18, 21, 18])]; +pub const PULSE_COUNT: [&[u8]; 11] = [ + &icdf::<18>(&[131, 74, 25, 8, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + &icdf::<18>(&[58, 93, 60, 23, 7, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + &icdf::<18>(&[43, 51, 46, 33, 24, 16, 11, 8, 6, 3, 3, 3, 2, 1, 1, 2, 1, 2]), + &icdf::<18>(&[17, 52, 71, 57, 31, 12, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + &icdf::<18>(&[6, 21, 41, 53, 49, 35, 21, 11, 6, 3, 2, 2, 1, 1, 1, 1, 1, 1]), + &icdf::<18>(&[7, 14, 22, 28, 29, 28, 25, 20, 17, 13, 11, 9, 7, 5, 4, 4, 3, 10]), + &icdf::<18>(&[2, 5, 14, 29, 42, 46, 41, 31, 19, 11, 6, 3, 2, 1, 1, 1, 1, 1]), + &icdf::<18>(&[1, 2, 4, 10, 19, 29, 35, 37, 34, 28, 20, 14, 8, 5, 4, 2, 2, 2]), + &icdf::<18>(&[1, 2, 2, 5, 9, 14, 20, 24, 27, 28, 26, 23, 20, 15, 11, 8, 6, 15]), + &icdf::<18>(&[1, 1, 1, 6, 27, 58, 56, 39, 25, 14, 10, 6, 3, 3, 2, 1, 1, 2]), + &icdf::<18>(&[2, 1, 6, 27, 58, 56, 39, 25, 14, 10, 6, 3, 3, 2, 1, 1, 2, 0]), +]; +pub const SHELL_16: [&[u8]; 16] = [ + &icdf::<2>(&[126, 130]), + &icdf::<3>(&[56, 142, 58]), + &icdf::<4>(&[25, 101, 104, 26]), + &icdf::<5>(&[12, 60, 108, 64, 12]), + &icdf::<6>(&[7, 35, 84, 87, 37, 6]), + &icdf::<7>(&[4, 20, 59, 86, 63, 21, 3]), + &icdf::<8>(&[3, 12, 38, 72, 75, 42, 12, 2]), + &icdf::<9>(&[2, 8, 25, 54, 73, 59, 27, 7, 1]), + &icdf::<10>(&[2, 5, 17, 39, 63, 65, 42, 18, 4, 1]), + &icdf::<11>(&[1, 4, 12, 28, 49, 63, 54, 30, 11, 3, 1]), + &icdf::<12>(&[1, 4, 8, 20, 37, 55, 57, 41, 22, 8, 2, 1]), + &icdf::<13>(&[1, 3, 7, 15, 28, 44, 53, 48, 33, 16, 6, 1, 1]), + &icdf::<14>(&[1, 2, 6, 12, 21, 35, 47, 48, 40, 25, 12, 5, 1, 1]), + &icdf::<15>(&[1, 1, 4, 10, 17, 27, 37, 47, 43, 33, 21, 9, 4, 1, 1]), + &icdf::<16>(&[1, 1, 1, 8, 14, 22, 33, 40, 43, 38, 28, 16, 8, 1, 1, 1]), + &icdf::<17>(&[1, 1, 1, 1, 13, 18, 27, 36, 41, 41, 34, 24, 14, 1, 1, 1, 1]), +]; +pub const SHELL_8: [&[u8]; 16] = [ + &icdf::<2>(&[127, 129]), + &icdf::<3>(&[53, 149, 54]), + &icdf::<4>(&[22, 105, 106, 23]), + &icdf::<5>(&[11, 61, 111, 63, 10]), + &icdf::<6>(&[6, 35, 86, 88, 36, 5]), + &icdf::<7>(&[4, 20, 59, 87, 62, 21, 3]), + &icdf::<8>(&[3, 13, 40, 71, 73, 41, 13, 2]), + &icdf::<9>(&[3, 9, 27, 53, 70, 56, 28, 9, 1]), + &icdf::<10>(&[3, 8, 19, 37, 57, 61, 44, 20, 6, 1]), + &icdf::<11>(&[3, 7, 15, 28, 44, 54, 49, 33, 17, 5, 1]), + &icdf::<12>(&[1, 7, 13, 22, 34, 46, 48, 38, 28, 14, 4, 1]), + &icdf::<13>(&[1, 1, 11, 22, 27, 35, 42, 47, 33, 25, 10, 1, 1]), + &icdf::<14>(&[1, 1, 6, 14, 26, 37, 43, 43, 37, 26, 14, 6, 1, 1]), + &icdf::<15>(&[1, 1, 4, 10, 20, 31, 40, 42, 40, 31, 20, 10, 4, 1, 1]), + &icdf::<16>(&[1, 1, 3, 8, 16, 26, 35, 38, 38, 35, 26, 16, 8, 3, 1, 1]), + &icdf::<17>(&[1, 1, 2, 6, 12, 21, 30, 36, 38, 36, 30, 21, 12, 6, 2, 1, 1]), +]; +pub const SHELL_4: [&[u8]; 16] = [ + &icdf::<2>(&[127, 129]), + &icdf::<3>(&[49, 157, 50]), + &icdf::<4>(&[20, 107, 109, 20]), + &icdf::<5>(&[11, 60, 113, 62, 10]), + &icdf::<6>(&[7, 36, 84, 87, 36, 6]), + &icdf::<7>(&[6, 24, 57, 82, 60, 23, 4]), + &icdf::<8>(&[5, 18, 39, 64, 68, 42, 16, 4]), + &icdf::<9>(&[6, 14, 29, 47, 61, 52, 30, 14, 3]), + &icdf::<10>(&[1, 15, 23, 35, 51, 50, 40, 30, 10, 1]), + &icdf::<11>(&[1, 1, 21, 32, 42, 52, 46, 41, 18, 1, 1]), + &icdf::<12>(&[1, 6, 16, 27, 36, 42, 42, 36, 27, 16, 6, 1]), + &icdf::<13>(&[1, 5, 12, 21, 31, 38, 40, 38, 31, 21, 12, 5, 1]), + &icdf::<14>(&[1, 3, 9, 17, 26, 34, 38, 38, 34, 26, 17, 9, 3, 1]), + &icdf::<15>(&[1, 3, 7, 14, 22, 29, 34, 36, 34, 29, 22, 14, 7, 3, 1]), + &icdf::<16>(&[1, 2, 5, 11, 18, 25, 31, 35, 35, 31, 25, 18, 11, 5, 2, 1]), + &icdf::<17>(&[1, 1, 4, 9, 15, 21, 28, 32, 34, 32, 28, 21, 15, 9, 4, 1, 1]), +]; +pub const SHELL_2: [&[u8]; 16] = [ + &icdf::<2>(&[128, 128]), + &icdf::<3>(&[42, 172, 42]), + &icdf::<4>(&[21, 107, 107, 21]), + &icdf::<5>(&[12, 60, 112, 61, 11]), + &icdf::<6>(&[8, 34, 86, 86, 35, 7]), + &icdf::<7>(&[8, 23, 55, 90, 55, 20, 5]), + &icdf::<8>(&[5, 15, 38, 72, 72, 36, 15, 3]), + &icdf::<9>(&[6, 12, 27, 52, 77, 47, 20, 10, 5]), + &icdf::<10>(&[6, 19, 28, 35, 40, 40, 35, 28, 19, 6]), + &icdf::<11>(&[4, 14, 22, 31, 37, 40, 37, 31, 22, 14, 4]), + &icdf::<12>(&[3, 10, 18, 26, 33, 38, 38, 33, 26, 18, 10, 3]), + &icdf::<13>(&[2, 8, 13, 21, 29, 36, 38, 36, 29, 21, 13, 8, 2]), + &icdf::<14>(&[1, 5, 10, 17, 25, 32, 38, 38, 32, 25, 17, 10, 5, 1]), + &icdf::<15>(&[1, 4, 7, 13, 21, 29, 35, 36, 35, 29, 21, 13, 7, 4, 1]), + &icdf::<16>(&[1, 2, 5, 10, 17, 25, 32, 36, 36, 32, 25, 17, 10, 5, 2, 1]), + &icdf::<17>(&[1, 2, 4, 7, 13, 21, 28, 34, 36, 34, 28, 21, 13, 7, 4, 2, 1]), +]; +pub const EXC_LSB: [u8; 2] = icdf(&[136, 120]); +pub const EXC_SIGN: [&[u8]; 42] = [ + &icdf::<2>(&[2, 254]), + &icdf::<2>(&[207, 49]), + &icdf::<2>(&[189, 67]), + &icdf::<2>(&[179, 77]), + &icdf::<2>(&[174, 82]), + &icdf::<2>(&[163, 93]), + &icdf::<2>(&[157, 99]), + &icdf::<2>(&[58, 198]), + &icdf::<2>(&[245, 11]), + &icdf::<2>(&[238, 18]), + &icdf::<2>(&[232, 24]), + &icdf::<2>(&[225, 31]), + &icdf::<2>(&[220, 36]), + &icdf::<2>(&[211, 45]), + &icdf::<2>(&[1, 255]), + &icdf::<2>(&[210, 46]), + &icdf::<2>(&[190, 66]), + &icdf::<2>(&[178, 78]), + &icdf::<2>(&[169, 87]), + &icdf::<2>(&[162, 94]), + &icdf::<2>(&[152, 104]), + &icdf::<2>(&[48, 208]), + &icdf::<2>(&[242, 14]), + &icdf::<2>(&[235, 21]), + &icdf::<2>(&[224, 32]), + &icdf::<2>(&[214, 42]), + &icdf::<2>(&[205, 51]), + &icdf::<2>(&[190, 66]), + &icdf::<2>(&[1, 255]), + &icdf::<2>(&[162, 94]), + &icdf::<2>(&[152, 104]), + &icdf::<2>(&[147, 109]), + &icdf::<2>(&[144, 112]), + &icdf::<2>(&[141, 115]), + &icdf::<2>(&[138, 118]), + &icdf::<2>(&[8, 248]), + &icdf::<2>(&[203, 53]), + &icdf::<2>(&[187, 69]), + &icdf::<2>(&[176, 80]), + &icdf::<2>(&[168, 88]), + &icdf::<2>(&[161, 95]), + &icdf::<2>(&[154, 102]), +]; +pub const LBRR_FLAGS: [&[u8]; 2] = [&icdf::<3>(&[53, 53, 150]), &icdf::<7>(&[41, 20, 29, 41, 15, 28, 82])]; diff --git a/crates/audio/src/opus/encoder/tables.rs b/crates/audio/src/opus/encoder/tables.rs new file mode 100644 index 000000000..1985202cc --- /dev/null +++ b/crates/audio/src/opus/encoder/tables.rs @@ -0,0 +1,123 @@ +//! Constant tables of the 48 kHz CELT mode (RFC 6716 §4.3, Tables 55–58 and §4.3.2). +//! +//! Transcribed from RFC 6716; copied from FilmCraft's spec-derived `filmcraft-opus` decoder +//! (first-party, MIT OR Apache-2.0) so both sides share the exact same values. + +/// Number of energy bands. +pub const NB_EBANDS: usize = 21; +/// Band edges in units of 2.5 ms MDCT bins (Table 55). +pub const EBANDS: [i32; NB_EBANDS + 1] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100]; +/// Overlap of the low-overlap window (samples at 48 kHz). +pub const OVERLAP: usize = 120; +/// Largest LM (20 ms frames). +pub const MAX_LM: usize = 3; +/// Pre-emphasis coefficient. +pub const PREEMPH: f32 = 0.850_006_1; + +/// Static allocation table (Table 57), indexed `[quality][band]`, in 1/32 bit per MDCT bin. +pub const ALLOC: [[u8; NB_EBANDS]; 11] = transpose([ + [0, 90, 110, 118, 126, 134, 144, 152, 162, 172, 200], + [0, 80, 100, 110, 119, 127, 137, 145, 155, 165, 200], + [0, 75, 90, 103, 112, 120, 130, 138, 148, 158, 200], + [0, 69, 84, 93, 104, 114, 124, 132, 142, 152, 200], + [0, 63, 78, 86, 95, 103, 113, 123, 133, 143, 200], + [0, 56, 71, 80, 89, 97, 107, 117, 127, 137, 200], + [0, 49, 65, 75, 83, 91, 101, 111, 121, 131, 200], + [0, 40, 58, 70, 78, 85, 95, 105, 115, 125, 200], + [0, 34, 51, 65, 72, 78, 88, 98, 108, 118, 198], + [0, 29, 45, 59, 66, 72, 82, 92, 102, 112, 193], + [0, 20, 39, 53, 60, 66, 76, 86, 96, 106, 188], + [0, 18, 32, 47, 54, 60, 70, 80, 90, 100, 183], + [0, 10, 26, 40, 47, 54, 64, 74, 84, 94, 178], + [0, 0, 20, 31, 39, 47, 57, 67, 77, 87, 173], + [0, 0, 12, 23, 32, 41, 51, 61, 71, 81, 168], + [0, 0, 0, 15, 25, 35, 45, 55, 65, 75, 163], + [0, 0, 0, 4, 17, 29, 39, 49, 59, 69, 158], + [0, 0, 0, 0, 12, 23, 33, 43, 53, 63, 153], + [0, 0, 0, 0, 1, 16, 26, 36, 46, 56, 148], + [0, 0, 0, 0, 0, 10, 15, 20, 30, 45, 129], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 20, 104], +]); + +const fn transpose(t: [[u8; 11]; NB_EBANDS]) -> [[u8; NB_EBANDS]; 11] { + let mut out = [[0u8; NB_EBANDS]; 11]; + let mut b = 0; + while b < NB_EBANDS { + let mut q = 0; + while q < 11 { + out[q][b] = t[b][q]; + q += 1; + } + b += 1; + } + out +} + +/// Mean band energy (log2 domain) removed before coarse quantisation. +pub const E_MEANS: [f32; 25] = [ + 6.4375, 6.25, 5.75, 5.3125, 5.0625, 4.8125, 4.5, 4.375, 4.875, 4.6875, 4.5625, 4.4375, 4.875, 4.625, 4.3125, 4.5, 4.375, 4.625, 4.75, 4.4375, + 3.75, 3.75, 3.75, 3.75, 3.75, +]; + +/// Inter-frame prediction coefficient (alpha) per LM, Q15. +pub const PRED_COEF: [f32; 4] = [29440.0 / 32768.0, 26112.0 / 32768.0, 21248.0 / 32768.0, 16384.0 / 32768.0]; +/// Inter-band prediction coefficient (beta) per LM for inter frames, Q15. +pub const BETA_COEF: [f32; 4] = [30147.0 / 32768.0, 22282.0 / 32768.0, 12124.0 / 32768.0, 6554.0 / 32768.0]; +/// Beta for intra frames. +pub const BETA_INTRA: f32 = 4915.0 / 32768.0; + +/// Laplace model parameters for coarse energy: `[LM][intra][2*band + {0: prob, 1: decay}]`. +pub const E_PROB_MODEL: [[[u8; 42]; 2]; 4] = [ + [ + [ + 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, 116, 41, 115, 40, 114, 40, 132, + 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11, + ], + [ + 24, 179, 48, 138, 54, 135, 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, 100, 59, + 108, 50, 120, 40, 122, 37, 97, 43, 78, 50, + ], + ], + [ + [ + 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, 93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, + 165, 10, 178, 7, 189, 6, 190, 8, 177, 9, + ], + [ + 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, + 123, 44, 138, 35, 133, 31, 97, 38, 77, 45, + ], + ], + [ + [ + 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, 155, 14, 159, 16, 158, 18, 170, + 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10, + ], + [ + 21, 178, 59, 110, 71, 86, 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56, 129, 51, + 132, 40, 150, 33, 140, 29, 98, 35, 77, 42, + ], + ], + [ + [ + 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, 120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, + 166, 21, 173, 16, 184, 13, 184, 10, 150, 13, 139, 15, + ], + [ + 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, + 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40, + ], + ], +]; + +/// Inverse CDF for coarse energy when only a few bits remain. +pub const SMALL_ENERGY_ICDF: [u8; 3] = [2, 1, 0]; +/// Conservative log2 in 1/8 bits of the number of coded bands (intensity reservation). +pub const LOG2_FRAC_TABLE: [i32; 24] = [0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37]; +/// TF resolution changes: `[LM][4*transient + 2*tf_select + tf_flag]`. +pub const TF_SELECT_TABLE: [[i8; 8]; 4] = + [[0, -1, 0, -1, 0, -1, 0, -1], [0, -1, 0, -2, 1, 0, 1, -1], [0, -2, 0, -3, 2, 0, 1, -1], [0, -2, 0, -3, 3, 0, 1, -1]]; +/// Spreading decision `{7, 2, 21, 2}/32`. +pub const SPREAD_ICDF: [u8; 4] = [25, 23, 2, 0]; +/// Allocation trim (Table 58). +pub const TRIM_ICDF: [u8; 11] = [126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0]; diff --git a/crates/audio/src/opus/mod.rs b/crates/audio/src/opus/mod.rs index cf2accd33..b67e1ef3d 100644 --- a/crates/audio/src/opus/mod.rs +++ b/crates/audio/src/opus/mod.rs @@ -1,20 +1,31 @@ //! Clean-room pure-Rust Opus (RFC 6716, updated by RFC 8251; RFC 7845 `OpusHead`). //! -//! Decoding (feature `opus-decode`): [`Decoder`] (multistream, surround), [`StreamDecoder`] (one -//! elementary stream), [`OpusHead`] and the packet parser [`packet`]. From FilmCraft's -//! `filmcraft-opus` (storytold/filmcraft@8fda2f2). +//! - Decoding (feature `opus-decode`): [`Decoder`] (multistream, surround), [`StreamDecoder`] (one +//! elementary stream), [`OpusHead`] and the packet parser [`packet`]. From FilmCraft's +//! `filmcraft-opus` (storytold/filmcraft@8fda2f2). +//! - Encoding (feature `opus-encode`): [`Encoder`] (in [`encoder`]) (SILK, hybrid and CELT modes, 48 kHz, +//! 20 ms, mono or stereo). From EffectCraft's `effectcraft-opusenc` (storytold/effectcraft@c618429). //! -//! Public items keep their names, so FilmCraft can re-export this module. +//! Public items keep their names, so FilmCraft and EffectCraft can re-export this module. The two +//! halves come from separate crates and do not share code yet (each has its own range coder, MDCT +//! and band tables). [`Bandwidth`] is one type for both (`encoder::Bandwidth` is the same type); +//! the two `Mode` enums keep their apps' variant names and convert into each other. -// Index loops and long argument lists follow the specification's pseudo-code (FilmCraft allows -// these lints workspace-wide). +// Index loops and long argument lists follow the specification's pseudo-code (FilmCraft and +// EffectCraft allow these lints workspace-wide). #![allow(clippy::needless_range_loop, clippy::too_many_arguments)] +#[cfg(feature = "opus-decode")] mod decode; +#[cfg(feature = "opus-encode")] +pub mod encoder; +#[cfg(feature = "opus-decode")] pub use decode::{Decoder, Error, Mode, OpusHead, Packet, Result, SAMPLE_RATES, StreamDecoder, Toc, packet}; +#[cfg(feature = "opus-encode")] +pub use encoder::Encoder; -/// Coded audio bandwidth (RFC 6716 §2, Table 1). +/// Coded audio bandwidth (RFC 6716 §2, Table 1), for the decoder and the encoder alike. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Bandwidth { /// 4 kHz (8 kHz sampling). @@ -29,9 +40,32 @@ pub enum Bandwidth { Fullband, } +#[cfg(all(feature = "opus-decode", feature = "opus-encode"))] +impl From for encoder::Mode { + fn from(m: Mode) -> Self { + match m { + Mode::SilkOnly => encoder::Mode::Silk, + Mode::Hybrid => encoder::Mode::Hybrid, + Mode::CeltOnly => encoder::Mode::Celt, + } + } +} + +#[cfg(all(feature = "opus-decode", feature = "opus-encode"))] +impl From for Mode { + fn from(m: encoder::Mode) -> Self { + match m { + encoder::Mode::Silk => Mode::SilkOnly, + encoder::Mode::Hybrid => Mode::Hybrid, + encoder::Mode::Celt => Mode::CeltOnly, + } + } +} + /// Channel order for Vorbis-ordered surround (mapping family 1, RFC 7845 §5.1.1.2): output channel /// → decoded channel, giving the WAV/SMPTE order (L R C LFE back… side…) the rest of craft-audio /// uses. From FilmCraft's `filmcraft-codecs`. +#[cfg(feature = "opus-decode")] pub fn wav_order(channels: usize) -> Option<&'static [usize]> { Some(match channels { 3 => &[0, 2, 1], diff --git a/crates/audio/src/read/wav.rs b/crates/audio/src/read/wav.rs index bd9c2301a..c1552d7e2 100644 --- a/crates/audio/src/read/wav.rs +++ b/crates/audio/src/read/wav.rs @@ -115,6 +115,50 @@ fn parse_bext(c: &[u8]) -> Option { }) } +/// Cap optional metadata independently of audio length, including on range-backed sources. +const IXML_MAX: usize = 1 << 20; + +/// iXML's BEXT mirror is a fallback only: a real `bext` always wins, including timestamp zero. +/// Read the two unsigned 32-bit words, not arbitrary text that merely contains their tag names. +fn ixml_time_reference(bytes: &[u8]) -> Option { + let options = craft_xml::Options { + doctype: craft_xml::Doctype::Reject, + ..craft_xml::Options::default().strict().with_limits(craft_xml::Limits { + max_input: IXML_MAX, + max_depth: 32, + max_nodes: 8192, + max_attrs: 64, + max_attrs_total: 8192, + ..craft_xml::Limits::default() + }) + }; + let root = options.parse(bytes).ok()?; + if root.name != "BWFXML" { + return None; + } + let mut bexts = root.children("BEXT"); + let bext = bexts.next()?; + if bexts.next().is_some() { + return None; + } + let word = |name: &str| -> Option> { + let mut fields = bext.children(name); + let Some(field) = fields.next() else { return Some(None) }; + if fields.next().is_some() || field.children.iter().any(|n| matches!(n, craft_xml::Node::El(_))) { + return None; + } + let text = field.text(); + let text = text.trim(); + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + Some(Some(text.parse().ok()?)) + }; + let low = word("BWF_TIME_REFERENCE_LOW")??; + let high = word("BWF_TIME_REFERENCE_HIGH")?.unwrap_or(0); + Some((u64::from(high) << 32) | u64::from(low)) +} + /// Refuse the WAVE file at `at`, which symphonia reads (A-law, ADPCM, ...), if an INFO entry /// claims more bytes than the file holds: symphonia allocates each entry's length. Chunks are /// walked where symphonia reads them: after the bytes a chunk's parser used, not its length. @@ -239,7 +283,7 @@ fn pcm_layout(fmt: &Fmt) -> Result> { } /// Parse a WAV file's chunks: its format, `bext` metadata and where its samples are. Only chunk -/// headers and the small `fmt `, `bext` and `ds64` bodies are read. +/// headers, small `fmt `, `bext` and `ds64` bodies, and at most one 1 MiB iXML document are read. pub(crate) fn parse(src: &Src<'_>) -> Result { if !is_wav(&src.bytes_upto(0, 12)) { return Err(AudioError::Malformed("not a RIFF/RF64 WAVE file".into())); @@ -249,6 +293,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { let mut ds64_data: Option = None; let mut fmt: Option = None; let mut bwf: Option = None; + let mut ixml_time = None; + let mut ixml_seen = false; let mut data: Option<(u64, u64)> = None; let mut pos: u64 = 12; @@ -288,7 +334,18 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { let small = |n: u64| src.bytes(body, usize::try_from(declared.min(n)).unwrap_or(0)).unwrap_or_default(); match &id { b"fmt " => fmt = Some(parse_fmt(&small(256))?), - b"bext" => bwf = parse_bext(&small(4096)), + b"bext" => { + if let Some(info) = parse_bext(&small(4096)) { + bwf = Some(info); + } + } + b"iXML" if !ixml_seen => { + // Inspect at most one bounded document, not 100,000 individually bounded trees. + ixml_seen = true; + if declared <= IXML_MAX as u64 { + ixml_time = ixml_time_reference(&small(IXML_MAX as u64)); + } + } b"ds64" => ds64_data = le_u64(&small(64), 8), _ => {} } @@ -297,6 +354,9 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { pos = next; } + if bwf.is_none() { + bwf = ixml_time.map(|time_reference| BwfInfo { time_reference, ..BwfInfo::default() }); + } let fmt = fmt.ok_or_else(|| AudioError::Malformed("WAV has no fmt chunk".into()))?; if fmt.channels == 0 { return Err(AudioError::Malformed("WAV declares zero channels".into())); diff --git a/crates/audio/src/write/coded.rs b/crates/audio/src/write/coded.rs new file mode 100644 index 000000000..0d0dd626f --- /dev/null +++ b/crates/audio/src/write/coded.rs @@ -0,0 +1,506 @@ +//! 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. + +// 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. +#![cfg_attr( + not(all(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode")), + allow(dead_code, unused_imports, unused_variables) +)] + +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 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 { + match e { + craft_media::isobmff::Error::Io(e) => AudioError::Io(e), + e => AudioError::Encode(format!("M4A: {e}")), + } +} + +/// 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 +/// last frame, so the sample durations add up to the priming plus the audio, and the edit that +/// skips the priming ends where the audio does. The movie timescale is the sample rate, which +/// keeps that edit exact. +#[cfg(any(feature = "aac-encode", feature = "alac-encode"))] +struct M4a { + mux: craft_media::isobmff::Mp4Writer, + /// The track, added with the first packet: a file with no audio gets a track without an edit. + track: Option, + entry: craft_media::isobmff::SampleEntry, + sample_rate: u32, + channels: u32, + priming: u32, + held: Option, + /// Frames and bytes of the packets written, the held one not counted. + frames: u64, + bytes: u64, +} + +#[cfg(any(feature = "aac-encode", feature = "alac-encode"))] +impl M4a { + fn new(out: W, codec: &Codec, sample_rate: u32, channels: u32) -> 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 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 }) + } + + fn track(&mut self, has_audio: bool) -> Result { + if let Some(track) = self.track { + return Ok(track); + } + let mut config = craft_media::isobmff::TrackConfig::new(self.entry.clone(), self.sample_rate); + if has_audio && self.priming > 0 { + config.media_start = Some(i64::from(self.priming)); + // AAC's overlap: a packet decodes right only after the one before it. Apple's + // decoders take the priming from the edit only when the track says so. + config.roll_distance = Some(-1); + } + let track = self.mux.add_track(config).map_err(mux_error)?; + self.track = Some(track); + Ok(track) + } + + fn sample(&mut self, packet: &Packet, 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)?; + self.frames += u64::from(duration); + self.bytes += packet.data.len() as u64; + Ok(()) + } + + fn write(&mut self, packet: Packet) -> Result<()> { + if let Some(held) = self.held.replace(packet) { + self.sample(&held, held.frames)?; + } + 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 { + 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 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) { + self.mux.set_sample_entry(track, entry).map_err(mux_error)?; + } + self.mux.finish().map_err(mux_error) + } +} + +/// Where the packets go. +enum Sink { + #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] + M4a(Box>), + /// The packets in a row are the file. + Raw(W), +} + +/// A file of one of the coded formats written block by block. +pub(crate) struct Writer { + codec: Codec, + 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, +} + +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 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)?)), + _ => Sink::Raw(out), + }; + Ok(Writer { codec, sink, map, bitrate, frames: 0, packets: Vec::new(), failed: false }) + } + + pub(crate) fn bitrate(&self) -> Option { + self.bitrate + } + + /// Hands the packets waiting to the sink. + fn drain(&mut self) -> Result<()> { + for packet in self.packets.drain(..) { + match &mut self.sink { + #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] + Sink::M4a(m4a) => m4a.write(packet)?, + Sink::Raw(out) => out.write_all(&packet.data)?, + } + } + Ok(()) + } + + /// Appends `frames` frames of `block`, which holds every channel at least that long. + pub(crate) fn write>(&mut self, block: &[C], frames: usize) -> Result<()> { + 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()); + if let Err(e) = written { + self.failed = true; + return Err(e); + } + } + self.frames = self.frames.saturating_add(frames as u64); + Ok(()) + } + + pub(crate) fn finish(mut self) -> Result { + if self.failed { + return Err(failed_write_error()); + } + self.codec.finish(&mut self.packets)?; + self.drain()?; + match self.sink { + #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] + Sink::M4a(m4a) => m4a.finish(&self.codec, self.frames), + Sink::Raw(mut out) => { + out.flush()?; + Ok(out) + } + } + } +} + +pub(crate) fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { + let mut w = Writer::new(Cursor::new(Vec::new()), opts, buf.sample_rate, buf.channels.len())?; + w.write(&buf.channels, buf.frames())?; + Ok(w.finish()?.into_inner()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/audio/src/write/coded/tests.rs b/crates/audio/src/write/coded/tests.rs new file mode 100644 index 000000000..cbdbd3375 --- /dev/null +++ b/crates/audio/src/write/coded/tests.rs @@ -0,0 +1,167 @@ +use super::*; + +use crate::Speaker; + +fn map(mask: u32, order: Option<&[usize]>, layout: u32) -> Option> { + channel_map(mask, order, &ChannelLayout::from_mask(layout)) +} + +/// Channels are matched by speaker, not by position: a layout that lists the same speakers in +/// another WAV order is reordered, and one with other speakers is refused. +#[test] +fn channels_are_mapped_by_speaker() { + // L R C LFE Ls Rs onto itself, and onto an encoder order C L R Ls Rs LFE. + assert_eq!(map(0x60F, None, 0x60F), Some(vec![0, 1, 2, 3, 4, 5])); + assert_eq!(map(0x60F, Some(&[2, 0, 1, 4, 5, 3]), 0x60F), Some(vec![2, 0, 1, 4, 5, 3])); + // Back surrounds feed a format that has one surround pair, and the other way round. + assert_eq!(map(0x60F, None, 0x3F), Some(vec![0, 1, 2, 3, 4, 5])); + assert_eq!(map(0x3F, None, 0x60F), Some(vec![0, 1, 2, 3, 4, 5])); + // 6.1 with the back centre after the pair (L R C LFE Lb Rb Cb) onto L R C LFE Cb Ls Rs. + assert_eq!(map(0x70F, None, 0x13F), Some(vec![0, 1, 2, 3, 6, 4, 5])); + // Quad has no centre; 7.1 with sides and backs has no front pair left and right of centre. + assert_eq!(map(0x107, None, 0x33), None); + assert_eq!(map(0xFF, None, 0x63F), None); + // With both pairs in the format, one pair cannot feed both. + assert_eq!(map(0x63F, None, 0xFF), None); + assert_eq!(channel_map(0x3, None, &ChannelLayout::unordered(2)), None); + assert_eq!(map(0x3, None, 0x7), None); +} + +#[cfg(feature = "aac-encode")] +#[test] +fn every_aac_channel_count_has_a_layout_and_an_order() { + for channels in 1..=8 { + let mask = EncodeFormat::Aac.layout_masks(channels as u16)[0]; + assert_eq!(mask.count_ones() as usize, channels); + let mut order = map(mask, aac_order(channels), mask).unwrap(); + order.sort_unstable(); + assert_eq!(order, (0..channels).collect::>()); + } + assert!(EncodeFormat::Aac.layout_masks(9).is_empty() && EncodeFormat::Aac.layout_masks(0).is_empty()); + // The layouts this crate's decoder reports for what the encoder writes (`track::aac_layout`), + // and configuration 7's speakers for 8 channels. + let masks: Vec = (1..=8).map(|channels| EncodeFormat::Aac.layout_masks(channels)[0]).collect(); + assert_eq!(masks, [0x4, 0x3, 0x7, 0x107, 0x607, 0x60F, 0x70F, 0xFF]); + assert_eq!( + (EncodeFormat::Mp3.layout_masks(1), EncodeFormat::Mp3.layout_masks(2), EncodeFormat::Mp3.layout_masks(3)), + (&[0x4][..], &[0x3][..], &[][..]) + ); + // Configuration 7: C, Lc Rc, L R, Ls Rs, LFE. + let wide: Vec = ChannelLayout::from_mask(0xFF).speakers(); + let named: Vec = aac_order(8).unwrap().iter().map(|&c| wide[c]).collect(); + use Speaker::*; + assert_eq!(named, [FrontCenter, FrontLeftOfCenter, FrontRightOfCenter, FrontLeft, FrontRight, BackLeft, BackRight, Lfe]); +} + +/// The range the writer keeps a bit rate in is the one the encoder accepts. +#[cfg(feature = "aac-encode")] +#[test] +fn the_aac_bit_rate_range_is_the_encoders() { + use crate::aac::{Encoder, EncoderConfig, SAMPLE_RATES}; + for &rate in &SAMPLE_RATES { + for channels in 1..=8 { + let (lo, hi) = crate::aac::cbr_range(rate, channels); + assert!(lo <= hi, "{rate} Hz, {channels} channels"); + let accepts = |bps| Encoder::new(EncoderConfig::cbr(rate, channels, bps)).is_ok(); + assert!(accepts(lo) && accepts(hi), "{rate} Hz, {channels} channels: {lo}..={hi}"); + assert!(!accepts(lo - 1) && !accepts(hi + 1), "{rate} Hz, {channels} channels: {lo}..={hi}"); + for want in [None, Some(RateControl::Bitrate(0)), Some(RateControl::Bitrate(u32::MAX))] { + let mode = aac_mode(want, rate, channels); + assert!( + Encoder::new(EncoderConfig { mode, ..EncoderConfig::cbr(rate, channels, 0) }).is_ok(), + "{rate} Hz, {channels} channels, {want:?}" + ); + } + } + } +} + +/// Every layout the AC-3 encoders have is found from its speakers, at a bit rate the encoder +/// accepts whatever rate was asked for. +#[cfg(all(feature = "ac3-encode", feature = "eac3-encode"))] +#[test] +fn ac3_settings_follow_the_layout_and_validate() { + use crate::ac3::encoder::{Codec, CodingMode}; + let layouts = [ + (0x4, CodingMode::Mono, false), + (0x3, CodingMode::Stereo, false), + (0xB, CodingMode::Stereo, true), + (0x7, CodingMode::ThreeFront, false), + (0x103, CodingMode::StereoSurround, false), + (0x107, CodingMode::ThreeFrontSurround, false), + (0x33, CodingMode::StereoTwoSurround, false), + (0x603, CodingMode::StereoTwoSurround, false), + (0x37, CodingMode::ThreeFrontTwoSurround, false), + (0x3F, CodingMode::ThreeFrontTwoSurround, true), + (0x60F, CodingMode::ThreeFrontTwoSurround, true), + ]; + for codec in [Codec::Ac3, Codec::Eac3] { + for sample_rate in [32_000, 44_100, 48_000] { + for (mask, mode, lfe) in layouts { + for want in [None, Some(RateControl::Bitrate(0)), Some(RateControl::Bitrate(200_000)), Some(RateControl::Bitrate(u32::MAX))] { + let layout = ChannelLayout::from_mask(mask); + let (config, map) = ac3_config(codec, sample_rate, &layout, want).unwrap(); + assert_eq!((config.mode, config.lfe), (mode, lfe), "{mask:#x}"); + assert_eq!(map, (0..usize::from(layout.channels())).collect::>()); + assert_eq!(config.validate(), Ok(()), "{codec:?} {sample_rate} {mask:#x} {want:?}: {} kbit/s", config.bitrate_kbps); + } + } + let seven_one = ac3_config(codec, sample_rate, &ChannelLayout::SURROUND_7_1, Some(RateControl::Bitrate(u32::MAX))); + match codec { + Codec::Ac3 => assert!(matches!(seven_one, Err(AudioError::Unsupported(_)))), + Codec::Eac3 => assert_eq!(seven_one.unwrap().0.validate(), Ok(())), + } + } + } + // The highest table rate not above the one asked for; the default is 96 kbit/s per channel. + let rate = |codec, mask, want| ac3_config(codec, 48_000, &ChannelLayout::from_mask(mask), want).unwrap().0.bitrate_kbps; + assert_eq!(rate(Codec::Ac3, 0x3, Some(RateControl::Bitrate(200_000))), 192); + assert_eq!(rate(Codec::Ac3, 0x3, None), 192); + assert_eq!(rate(Codec::Ac3, 0x60F, None), 448); + assert_eq!(rate(Codec::Ac3, 0x60F, Some(RateControl::Bitrate(1))), 160); + assert_eq!(rate(Codec::Eac3, 0x3, Some(RateControl::Bitrate(200_500))), 200); + assert!(matches!(ac3_config(Codec::Ac3, 48_000, &ChannelLayout::STEREO, Some(RateControl::Quality(0.5))), Err(AudioError::Unsupported(_)))); + assert!(matches!(ac3_config(Codec::Ac3, 48_000, &ChannelLayout::unordered(2), None), Err(AudioError::Unsupported(_)))); +} + +/// The layouts `EncodeFormat` lists are the encoders' own: ALAC's layout per channel count, and +/// the speakers of every AC-3 and E-AC-3 coding mode the encoder has. +#[cfg(all(feature = "alac-encode", feature = "ac3-encode", feature = "eac3-encode"))] +#[test] +fn the_listed_layouts_are_the_encoders() { + use crate::ac3::encoder::{Codec, CodingMode::*, Config}; + for channels in 0..=10u16 { + let alac = crate::alac::channel_mask(channels as u8); + assert_eq!(EncodeFormat::Alac.layout_masks(channels), if alac == 0 { &[][..] } else { std::slice::from_ref(&alac) }, "ALAC, {channels}"); + for (format, codec) in [(EncodeFormat::Ac3, Codec::Ac3), (EncodeFormat::Eac3, Codec::Eac3)] { + let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; + let mut encoder: Vec = modes + .iter() + .flat_map(|&mode| [false, true].map(|lfe| Config { codec, sample_rate: 48_000, bitrate_kbps: 640, mode, lfe })) + .filter(|config| config.validate().is_ok() && config.channels() == usize::from(channels)) + .filter_map(|config| config.channel_layout().mask()) + .collect(); + let mut listed = format.layout_masks(channels).to_vec(); + encoder.sort_unstable(); + listed.sort_unstable(); + assert_eq!(listed, encoder, "{format:?}, {channels} channels"); + for &mask in &listed { + let layout = ChannelLayout::from_mask(mask); + assert_eq!(ac3_config(codec, 48_000, &layout, None).unwrap().0.channel_layout(), layout); + } + } + } +} + +/// The sample rates `EncodeFormat` lists are the encoders'. +#[cfg(all(feature = "aac-encode", feature = "mp3-encode"))] +#[test] +fn the_listed_sample_rates_are_the_encoders() { + let sorted = |rates: &[u32]| { + let mut rates = rates.to_vec(); + rates.sort_unstable(); + rates + }; + assert_eq!(EncodeFormat::Aac.sample_rates().unwrap(), sorted(&crate::aac::SAMPLE_RATES)); + assert_eq!(EncodeFormat::Mp3.sample_rates().unwrap(), sorted(&crate::mp3::SAMPLE_RATES)); +} diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 2355a7b05..ce4b90773 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -1,11 +1,18 @@ -//! Encoding: WAV/BWF/RF64 and AIFF/AIFF-C writers (`pcm-encode`) and the FLAC encoder -//! (`flac-encode`), whole-buffer and streaming. +//! Encoding: WAV/BWF/RF64 and AIFF/AIFF-C writers (`pcm-encode`), the FLAC encoder +//! (`flac-encode`) and the coded formats (AAC and ALAC in M4A, MP3, AC-3 and E-AC-3 streams, each +//! with its codec's feature), whole-buffer and streaming. #[cfg(feature = "pcm-encode")] mod aiff; +#[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] +mod coded; #[cfg(feature = "flac-encode")] pub(crate) mod flac; mod pcm; +#[cfg(feature = "vorbis-encode")] +mod vorbis; +#[cfg(feature = "vorbis-encode")] +pub use vorbis::{OGG_BITRATES, encode as encode_ogg}; #[cfg(feature = "pcm-encode")] mod raw; #[cfg(feature = "pcm-encode")] @@ -14,11 +21,25 @@ mod wav; use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, Result}; #[cfg(feature = "pcm-encode")] pub use raw::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] use std::io::{Seek, Write}; -/// Encode `buf` as WAV/BWF, AIFF/AIFF-C or FLAC. Integer depths clamp samples to [-1, 1]; float +/// Encode `buf` as the file `opts.format` names. Integer depths clamp samples to [-1, 1]; float /// keeps values above full scale. `opts.layout`, when set, must have `buf`'s channel count. /// +/// The lossy formats take `opts.rate_control`. AAC and ALAC are written as M4A, which records the +/// encoder's priming and the exact length, so the file decodes to `buf`'s frames. MP3, AC-3 and +/// E-AC-3 are raw streams, which have no place for that: they decode with the codec's delay in +/// front and padded to whole frames. +/// /// ``` /// # #[cfg(feature = "pcm-encode")] { /// use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, encode}; @@ -32,6 +53,7 @@ use std::io::{Seek, Write}; pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { check_built(opts.format)?; // Checked for every format; WAV and FLAC record it. + #[cfg_attr(not(any(feature = "pcm-encode", feature = "flac-encode")), allow(unused_variables))] let mask = opts.layout.map(|l| wav_mask(&l, buf.channels.len())).transpose()?; match opts.format { #[cfg(feature = "pcm-encode")] @@ -40,6 +62,20 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { EncodeFormat::Aiff => aiff::encode(buf, opts.bit_depth, opts.dither), #[cfg(feature = "flac-encode")] EncodeFormat::Flac => flac::encode(buf, opts.bit_depth, opts.dither, mask), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 => coded::encode(buf, opts), + #[cfg(feature = "vorbis-encode")] + EncodeFormat::Ogg => { + if opts.layout.is_some_and(|layout| !EncodeFormat::Ogg.supports_layout(&layout)) { + return Err(AudioError::Unsupported("Vorbis requires a mono or stereo speaker layout".into())); + } + let kbps = match opts.rate_control { + None => 192, + Some(crate::RateControl::Bitrate(bps)) => bps / 1000, + Some(crate::RateControl::Quality(_)) => return Err(AudioError::Unsupported("Ogg export takes a target bitrate".into())), + }; + vorbis::encode(buf, kbps) + } #[allow(unreachable_patterns)] f => Err(AudioError::Unsupported(format!("writing {f:?}"))), } @@ -47,31 +83,49 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { /// Refuses a format whose writer is not built, before anything else about the request is checked. fn check_built(format: EncodeFormat) -> Result<()> { - let (built, feature) = - if format == EncodeFormat::Flac { (cfg!(feature = "flac-encode"), "flac-encode") } else { (cfg!(feature = "pcm-encode"), "pcm-encode") }; - if built { Ok(()) } else { Err(AudioError::Unsupported(format!("writing {format:?} needs the `{feature}` feature"))) } + if format.is_built() { Ok(()) } else { Err(AudioError::Unsupported(format!("writing {format:?} needs the `{}` feature", format.feature()))) } } -/// The file extensions of the formats [`encode`] can write (those whose features are on). -#[cfg(all(feature = "pcm-encode", feature = "flac-encode"))] -pub const ENCODE_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "aifc", "flac"]; -/// The file extensions of the formats [`encode`] can write (those whose features are on). -#[cfg(all(feature = "pcm-encode", not(feature = "flac-encode")))] -pub const ENCODE_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "aifc"]; -/// The file extensions of the formats [`encode`] can write (those whose features are on). -#[cfg(all(feature = "flac-encode", not(feature = "pcm-encode")))] -pub const ENCODE_EXTENSIONS: &[&str] = &["flac"]; +/// Every extension [`ENCODE_EXTENSIONS`] can list, and how many of them the features built give. +const fn extensions() -> ([&'static str; 13], usize) { + let mut all = [""; 13]; + let mut n = 0; + macro_rules! add { + ($built:expr, $($extension:literal),+) => { + if $built { + $( + all[n] = $extension; + n += 1; + )+ + } + }; + } + add!(cfg!(feature = "pcm-encode"), "wav", "wave", "bwf", "aif", "aiff", "aifc"); + add!(cfg!(feature = "flac-encode"), "flac"); + add!(cfg!(any(feature = "aac-encode", feature = "alac-encode")), "m4a"); + add!(cfg!(feature = "mp3-encode"), "mp3"); + add!(cfg!(feature = "ac3-encode"), "ac3"); + add!(cfg!(feature = "eac3-encode"), "eac3", "ec3"); + add!(cfg!(all(feature = "vorbis-encode", not(target_arch = "wasm32"))), "ogg"); + (all, n) +} -/// The format [`encode`] writes for a file extension or format name (`wav`, `aiff`, `flac`, -/// case-insensitive, with or without the dot), or `None` when it cannot write it. `aifc` is -/// AIFF: float AIFF is written as AIFF-C. +const EXTENSIONS: ([&str; 13], usize) = extensions(); + +/// The file extensions of the formats [`encode`] can write (those whose features are on). +pub const ENCODE_EXTENSIONS: &[&str] = EXTENSIONS.0.split_at(EXTENSIONS.1).0; + +/// The format [`encode`] writes for a file extension or format name (`wav`, `aiff`, `flac`, `m4a`, +/// `mp3`, `ac3`, `eac3`, case-insensitive, with or without the dot), or `None` when it cannot +/// write it. `aifc` is AIFF: float AIFF is written as AIFF-C. `m4a` is AAC when the AAC encoder +/// is built and ALAC otherwise; `alac` always names ALAC. /// /// ``` /// # #[cfg(feature = "pcm-encode")] { /// use craft_audio::{EncodeFormat, encode_format_for}; /// /// assert_eq!(encode_format_for(".AIFF"), Some(EncodeFormat::Aiff)); -/// assert_eq!(encode_format_for("mp3"), None); +/// assert_eq!(encode_format_for("unknown"), None); /// # } /// ``` pub fn encode_format_for(name: &str) -> Option { @@ -82,6 +136,20 @@ pub fn encode_format_for(name: &str) -> Option { "aif" | "aiff" | "aifc" => Some(EncodeFormat::Aiff), #[cfg(feature = "flac-encode")] "flac" => Some(EncodeFormat::Flac), + #[cfg(feature = "aac-encode")] + "m4a" => Some(EncodeFormat::Aac), + #[cfg(all(feature = "alac-encode", not(feature = "aac-encode")))] + "m4a" => Some(EncodeFormat::Alac), + #[cfg(feature = "alac-encode")] + "alac" => Some(EncodeFormat::Alac), + #[cfg(feature = "mp3-encode")] + "mp3" => Some(EncodeFormat::Mp3), + #[cfg(feature = "ac3-encode")] + "ac3" => Some(EncodeFormat::Ac3), + #[cfg(feature = "eac3-encode")] + "eac3" | "ec3" => Some(EncodeFormat::Eac3), + #[cfg(all(feature = "vorbis-encode", not(target_arch = "wasm32")))] + "ogg" => Some(EncodeFormat::Ogg), _ => None, } } @@ -98,15 +166,24 @@ fn wav_mask(layout: &ChannelLayout, channels: usize) -> Result { /// The error a stream encoder returns for every call after one of its writes has failed: the /// sink may already hold a prefix of the failed block, so the encoder's counters can no longer /// describe the bytes on the sink, and later writes or `finish` must not claim success. +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] fn failed_write_error() -> AudioError { AudioError::Encode("the stream encoder already failed on an earlier write; its output is incomplete".into()) } -/// Writes WAV/BWF (RF64 above 4 GiB), AIFF / AIFF-C `fl32` or FLAC block by block, producing -/// the same bytes [`encode`] would for the whole buffer: a file of any length never -/// has to fit in memory. The file starts at the sink's position, and nothing may follow that -/// position (a new file, or one truncated there): the encoder cannot truncate a `Write + Seek`, -/// so the bytes of a longer file already there would stay after the new one. +/// Writes a file of any [`EncodeFormat`] block by block, producing the same bytes [`encode`] +/// would for the whole buffer: a file of any length never has to fit in memory. The file starts +/// at the sink's position, and nothing may follow that position (a new file, or one truncated +/// there): the encoder cannot truncate a `Write + Seek`, so the bytes of a longer file already +/// there would stay after the new one. /// /// ``` /// # #[cfg(feature = "flac-encode")] { @@ -123,40 +200,76 @@ fn failed_write_error() -> AudioError { /// assert_eq!(&flac[..4], b"fLaC"); /// # } /// ``` +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] pub struct FileEncoder { writer: Writer, + format: EncodeFormat, channels: usize, } +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] impl std::fmt::Debug for FileEncoder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let format = match &self.writer { - #[cfg(feature = "pcm-encode")] - Writer::Wav(_) => EncodeFormat::Wav, - #[cfg(feature = "pcm-encode")] - Writer::Aiff(_) => EncodeFormat::Aiff, - #[cfg(feature = "flac-encode")] - Writer::Flac(_) => EncodeFormat::Flac, - }; - f.debug_struct("FileEncoder").field("format", &format).finish_non_exhaustive() + f.debug_struct("FileEncoder").field("format", &self.format).finish_non_exhaustive() } } -enum Writer { +// The writers differ in size with the features built; the coded one is boxed for its encoder. +#[allow(clippy::large_enum_variant)] +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] +enum Writer { #[cfg(feature = "pcm-encode")] Wav(wav::Writer), #[cfg(feature = "pcm-encode")] Aiff(aiff::Writer), #[cfg(feature = "flac-encode")] Flac(flac::Writer), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + Coded(Box>), } +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] impl FileEncoder { /// Starts a file of `channels` channels at `sample_rate` at the current position of `out`. /// `opts.layout`, when set, must have `channels` channels. pub fn new(out: W, opts: &EncodeOptions, sample_rate: u32, channels: u16) -> Result { check_built(opts.format)?; - let (depth, dither, channels) = (opts.bit_depth, opts.dither, usize::from(channels)); + let channels = usize::from(channels); + #[cfg_attr(not(any(feature = "pcm-encode", feature = "flac-encode")), allow(unused_variables))] + let (depth, dither) = (opts.bit_depth, opts.dither); + #[cfg_attr(not(any(feature = "pcm-encode", feature = "flac-encode")), allow(unused_variables))] let mask = opts.layout.map(|l| wav_mask(&l, channels)).transpose()?; let writer = match opts.format { #[cfg(feature = "pcm-encode")] @@ -172,24 +285,45 @@ impl FileEncoder { EncodeFormat::Aiff => Writer::Aiff(aiff::Writer::new(out, channels, sample_rate, depth, dither)?), #[cfg(feature = "flac-encode")] EncodeFormat::Flac => Writer::Flac(flac::Writer::new(out, channels, sample_rate, depth, dither, mask)?), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 => { + Writer::Coded(Box::new(coded::Writer::new(out, opts, sample_rate, channels)?)) + } #[allow(unreachable_patterns)] f => return Err(AudioError::Unsupported(format!("writing {f:?}"))), }; - Ok(FileEncoder { writer, channels }) + Ok(FileEncoder { writer, format: opts.format, channels }) + } + + /// The constant bit rate the file is written at, in bits per second for all channels + /// together: the rate asked for or the format's default, moved to one the stream + /// can carry as [`RateControl::Bitrate`](crate::RateControl::Bitrate) describes. `None` for the lossless + /// formats and for AAC at a constant quality. + pub fn bitrate(&self) -> Option { + match &self.writer { + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + Writer::Coded(w) => w.bitrate(), + #[allow(unreachable_patterns)] + _ => None, + } } /// Fails, without writing anything, when `frames` more frames would not fit the format (an - /// AIFF holds 4 GiB, a FLAC 2^36 - 1 frames). + /// AIFF holds 4 GiB, a FLAC 2^36 - 1 frames). The coded formats have no limit a file reaches. pub fn check_room(&self, frames: u64) -> Result<()> { match &self.writer { #[cfg(feature = "pcm-encode")] - Writer::Wav(w) => w.check_room(frames), + Writer::Wav(w) => w.check_room(frames).map(drop), #[cfg(feature = "pcm-encode")] - Writer::Aiff(w) => w.check_room(frames), + Writer::Aiff(w) => w.check_room(frames).map(drop), #[cfg(feature = "flac-encode")] - Writer::Flac(w) => w.check_room(frames), + Writer::Flac(w) => w.check_room(frames).map(drop), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + Writer::Coded(_) => { + let _ = frames; + Ok(()) + } } - .map(drop) } /// Appends the first `frames` frames of `block`, one slice per channel (`&[Vec]`, @@ -212,10 +346,13 @@ impl FileEncoder { Writer::Aiff(w) => w.write(block, frames), #[cfg(feature = "flac-encode")] Writer::Flac(w) => w.write(block, frames), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + Writer::Coded(w) => w.write(block, frames), } } - /// Completes the headers and hands back `out`, positioned at the end of the file. + /// Encodes what is still buffered, completes the headers and hands back `out`, positioned at + /// the end of the file. pub fn finish(self) -> Result { match self.writer { #[cfg(feature = "pcm-encode")] @@ -224,6 +361,67 @@ impl FileEncoder { Writer::Aiff(w) => w.finish(), #[cfg(feature = "flac-encode")] Writer::Flac(w) => w.finish(), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + Writer::Coded(w) => w.finish(), + } + } +} + +impl EncodeOptions { + /// Whether a file of `channels` channels at `sample_rate` can be written with these options: + /// `Ok`, or the error [`FileEncoder::new`] and [`encode`] would return, with nothing written. + /// For choosing a format before a file is created; [`EncodeFormat::sample_rates`], + /// [`EncodeFormat::max_channels`] and [`EncodeFormat::supports_layout`] say what a format takes. + /// + /// ``` + /// # #[cfg(feature = "mp3-encode")] { + /// use craft_audio::{EncodeFormat, EncodeOptions}; + /// + /// let mp3 = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(200_000); + /// assert!(mp3.check(48_000, 2).is_ok()); + /// assert!(mp3.check(96_000, 2).is_err()); // not an MP3 sample rate + /// assert_eq!(mp3.bitrate(48_000, 2).unwrap(), Some(192_000)); // the table rate below 200 kbit/s + /// # } + /// ``` + pub fn check(&self, sample_rate: u32, channels: u16) -> Result<()> { + self.bitrate(sample_rate, channels).map(drop) + } + + /// The constant bit rate such a file would be written at ([`FileEncoder::bitrate`]), or the + /// error [`EncodeOptions::check`] returns. + pub fn bitrate(&self, sample_rate: u32, channels: u16) -> Result> { + #[cfg(feature = "vorbis-encode")] + if self.format == EncodeFormat::Ogg { + // Vorbis is whole-buffer only and VBR has no constant output bitrate. + encode(&AudioBuffer::new(sample_rate, channels, 0), self)?; + return Ok(None); + } + // The encoder a file would get, on a sink that is thrown away: what it accepts and the + // rate it settles on are then the writer's by construction. + #[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" + ))] + { + Ok(FileEncoder::new(std::io::Cursor::new(Vec::new()), self, sample_rate, channels)?.bitrate()) + } + #[cfg(not(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" + )))] + { + let _ = (sample_rate, channels); + Err(AudioError::Unsupported("streaming encoders are not built".into())) } } } @@ -252,7 +450,7 @@ pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result< // With only one of `pcm-encode` and `flac-encode`, the other's formats are refused, not silently // written as something else. -#[cfg(all(test, not(all(feature = "pcm-encode", feature = "flac-encode"))))] +#[cfg(all(test, any(feature = "pcm-encode", feature = "flac-encode"), not(all(feature = "pcm-encode", feature = "flac-encode"))))] mod tests { use super::*; @@ -265,6 +463,7 @@ mod tests { let enc = FileEncoder::new(std::io::Cursor::new(Vec::new()), &opts, 48_000, 1); assert!(matches!(enc, Err(AudioError::Unsupported(_)))); assert_eq!(encode_format_for(name), None); + assert!(!format.is_built() && EncodeFormat::ALL.iter().any(|f| f.is_built())); // Also with a layout it could not use. let opts = opts.with_layout(ChannelLayout::STEREO); assert!(matches!(encode(&buf, &opts), Err(AudioError::Unsupported(_)))); diff --git a/crates/audio/src/write/pcm.rs b/crates/audio/src/write/pcm.rs index 614d5a4a7..402b9bebc 100644 --- a/crates/audio/src/write/pcm.rs +++ b/crates/audio/src/write/pcm.rs @@ -1,6 +1,9 @@ //! PCM helpers shared by the WAV, AIFF and FLAC writers: quantization (with optional TPDF //! dither), interleaving and layout checks. +// The coded formats use the layout check, and of those only ALAC the quantizer. +#![cfg_attr(not(any(feature = "pcm-encode", feature = "flac-encode")), allow(dead_code))] + use crate::{AudioBuffer, AudioError, Result}; #[cfg(feature = "pcm-encode")] use {crate::BitDepth, std::io::Write}; diff --git a/crates/audio/src/write/vorbis.rs b/crates/audio/src/write/vorbis.rs new file mode 100644 index 000000000..f56d01148 --- /dev/null +++ b/crates/audio/src/write/vorbis.rs @@ -0,0 +1,130 @@ +//! Ogg Vorbis encoding (RFC 5334): the reference libvorbis encoder, built from its C sources by +//! `vorbis_rs`. Stereo or mono, variable bitrate at the requested kbit/s (64–500), with a +//! fallback to a quality preset when the bitrate is not supported for the rate and channel count. + +use crate::{AudioBuffer, AudioError, Result}; + +/// The bitrates an Ogg Vorbis export is asked for, in kbit/s. +pub const OGG_BITRATES: (u32, u32) = (64, 500); + +/// The block size the encoder processes at a time: small enough that memory stays bounded +/// regardless of file length. +#[cfg(not(target_arch = "wasm32"))] +const BLOCK: usize = 4096; + +#[cfg(not(target_arch = "wasm32"))] +fn encode_error(e: vorbis_rs::VorbisError) -> AudioError { + AudioError::Encode(e.to_string()) +} + +/// Encode `buf` as an Ogg Vorbis stream at about `kbps` (variable, as Vorbis is): stereo, or mono +/// for a mono buffer. A bitrate the encoder has no setup for at that rate and channel count falls +/// back to a quality that suits it. `Err` says why there is nothing. +#[cfg(not(target_arch = "wasm32"))] +pub fn encode(buf: &AudioBuffer, kbps: u32) -> Result> { + use std::num::{NonZeroU8, NonZeroU32}; + + let channels = buf.channels.len(); + if !(1..=2).contains(&channels) { + return Err(AudioError::Unsupported("Ogg Vorbis export requires mono or stereo audio".into())); + } + if buf.channels.iter().any(|c| c.len() != buf.frames() || c.iter().any(|s| !s.is_finite())) { + return Err(AudioError::Encode("Vorbis samples must be finite and channels equally long".into())); + } + let (Some(rate), Some(count)) = (NonZeroU32::new(buf.sample_rate), NonZeroU8::new(channels as u8)) else { + return Err(AudioError::Encode("there is no audio to encode".into())); + }; + let target = NonZeroU32::new(kbps.clamp(OGG_BITRATES.0, OGG_BITRATES.1) * 1000).unwrap_or(NonZeroU32::MIN); + + let encode = |strategy: vorbis_rs::VorbisBitrateManagementStrategy| -> Result> { + let mut encoder = vorbis_rs::VorbisEncoderBuilder::new_with_serial(rate, count, Vec::new(), 0x4C43_5246) + .bitrate_management_strategy(strategy) + .build() + .map_err(encode_error)?; + let frames = buf.frames(); + let mut at = 0usize; + while at < frames { + let end = (at + BLOCK).min(frames); + let block: Vec<&[f32]> = buf.channels.iter().take(channels).map(|side| side.get(at..end).unwrap_or_default()).collect(); + encoder.encode_audio_block(&block).map_err(encode_error)?; + at = end; + } + encoder.finish().map_err(encode_error) + }; + + // Convert Rust unwinds to an error. This does not catch native crashes or aborts. + let attempt = |strategy| { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| encode(strategy))) + .unwrap_or_else(|_| Err(AudioError::Encode("the Vorbis encoder failed".into()))) + }; + match attempt(vorbis_rs::VorbisBitrateManagementStrategy::Vbr { target_bitrate: target }) { + Ok(bytes) => Ok(bytes), + Err(_) => attempt(vorbis_rs::VorbisBitrateManagementStrategy::QualityVbr { target_quality: 0.6 }) + .map_err(|e| AudioError::Encode(format!("the Vorbis encoder refused the audio: {e}"))), + } +} + +/// Ogg Vorbis encoding is unavailable on WASM; returns an unsupported-format error. +#[cfg(target_arch = "wasm32")] +pub fn encode(_buf: &AudioBuffer, _kbps: u32) -> Result> { + Err(AudioError::Unsupported("Ogg Vorbis files are exported by the desktop app".into())) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn rejects_unsupported_or_malformed_channels_without_dropping_audio() { + for channels in [0, 3, 6] { + assert!(matches!(encode(&AudioBuffer::new(48_000, channels, 16), 192), Err(AudioError::Unsupported(_)))); + } + let ragged = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.0; 16], vec![0.0; 15]] }; + assert!(encode(&ragged, 192).is_err()); + assert!(encode(&AudioBuffer::new(0, 1, 16), 192).is_err()); + let invalid = AudioBuffer { sample_rate: 48_000, channels: vec![vec![f32::NAN]] }; + assert!(encode(&invalid, 192).is_err()); + } + + #[test] + fn generic_and_direct_encoders_write_mono_and_stereo_ogg() { + for channels in [1, 2] { + let audio = AudioBuffer::new(48_000, channels, 512); + let opts = crate::EncodeOptions::new(crate::EncodeFormat::Ogg); + assert!(opts.check(48_000, channels).is_ok()); + assert_eq!(opts.bitrate(48_000, channels).unwrap(), None); + let direct = encode(&audio, 192).unwrap(); + let generic = crate::encode(&audio, &opts).unwrap(); + assert!(direct.starts_with(b"OggS")); + assert_eq!(direct, generic); + #[cfg(feature = "decode")] + { + let (info, decoded) = crate::decode(&generic, Some("ogg")).unwrap(); + assert_eq!(info.channels, channels); + assert_eq!(decoded.num_channels(), channels); + assert_eq!(decoded.frames(), audio.frames()); + } + } + } + #[cfg(feature = "decode")] + #[test] + fn distinct_signals_survive_full_and_partial_blocks() { + for frames in [4096, 4097, 8193] { + let channels: Vec> = [440.0f32, 880.0] + .into_iter() + .map(|hz| (0..frames).map(|i| (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin() * 0.4).collect()) + .collect(); + let audio = AudioBuffer { sample_rate: 48_000, channels }; + let bytes = encode(&audio, 192).unwrap(); + let (_, decoded) = crate::decode(&bytes, Some("ogg")).unwrap(); + assert_eq!(decoded.frames(), frames); + assert_eq!(decoded.channels.len(), 2); + for (expected, actual) in audio.channels.iter().zip(&decoded.channels) { + let mse = expected.iter().zip(actual).map(|(a, b)| (a - b).powi(2)).sum::() / frames as f32; + // Vorbis is lossy; this tolerates codec error but rejects silence or swapped channels. + assert!(mse.sqrt() < 0.08, "{frames} frames: RMS error {}", mse.sqrt()); + } + } + } +} diff --git a/crates/audio/tests/audio/decode_extensions.rs b/crates/audio/tests/audio/decode_extensions.rs index e8fe22d58..fc961cc39 100644 --- a/crates/audio/tests/audio/decode_extensions.rs +++ b/crates/audio/tests/audio/decode_extensions.rs @@ -62,11 +62,21 @@ fn every_decode_extension_probes_and_decodes() { fn every_encode_format_has_an_extension_it_is_written_and_read_under() { for &format in EncodeFormat::ALL { let ext = format.extension(); - assert_eq!(craft_audio::encode_format_for(ext), Some(format), "{ext}"); - assert!(craft_audio::ENCODE_EXTENSIONS.contains(&ext), "{ext}"); + // The extension names the format, or for `m4a`, which two formats share, AAC before ALAC. + // A format whose feature is off has no name. + match craft_audio::encode_format_for(ext) { + Some(named) => { + let shares_m4a = |f| matches!(f, EncodeFormat::Aac | EncodeFormat::Alac); + assert!(named == format || (shares_m4a(named) && shares_m4a(format)), "{ext}"); + assert!(named.is_built(), "{ext}"); + assert!(craft_audio::ENCODE_EXTENSIONS.contains(&ext), "{ext}"); + } + None => assert!(!matches!(format, EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac), "{ext}"), + } assert!(DECODE_EXTENSIONS.contains(&ext), "{ext}: what is written reads back"); assert!(format.mime_type().starts_with("audio/"), "{format:?}"); } - assert_eq!(EncodeFormat::ALL.iter().map(|f| f.extension()).collect::>(), ["wav", "aif", "flac"]); + let extensions: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.extension()).collect(); + assert_eq!(extensions, ["wav", "aif", "flac", "m4a", "m4a", "mp3", "ac3", "eac3", "ogg"]); assert_eq!(EncodeFormat::Aiff.mime_type(), "audio/aiff"); } diff --git a/crates/audio/tests/audio/encode_format.rs b/crates/audio/tests/audio/encode_format.rs index 30b992685..e91f93623 100644 --- a/crates/audio/tests/audio/encode_format.rs +++ b/crates/audio/tests/audio/encode_format.rs @@ -14,7 +14,15 @@ fn only_formats_the_encoder_writes_are_named() { for name in craft_audio::ENCODE_EXTENSIONS { assert!(encode_format_for(name).is_some(), "{name}"); } - for other in ["mp3", "ogg", "m4a", "xyz", ""] { + for other in ["opus", "aac", "mp4", "xyz", ""] { assert_eq!(encode_format_for(other), None, "{other}"); } } + +#[test] +fn ogg_names_follow_the_native_feature() { + let built = cfg!(all(feature = "vorbis-encode", not(target_arch = "wasm32"))); + assert_eq!(EncodeFormat::Ogg.is_built(), built); + assert_eq!(encode_format_for("ogg"), built.then_some(EncodeFormat::Ogg)); + assert_eq!(craft_audio::ENCODE_EXTENSIONS.contains(&"ogg"), built); +} diff --git a/crates/audio/tests/audio/main.rs b/crates/audio/tests/audio/main.rs index 8c37256d6..52e1d17f4 100644 --- a/crates/audio/tests/audio/main.rs +++ b/crates/audio/tests/audio/main.rs @@ -10,3 +10,4 @@ mod raw_pcm; mod roundtrip; mod stream; mod wav_empty_data; +mod wav_ixml; diff --git a/crates/audio/tests/audio/wav_ixml.rs b/crates/audio/tests/audio/wav_ixml.rs new file mode 100644 index 000000000..88e0cfcbf --- /dev/null +++ b/crates/audio/tests/audio/wav_ixml.rs @@ -0,0 +1,87 @@ +//! iXML timestamp parity with FilmCraft's streaming WAV reader, including hostile metadata. +use std::io::Cursor; + +use craft_audio::{DecodeOptions, Decoder}; +use craft_media::ReadSeekSource; + +fn chunk(id: &[u8; 4], body: &[u8]) -> Vec { + let mut out = id.to_vec(); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(body); + if !body.len().is_multiple_of(2) { + out.push(0); + } + out +} + +fn wav(metadata: &[Vec]) -> Vec { + let mut out = b"RIFF\0\0\0\0WAVE".to_vec(); + out.extend(chunk(b"fmt ", &[1, 0, 1, 0, 0x80, 0xbb, 0, 0, 0, 0x77, 1, 0, 2, 0, 16, 0])); + for m in metadata { + out.extend(m); + } + out.extend(chunk(b"data", &[0, 0, 1, 0])); + let len = (out.len() - 8) as u32; + out[4..8].copy_from_slice(&len.to_le_bytes()); + out +} + +fn xml(low: &str, high: Option<&str>) -> Vec { + let high = high.map(|v| format!("{v}")).unwrap_or_default(); + chunk(b"iXML", format!("{low}{high}").as_bytes()) +} + +fn check(file: Vec, expected: Option) { + let options = DecodeOptions::default(); + let mut bytes = Decoder::from_bytes(&file, Some("wav"), &options).unwrap(); + assert_eq!(bytes.info().bwf.as_ref().map(|b| b.time_reference), expected); + let source = ReadSeekSource::new(Cursor::new(file.clone())).unwrap(); + let mut stream = Decoder::open(source, Some("wav"), &options).unwrap(); + assert_eq!(stream.info().bwf.as_ref().map(|b| b.time_reference), expected); + assert_eq!(bytes.info().frames, 2); + assert_eq!(stream.next_block().unwrap().unwrap().frames(), 2); + assert_eq!(bytes.next_block().unwrap().unwrap().frames(), 2); +} + +#[test] +fn ixml_fallback_preserves_large_timestamps_and_optional_high_word() { + check(wav(&[xml(" 5 ", Some("1"))]), Some((1 << 32) + 5)); + check(wav(&[xml("0", None)]), Some(0)); + check(wav(&[xml("4294967295", Some("4294967295"))]), Some(u64::MAX)); +} + +#[test] +fn bext_wins_in_either_chunk_order_including_timestamp_zero() { + let bext = chunk(b"bext", &[0; 602]); + let ixml = xml("5", Some("1")); + check(wav(&[bext.clone(), ixml.clone()]), Some(0)); + check(wav(&[ixml.clone(), bext.clone()]), Some(0)); + check(wav(&[bext, chunk(b"bext", &[0; 12]), ixml.clone()]), Some(0)); + check(wav(&[chunk(b"bext", &[0; 12]), ixml]), Some((1 << 32) + 5)); +} + +#[test] +fn invalid_metadata_never_fabricates_a_timestamp_or_blocks_audio() { + for low in ["4294967296", "-1", "+1", "", "1.5", "5"] { + check(wav(&[xml(low, Some("0"))]), None); + } + for high in ["4294967296", "-1", "", "oops"] { + check(wav(&[xml("5", Some(high))]), None); + } + for text in [ + "5", + "", + "56", + "5", + ] { + check(wav(&[chunk(b"iXML", text.as_bytes())]), None); + } + check(wav(&[chunk(b"iXML", &vec![b' '; (1 << 20) + 1])]), None); + let deep = format!("{}{}", "".repeat(40), "".repeat(40)); + check(wav(&[chunk(b"iXML", deep.as_bytes())]), None); +} + +#[test] +fn only_first_ixml_document_is_considered() { + check(wav(&[xml("5", None), xml("6", None)]), Some(5)); +} diff --git a/crates/audio/tests/codecs/file_formats.rs b/crates/audio/tests/codecs/file_formats.rs new file mode 100644 index 000000000..84169f665 --- /dev/null +++ b/crates/audio/tests/codecs/file_formats.rs @@ -0,0 +1,591 @@ +//! The coded formats of `encode` and `FileEncoder` (AAC and ALAC in M4A; MP3, AC-3 and E-AC-3 +//! streams), read back with this crate's decoder and, where ffmpeg is installed, with ffmpeg. + +use std::io::{Cursor, Seek, SeekFrom, Write}; +use std::process::Command; + +use craft_audio::{ + AudioBuffer, AudioError, BitDepth, ChannelLayout, CodecId, Container, ENCODE_EXTENSIONS, EncodeFormat, EncodeOptions, FileEncoder, RateControl, + decode, encode, encode_format_for, +}; + +const CODED: [EncodeFormat; 5] = [EncodeFormat::Aac, EncodeFormat::Alac, EncodeFormat::Mp3, EncodeFormat::Ac3, EncodeFormat::Eac3]; + +/// `channels` channels of `frames` frames, each channel a tone of its own frequency, on the +/// 16-bit grid (so a lossless 16-bit format returns it exactly). +fn tones(sample_rate: u32, channels: usize, frames: usize) -> AudioBuffer { + let channel = |c: usize| { + let step = (60.0 + 17.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() + }; + AudioBuffer { sample_rate, channels: (0..channels).map(channel).collect() } +} + +/// Signal-to-noise ratio in dB of `got` against `want`, over the frames both have. +fn snr(want: &[f32], got: &[f32]) -> f64 { + let (signal, noise) = + want.iter().zip(got).fold((0f64, 0f64), |(s, n), (&w, &g)| (s + f64::from(w).powi(2), n + (f64::from(w) - f64::from(g)).powi(2))); + 10.0 * (signal / noise.max(1e-30)).log10() +} + +fn is_unsupported(r: Result) -> bool { + matches!(r, Err(AudioError::Unsupported(_))) +} + +/// An AAC file decodes to the frames that were written, in place: the edit list skips the +/// encoder's priming and cuts the padding of the last packet. +#[test] +fn aac_decodes_to_the_frames_written() { + for frames in [1, 1000, 1024, 1025, 5000, 48_017] { + let buf = tones(48_000, 2, frames); + let file = encode(&buf, &EncodeOptions::new(EncodeFormat::Aac)).unwrap(); + let (info, out) = decode(&file, Some("m4a")).unwrap(); + assert_eq!((info.container, info.codec, info.sample_rate, info.damaged), (Container::Mp4, CodecId::Aac, 48_000, 0)); + assert_eq!((info.frames, out.frames(), info.layout), (frames as u64, frames, ChannelLayout::STEREO), "{frames} frames"); + if frames >= 5000 { + for (want, got) in buf.channels.iter().zip(&out.channels) { + assert!(snr(want, got) > 30.0, "{frames} frames: {} dB", snr(want, got)); + } + } + } +} + +/// The M4A track's durations add up to the priming and the audio, and its one edit skips the +/// priming and lasts as long as the audio, in a movie timescale that is the sample rate. +#[test] +fn aac_timing_is_in_the_sample_table_and_the_edit_list() { + use craft_audio::craft_media::isobmff; + let file = encode(&tones(44_100, 1, 3000), &EncodeOptions::new(EncodeFormat::Aac)).unwrap(); + let mp4 = isobmff::open(file.as_slice()).unwrap(); + let track = &mp4.tracks[0]; + assert_eq!((mp4.timescale, track.timescale), (44_100, 44_100)); + assert_eq!(track.samples.iter().map(|s| u64::from(s.duration)).sum::(), 1024 + 3000); + assert_eq!(track.edits.len(), 1); + assert_eq!((track.edits[0].media_time, track.edits[0].segment_duration), (1024, 3000)); + // Every packet is in a `roll` group of distance -1, which Apple's decoders need to apply the edit. + let groups = &track.sample_groups; + assert_eq!((groups.len(), groups[0].grouping_type), (1, isobmff::FourCc(*b"roll"))); + assert_eq!((groups[0].runs.as_slice(), &groups[0].descriptions), ([(track.samples.len() as u32, 1)].as_slice(), &vec![vec![0xFF, 0xFF]])); +} + +/// The sample entry is completed when the file is: AAC's average bit rate, and the largest packet +/// and average bit rate in ALAC's cookie. +#[test] +fn the_sample_entry_describes_the_finished_stream() { + use craft_audio::craft_media::isobmff::{self, CodecConfig}; + let buf = tones(48_000, 2, 48_000); + let file = encode(&buf, &EncodeOptions::new(EncodeFormat::Aac).with_bitrate(96_000)).unwrap(); + let mp4 = isobmff::open(file.as_slice()).unwrap(); + let CodecConfig::Aac(aac) = &mp4.tracks[0].entries[0].codec else { panic!("not AAC") }; + assert!((90_000..100_000).contains(&aac.avg_bitrate), "{} bit/s", aac.avg_bitrate); + + let file = encode(&buf, &EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16)).unwrap(); + let mp4 = isobmff::open(file.as_slice()).unwrap(); + let CodecConfig::Alac { cookie } = &mp4.tracks[0].entries[0].codec else { panic!("not ALAC") }; + let config = craft_audio::alac::SpecificConfig::parse(cookie).unwrap(); + let largest = mp4.tracks[0].samples.iter().map(|s| s.size).max().unwrap(); + assert_eq!((config.max_frame_bytes, config.bit_depth, config.frame_length), (largest, 16, 4096)); + assert!(config.avg_bit_rate > 0); +} + +/// Dither reaches ALAC's quantizer: a level below one 16-bit step is silence without it. +#[test] +fn alac_dithers_when_asked() { + let buf = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.3 / 32768.0; 4096]] }; + let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16); + let (_, plain) = decode(&encode(&buf, &opts).unwrap(), Some("m4a")).unwrap(); + let (_, dithered) = decode(&encode(&buf, &opts.with_dither(true)).unwrap(), Some("m4a")).unwrap(); + assert!(plain.channels[0].iter().all(|&s| s == 0.0)); + assert!(dithered.channels[0].iter().any(|&s| s != 0.0)); +} + +/// ALAC returns the quantized samples exactly, for every channel count, with each channel where +/// its speaker is. +#[test] +fn alac_is_lossless_in_every_layout() { + for channels in 1..=8u8 { + let layout = ChannelLayout::from_mask(craft_audio::alac::channel_mask(channels)); + let buf = tones(44_100, usize::from(channels), 10_000); + let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(layout); + let file = encode(&buf, &opts).unwrap(); + let (info, out) = decode(&file, Some("m4a")).unwrap(); + assert_eq!((info.container, info.codec, info.frames, info.layout), (Container::Mp4, CodecId::Alac, 10_000, layout), "{channels} channels"); + assert_eq!(out, buf, "{channels} channels"); + } + // 24 bits, and a length that is no whole number of packets. + let buf = tones(96_000, 2, 4096 * 2 + 1); + let (_, out) = decode(&encode(&buf, &EncodeOptions::new(EncodeFormat::Alac)).unwrap(), Some("m4a")).unwrap(); + assert_eq!(out, buf); +} + +/// Channels go to the encoder by speaker. ALAC's 6.1 has the back centre last and AAC's has it +/// before the surround pair; 5.1 with side surrounds is the format's one 5.1. +#[test] +fn channels_reach_their_speakers() { + // WAV 6.1 with a back pair (L R C LFE Lb Rb Cb), the usual 7-channel layout, into ALAC: the same. + let buf = tones(48_000, 7, 8000); + let (info, out) = decode(&encode(&buf, &EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16)).unwrap(), Some("m4a")).unwrap(); + assert_eq!(info.layout, ChannelLayout::from_mask(0x13F)); + assert_eq!(out, buf); + // 5.1 with side surrounds decodes from ALAC as 5.1 with back surrounds, channel for channel. + let buf = tones(48_000, 6, 8000); + let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(ChannelLayout::SURROUND_5_1_SIDE); + assert_eq!(decode(&encode(&buf, &opts).unwrap(), Some("m4a")).unwrap().1, buf); + + // AAC: the decoded channel each input channel comes back as. 5.1 decodes in WAV order; the + // 6.1 and 7.1 streams have no speaker assignment and decode in AAC order (C L R Ls Rs Cs LFE + // and C Lc Rc L R Ls Rs LFE). + let wide = ChannelLayout::from_mask(0xFF); + let cases: [(usize, Option, &[usize]); 3] = + [(6, None, &[0, 1, 2, 3, 4, 5]), (7, None, &[2, 0, 1, 4, 5, 6, 3]), (8, Some(wide), &[2, 6, 7, 0, 1, 4, 5, 3])]; + for (channels, layout, decoded_from) in cases { + let buf = tones(48_000, channels, 48_000); + let mut opts = EncodeOptions::new(EncodeFormat::Aac); + opts.layout = layout; + let (info, out) = decode(&encode(&buf, &opts).unwrap(), Some("m4a")).unwrap(); + assert_eq!((usize::from(info.channels), out.frames()), (channels, 48_000)); + for (decoded, &input) in decoded_from.iter().enumerate() { + let db = snr(&buf.channels[input], &out.channels[decoded]); + assert!(db > 20.0, "{channels} channels: decoded {decoded} is not input {input} ({db} dB)"); + } + } +} + +/// MP3, AC-3 and E-AC-3 are raw streams: the audio comes back behind the codec's delay. +#[test] +fn raw_streams_decode_behind_the_codec_delay() { + let buf = tones(48_000, 2, 48_000); + for (format, codec, container, delay, floor) in [ + (EncodeFormat::Mp3, CodecId::Mp3, Container::MpegAudio, craft_audio::mp3::DELAY as usize, 25.0), + (EncodeFormat::Ac3, CodecId::Ac3, Container::Ac3, 256, 15.0), + (EncodeFormat::Eac3, CodecId::Eac3, Container::Ac3, 256, 15.0), + ] { + let file = encode(&buf, &EncodeOptions::new(format)).unwrap(); + let (info, out) = decode(&file, Some(format.extension())).unwrap(); + assert_eq!((info.codec, info.container, info.sample_rate, info.layout, info.damaged), (codec, container, 48_000, ChannelLayout::STEREO, 0)); + assert_eq!((format.codec(), format.container()), (codec, container)); + assert!(out.frames() >= 48_000 + delay, "{format:?}: {} frames", out.frames()); + for (want, got) in buf.channels.iter().zip(&out.channels) { + let db = snr(want, &got[delay..]); + assert!(db > floor, "{format:?}: {db} dB"); + } + } + // 5.1 with back surrounds is AC-3's 3/2 mode with an LFE, channel for channel. + let buf = tones(48_000, 6, 48_000); + let (info, out) = decode(&encode(&buf, &EncodeOptions::new(EncodeFormat::Ac3)).unwrap(), Some("ac3")).unwrap(); + assert_eq!(info.layout, ChannelLayout::SURROUND_5_1_SIDE); + for (c, (want, got)) in buf.channels.iter().zip(&out.channels).enumerate() { + // The encoder low-pass filters the LFE, which shifts its phase: it is compared by level. + if c == 3 { + let rms = |x: &[f32]| (x.iter().map(|&s| f64::from(s).powi(2)).sum::() / x.len() as f64).sqrt(); + let level = rms(&got[4800..]) / rms(want); + assert!((0.5..1.5).contains(&level), "LFE at {level} of its level"); + } else { + assert!(snr(want, &got[256..]) > 12.0, "channel {c}: {} dB", snr(want, &got[256..])); + } + } + // 7.1 is an E-AC-3 programme. + let buf = tones(48_000, 8, 4800); + assert!(is_unsupported(encode(&buf, &EncodeOptions::new(EncodeFormat::Ac3)))); + // (Read back by ffmpeg in `ffmpeg_reads_the_files`: this crate's file reader plays the 5.1 + // independent substream of a raw 7.1 stream.) + assert!(!encode(&buf, &EncodeOptions::new(EncodeFormat::Eac3)).unwrap().is_empty()); +} + +/// Blocks of any sizes give the bytes `encode` gives. +#[test] +fn streaming_writes_the_bytes_of_encode() { + let buf = tones(44_100, 2, 30_000); + for format in CODED { + let opts = EncodeOptions::new(format); + let whole = encode(&buf, &opts).unwrap(); + let mut enc = FileEncoder::new(Cursor::new(Vec::new()), &opts, 44_100, 2).unwrap(); + assert!(format!("{enc:?}").contains(&format!("{format:?}"))); + let mut at = 0; + for n in [1, 4095, 4097, 0, 9000, 12_807] { + let block: Vec<&[f32]> = buf.channels.iter().map(|c| &c[at..]).collect(); + enc.check_room(n as u64).unwrap(); + enc.write(&block, n).unwrap(); + at += n; + } + assert_eq!(at, buf.frames()); + assert!(enc.finish().unwrap().into_inner() == whole, "{format:?}"); + } +} + +/// A file starts at the sink's position. +#[test] +fn a_file_starts_at_the_sinks_position() { + let buf = tones(48_000, 1, 6000); + for format in CODED { + let opts = EncodeOptions::new(format); + let mut sink = Cursor::new(b"junk".to_vec()); + sink.seek(SeekFrom::End(0)).unwrap(); + let mut enc = FileEncoder::new(sink, &opts, 48_000, 1).unwrap(); + enc.write(&buf.channels, 6000).unwrap(); + let mut sink = enc.finish().unwrap(); + let end = sink.stream_position().unwrap(); + let bytes = sink.into_inner(); + assert_eq!(end, bytes.len() as u64, "{format:?}"); + assert!(bytes[4..] == encode(&buf, &opts).unwrap(), "{format:?}"); + } +} + +/// A file with no audio is still a file of its format. +#[test] +fn no_audio_gives_an_empty_file() { + let buf = AudioBuffer::new(48_000, 2, 0); + for format in CODED { + let file = encode(&buf, &EncodeOptions::new(format)).unwrap(); + if format.container() == Container::Mp4 { + let mp4 = craft_audio::craft_media::isobmff::open(file.as_slice()).unwrap(); + assert_eq!((mp4.tracks.len(), mp4.tracks[0].samples.len(), mp4.tracks[0].edits.len()), (1, 0, 0), "{format:?}"); + } else { + assert!(file.is_empty(), "{format:?}"); + } + } +} + +/// The bit rate asked for is the one written, moved to the nearest the format has. +#[test] +fn the_bit_rate_is_followed() { + let buf = tones(48_000, 2, 48_000); + let size = |opts: &EncodeOptions| encode(&buf, opts).unwrap().len(); + // MP3 at 48 kHz: 24 bytes per frame and kbit/s, 43 frames for a second and the delay. + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Mp3)), 43 * 192 * 3); + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(130_000)), 43 * 128 * 3); + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(1)), 43 * 32 * 3); + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(u32::MAX)), 43 * 320 * 3); + // AC-3: 32 packets of 1536 frames, 4 bytes per packet and kbit/s. + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Ac3)), 32 * 192 * 4); + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Ac3).with_bitrate(100_000)), 32 * 96 * 4); + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Eac3).with_bitrate(100_000)), 32 * 100 * 4); + // AAC: a second of audio at about the rate asked for, around the 128 kbit/s default. + let (low, default, high) = ( + size(&EncodeOptions::new(EncodeFormat::Aac).with_bitrate(64_000)), + size(&EncodeOptions::new(EncodeFormat::Aac)), + size(&EncodeOptions::new(EncodeFormat::Aac).with_bitrate(256_000)), + ); + assert!((7000..10_000).contains(&low) && (15_000..18_500).contains(&default) && (30_000..35_000).contains(&high), "{low} {default} {high}"); + // A rate no stream can carry is moved into range, not refused. + encode(&buf, &EncodeOptions::new(EncodeFormat::Aac).with_bitrate(u32::MAX)).unwrap(); + // The lowest rate still codes the audio: the encoder accepts rates that leave only silence + // (128 for 128 kbit/s is one), and the writer does not go that low. + for (sample_rate, channels) in [(8000, 1), (16_000, 2), (44_100, 2), (48_000, 6), (96_000, 2)] { + let buf = tones(sample_rate, channels, sample_rate as usize); + let (_, out) = decode(&encode(&buf, &EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128)).unwrap(), Some("m4a")).unwrap(); + let rms = |x: &[f32]| (x.iter().map(|&s| f64::from(s).powi(2)).sum::() / x.len() as f64).sqrt(); + let level = rms(&out.channels[0]) / rms(&buf.channels[0]); + assert!(level > 0.5, "{sample_rate} Hz, {channels} channels: {level} of the level"); + } + // Quality is AAC's; ALAC has no rate to control. + let (small, large) = + (size(&EncodeOptions::new(EncodeFormat::Aac).with_quality(0.0)), size(&EncodeOptions::new(EncodeFormat::Aac).with_quality(1.0))); + assert!(small < large, "{small} {large}"); + assert!(matches!(encode(&buf, &EncodeOptions::new(EncodeFormat::Aac).with_quality(f32::NAN)), Err(AudioError::Encode(_)))); + for format in [EncodeFormat::Mp3, EncodeFormat::Ac3, EncodeFormat::Eac3] { + assert!(is_unsupported(encode(&buf, &EncodeOptions::new(format).with_quality(0.5))), "{format:?}"); + } + let alac = EncodeOptions::new(EncodeFormat::Alac); + assert_eq!(size(&alac), size(&alac.clone().with_bitrate(64_000))); + assert_eq!(alac.rate_control, None); + assert_eq!(alac.with_quality(0.5).rate_control, Some(RateControl::Quality(0.5))); +} + +/// What a format cannot hold is refused before anything is written. +#[test] +fn what_a_format_cannot_hold_is_refused() { + let refused = |format, sample_rate, channels: u16, layout: Option| { + let mut opts = EncodeOptions::new(format); + opts.layout = layout; + let mut sink = Cursor::new(Vec::new()); + let r = FileEncoder::new(&mut sink, &opts, sample_rate, channels).map(drop); + assert!(r.is_ok() || sink.into_inner().is_empty(), "{format:?}: bytes written for a refused file"); + assert_eq!(r.is_err(), encode(&AudioBuffer::new(sample_rate, channels, 100), &opts).is_err()); + r + }; + // Quad has no centre, which AAC's and ALAC's four channels have. + assert!(is_unsupported(refused(EncodeFormat::Aac, 48_000, 4, None))); + assert!(is_unsupported(refused(EncodeFormat::Alac, 48_000, 4, None))); + refused(EncodeFormat::Aac, 48_000, 4, Some(ChannelLayout::from_mask(0x107))).unwrap(); + // WAV 7.1 (backs and sides) is not the 7.1 of AAC and ALAC (a front pair left and right of centre). + assert!(is_unsupported(refused(EncodeFormat::Aac, 48_000, 8, None))); + assert!(is_unsupported(refused(EncodeFormat::Alac, 48_000, 8, Some(ChannelLayout::SURROUND_7_1)))); + assert!(is_unsupported(refused(EncodeFormat::Aac, 48_000, 2, Some(ChannelLayout::unordered(2))))); + for format in CODED { + assert!(is_unsupported(refused(format, 48_000, 9, None)), "{format:?}"); + assert!(matches!(refused(format, 48_000, 2, Some(ChannelLayout::MONO)), Err(AudioError::Encode(_))), "{format:?}"); + assert!(matches!(refused(format, 0, 2, None), Err(AudioError::Encode(_))), "{format:?}"); + assert!(matches!(refused(format, 48_000, 0, None), Err(AudioError::Encode(_))), "{format:?}"); + } + assert!(is_unsupported(refused(EncodeFormat::Mp3, 48_000, 3, None))); + assert!(is_unsupported(refused(EncodeFormat::Ac3, 48_000, 7, None))); + // Sample rates the codec has not. + for format in [EncodeFormat::Aac, EncodeFormat::Mp3, EncodeFormat::Ac3, EncodeFormat::Eac3] { + assert!(matches!(refused(format, 44_000, 2, None), Err(AudioError::Encode(_))), "{format:?}"); + } + refused(EncodeFormat::Alac, 44_000, 2, None).unwrap(); + let float = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Float32); + assert!(is_unsupported(encode(&AudioBuffer::new(48_000, 2, 100), &float))); +} + +/// Samples no encoder should see: NaN is silence, and values past full scale do not fail a +/// write (AC-3, whose encoder refuses them, gets them clamped). +#[test] +fn non_finite_and_loud_samples_are_written() { + let mut buf = tones(48_000, 2, 6000); + buf.channels[0][100] = f32::NAN; + buf.channels[0][200] = f32::INFINITY; + buf.channels[1][300] = -7.5; + for format in CODED { + let file = encode(&buf, &EncodeOptions::new(format)).unwrap(); + let (_, out) = decode(&file, Some(format.extension())).unwrap(); + assert!(out.channels.iter().flatten().all(|s| s.is_finite()), "{format:?}"); + } +} + +/// A sink that fails once `room` bytes are written. +struct Full { + inner: Cursor>, + room: usize, +} + +impl Write for Full { + fn write(&mut self, data: &[u8]) -> std::io::Result { + if self.inner.get_ref().len() + data.len() > self.room { + return Err(std::io::Error::other("disk full")); + } + self.inner.write(data) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl Seek for Full { + fn seek(&mut self, pos: SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } +} + +/// After a failed write the encoder is unusable: later writes and `finish` fail too. +#[test] +fn a_failed_write_ends_the_encoder() { + let buf = tones(48_000, 2, 48_000); + for format in CODED { + let mut enc = FileEncoder::new(Full { inner: Cursor::new(Vec::new()), room: 2000 }, &EncodeOptions::new(format), 48_000, 2).unwrap(); + assert!(matches!(enc.write(&buf.channels, 48_000), Err(AudioError::Io(_))), "{format:?}"); + assert!(matches!(enc.write(&buf.channels, 1), Err(AudioError::Encode(_))), "{format:?}"); + assert!(matches!(enc.finish(), Err(AudioError::Encode(_))), "{format:?}"); + } +} + +#[test] +fn the_formats_are_named() { + assert_eq!(encode_format_for("m4a"), Some(EncodeFormat::Aac)); + assert_eq!(encode_format_for(".ALAC"), Some(EncodeFormat::Alac)); + assert_eq!(encode_format_for("mp3"), Some(EncodeFormat::Mp3)); + assert_eq!(encode_format_for("ac3"), Some(EncodeFormat::Ac3)); + assert_eq!(encode_format_for("eac3"), Some(EncodeFormat::Eac3)); + assert_eq!(encode_format_for("ec3"), Some(EncodeFormat::Eac3)); + for &format in EncodeFormat::ALL { + assert!(ENCODE_EXTENSIONS.contains(&format.extension()), "{format:?}"); + let named = encode_format_for(format.extension()).unwrap(); + assert_eq!((named.extension(), named.mime_type()), (format.extension(), format.mime_type())); + assert_eq!(format.is_lossy(), !matches!(format.codec(), CodecId::Pcm | CodecId::Flac | CodecId::Alac)); + } + for name in ENCODE_EXTENSIONS { + assert!(encode_format_for(name).is_some(), "{name}"); + } + assert_eq!(ENCODE_EXTENSIONS.len(), 13); + for format in CODED { + assert!(EncodeFormat::ALL.contains(&format) && format.is_built()); + } + let features: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.feature()).collect(); + assert_eq!( + features, + ["pcm-encode", "pcm-encode", "flac-encode", "alac-encode", "aac-encode", "mp3-encode", "ac3-encode", "eac3-encode", "vorbis-encode"] + ); +} + +/// ffmpeg's decode of `file` as interleaved `f32`, split into `channels` channels. +fn ffmpeg_decode(ff: &std::path::Path, file: &[u8], name: &str, channels: usize) -> Vec> { + let path = crate::testkit::fixtures_dir("file_formats").join(name); + std::fs::write(&path, file).unwrap(); + let out = Command::new(ff).args(["-v", "error", "-i"]).arg(&path).args(["-f", "f32le", "-"]).output().unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "{name}: {}", String::from_utf8_lossy(&out.stderr)); + let mut planar = vec![Vec::new(); channels]; + for (i, s) in out.stdout.as_chunks::<4>().0.iter().enumerate() { + planar[i % channels].push(f32::from_le_bytes(*s)); + } + planar +} + +/// ffmpeg reads every format: the M4A files without their priming (it applies the edit list) and, +/// from ffmpeg 9, at the length written; ALAC exactly; the raw streams behind their delay. +#[test] +fn ffmpeg_reads_the_files() { + let ff = require_ffmpeg!(); + for (channels, layout) in [(1, None), (2, None), (6, None), (8, Some(ChannelLayout::from_mask(0xFF)))] { + let buf = tones(48_000, channels, 20_000); + let mut opts = EncodeOptions::new(EncodeFormat::Aac); + opts.layout = layout; + let out = ffmpeg_decode(&ff, &encode(&buf, &opts).unwrap(), &format!("aac_{channels}.m4a"), channels); + // The priming is skipped by every ffmpeg (the channels below line up). The padding of the + // last packet is cut by ffmpeg 9; ffmpeg 8 plays it, to the end of the 20th packet. + assert!([20_000, 20_480].contains(&out[0].len()), "AAC, {channels} channels: {} frames", out[0].len()); + if channels <= 6 { + // ffmpeg also returns 5.1 in WAV order. + for (c, (want, got)) in buf.channels.iter().zip(&out).enumerate() { + assert!(snr(want, got) > 20.0, "AAC, {channels} channels, channel {c}: {} dB", snr(want, got)); + } + } + let opts = opts.with_format(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16); + let opts = if channels == 6 { opts.with_layout(ChannelLayout::SURROUND_5_1) } else { opts }; + let out = ffmpeg_decode(&ff, &encode(&buf, &opts).unwrap(), &format!("alac_{channels}.m4a"), channels); + assert!(out == buf.channels, "ALAC, {channels} channels"); + } + let buf = tones(44_100, 2, 20_000); + for (format, delay, floor) in + [(EncodeFormat::Mp3, craft_audio::mp3::DELAY as usize, 25.0), (EncodeFormat::Ac3, 256, 15.0), (EncodeFormat::Eac3, 256, 15.0)] + { + let name = format!("stream.{}", format.extension()); + let out = ffmpeg_decode(&ff, &encode(&buf, &EncodeOptions::new(format)).unwrap(), &name, 2); + for (want, got) in buf.channels.iter().zip(&out) { + assert!( + got.len() >= 20_000 + delay && snr(want, &got[delay..]) > floor, + "{format:?}: {} frames, {} dB", + got.len(), + snr(want, &got[delay..]) + ); + } + } + // E-AC-3 7.1: the front channels, which the 5.1 downmix leaves as they are. + let buf = tones(48_000, 8, 20_000); + let out = ffmpeg_decode(&ff, &encode(&buf, &EncodeOptions::new(EncodeFormat::Eac3)).unwrap(), "stream_7_1.eac3", 8); + assert!(out[7].len() >= 20_256); + for c in 0..3 { + assert!(snr(&buf.channels[c], &out[c][256..]) > 12.0, "E-AC-3 7.1, channel {c}: {} dB", snr(&buf.channels[c], &out[c][256..])); + } +} + +/// Apple's decoder (macOS `afinfo`; skipped elsewhere) takes the priming and the length of an AAC +/// file from the edit list, which it does only for a track with a `roll` sample group. +#[test] +fn apple_reads_the_aac_priming_and_length() { + let Some(afinfo) = crate::testkit::oracle::find_tool("afinfo") else { return }; + for (frames, remainder) in [(20_000, 480), (1, 1023), (4096, 0)] { + let path = crate::testkit::fixtures_dir("file_formats").join(format!("apple_{frames}.m4a")); + std::fs::write(&path, encode(&tones(48_000, 2, frames), &EncodeOptions::new(EncodeFormat::Aac)).unwrap()).unwrap(); + let out = Command::new(&afinfo).arg(&path).output().unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + assert!(text.contains(&format!("{frames} valid frames + 1024 priming + {remainder} remainder")), "{frames} frames: {text}"); + } +} + +/// What `EncodeFormat` says a format takes is what the writer accepts: for every format, a file +/// can be begun exactly when the sample rate, the channel count and the layout are listed. +#[test] +fn the_format_queries_agree_with_the_writer() { + // Every rate a format lists, each with its neighbours, and some that none lists. + let mut rates: Vec = EncodeFormat::ALL.iter().filter_map(|f| f.sample_rates()).flatten().flat_map(|&r| [r - 1, r, r + 1]).collect(); + rates.extend([44_000, 176_400, 192_000]); + rates.sort_unstable(); + rates.dedup(); + let masks = [ + 0x4, 0x1, 0x3, 0xC, 0x600, 0x7, 0xB, 0x103, 0x33, 0x107, 0x603, 0xF, 0x10B, 0x37, 0x607, 0x10F, 0x60B, 0x3F, 0x60F, 0x13F, 0x70F, 0x63F, 0xFF, + ]; + let layouts = masks.iter().map(|&mask| ChannelLayout::from_mask(mask)).chain((1..=9).map(ChannelLayout::unordered)); + for layout in layouts { + for &format in EncodeFormat::ALL { + // Vorbis is whole-buffer-only; its direct/generic API and options are tested separately. + if format == EncodeFormat::Ogg { + continue; + } + // 24 bits is a depth every format has. + let opts = EncodeOptions::new(format).with_layout(layout); + for &sample_rate in &rates { + let listed = format.sample_rates().is_none_or(|r| r.contains(&sample_rate)) + && layout.channels() <= format.max_channels() + && format.supports_layout(&layout); + let checked = opts.check(sample_rate, layout.channels()); + assert_eq!(checked.is_ok(), listed, "{format:?}, {sample_rate} Hz, {layout:?}: {checked:?}"); + let begun = FileEncoder::new(Cursor::new(Vec::new()), &opts, sample_rate, layout.channels()); + assert_eq!(begun.is_ok(), listed, "{format:?}, {sample_rate} Hz, {layout:?}"); + } + if let Some(fixed) = format.fixed_layouts(layout.channels()) { + assert!(fixed.iter().all(|l| format.supports_layout(l) && l.channels() == layout.channels())); + assert_eq!(format.supports_layout(&layout), fixed.iter().any(|l| same_speakers(l, &layout)), "{format:?}, {layout:?}"); + } + } + } + for &format in EncodeFormat::ALL { + assert!(!format.supports_layout(&ChannelLayout::unordered(0))); + assert_eq!(format.supports_quality(), EncodeOptions::new(format).with_quality(0.5).check(48_000, 2).is_ok() && format.is_lossy()); + assert_eq!(format.fixed_layouts(2).is_none(), matches!(format, EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac)); + } + // The most channels is the most: one more is refused, by the layouts of a format that has + // a fixed set and by the writer of one that has not. + let most: Vec = EncodeFormat::ALL.iter().map(|f| f.max_channels()).collect(); + assert_eq!(most, [32_767, 32_767, 8, 8, 8, 2, 6, 8, 2]); + for &format in EncodeFormat::ALL { + let most = format.max_channels(); + match format.fixed_layouts(most) { + Some(layouts) => assert!(!layouts.is_empty() && format.fixed_layouts(most + 1).unwrap().is_empty(), "{format:?}"), + None => { + let opts = EncodeOptions::new(format).with_bit_depth(BitDepth::Int16); + assert!(opts.check(48_000, most).is_ok() && opts.check(48_000, most + 1).is_err(), "{format:?}"); + assert!(format.supports_layout(&ChannelLayout::unordered(most)) && !format.supports_layout(&ChannelLayout::unordered(most + 1))); + } + } + } + assert_eq!(EncodeFormat::Ac3.fixed_layouts(3).unwrap().len(), 3); + assert!(EncodeFormat::Aac.fixed_layouts(9).unwrap().is_empty()); +} + +/// Whether two layouts name the same speakers, a surround pair being either sides or backs. +fn same_speakers(a: &ChannelLayout, b: &ChannelLayout) -> bool { + let one_pair = |mask: u32| if mask & 0x630 == 0x30 { mask & !0x30 | 0x600 } else { mask }; + matches!((a.mask(), b.mask()), (Some(a), Some(b)) if one_pair(a) == one_pair(b)) +} + +/// `bitrate` is the rate the file is written at, for the options and for the encoder they give. +#[test] +fn the_bit_rate_used_can_be_asked_for() { + let rate = |opts: EncodeOptions, sample_rate, channels| { + let asked = opts.bitrate(sample_rate, channels).unwrap(); + assert_eq!(FileEncoder::new(Cursor::new(Vec::new()), &opts, sample_rate, channels).unwrap().bitrate(), asked); + asked + }; + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Mp3), 48_000, 2), Some(192_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(130_000), 48_000, 2), Some(128_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(u32::MAX), 22_050, 1), Some(160_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Ac3).with_bitrate(191_999), 48_000, 2), Some(160_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Ac3), 48_000, 6), Some(448_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Eac3).with_bitrate(100_999), 48_000, 2), Some(100_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Aac), 48_000, 2), Some(128_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128), 48_000, 2), Some(24_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Aac).with_bitrate(u32::MAX), 8000, 1), Some(48_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Aac).with_quality(0.5), 48_000, 2), None); + for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac, EncodeFormat::Alac] { + assert_eq!(rate(EncodeOptions::new(format).with_bitrate(96_000), 48_000, 2), None, "{format:?}"); + } + // The size of a second of MP3 is the rate reported. + let buf = tones(48_000, 2, 48_000); + let opts = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(130_000); + assert_eq!(encode(&buf, &opts).unwrap().len() as u32, 43 * 1152 / 8 * opts.bitrate(48_000, 2).unwrap().unwrap() / 48_000); + assert!(is_unsupported(EncodeOptions::new(EncodeFormat::Mp3).bitrate(48_000, 6))); +} + +#[test] +fn vorbis_is_whole_buffer_only_and_validates_layouts() { + let opts = EncodeOptions::new(EncodeFormat::Ogg).with_layout(ChannelLayout::STEREO); + assert!(opts.check(48_000, 2).is_ok()); + assert_eq!(opts.bitrate(48_000, 2).unwrap(), None); + assert!(FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, 2).is_err()); + let buf = craft_audio::AudioBuffer::new(48_000, 2, 512); + assert!(craft_audio::encode(&buf, &opts).unwrap().starts_with(b"OggS")); + let wrong = opts.with_layout(ChannelLayout::from_mask(0xC)); + assert!(wrong.check(48_000, 2).is_err()); + assert!(craft_audio::encode(&buf, &wrong).is_err()); +} diff --git a/crates/audio/tests/codecs/main.rs b/crates/audio/tests/codecs/main.rs index 5db6af4b0..c1c9e2131 100644 --- a/crates/audio/tests/codecs/main.rs +++ b/crates/audio/tests/codecs/main.rs @@ -1,5 +1,5 @@ -//! Tests of the codecs ported from FilmCraft, built as one test binary: each file is a module, as -//! in their original crates. +//! Tests of the codecs ported from FilmCraft and EffectCraft, built as one test binary: each file +//! is a module, as in their original crates. // Index loops follow the specifications, as in FilmCraft (which allows this lint workspace-wide). #![allow(clippy::needless_range_loop)] @@ -12,9 +12,11 @@ mod ac3_encoder_oracle; mod ac3_oracle; mod alac; mod concealment; +mod file_formats; mod mp3_decoder_oracle; mod mp3_encoder_oracle; mod mpa_oracle; mod opus; +mod opusenc; mod routing_oracle; mod track_decoder; diff --git a/crates/audio/tests/codecs/opusenc/common.rs b/crates/audio/tests/codecs/opusenc/common.rs new file mode 100644 index 000000000..571c9826c --- /dev/null +++ b/crates/audio/tests/codecs/opusenc/common.rs @@ -0,0 +1,286 @@ +//! Shared helpers for the SILK/hybrid round-trip tests: synthetic signals, encoding, decoding +//! with FilmCraft's spec-derived decoder, delay-searched SNR and an Ogg Opus writer for ffmpeg. +#![allow(dead_code)] + +use craft_audio::opus::encoder::OpusEncoder; + +pub const SR: f64 = 48_000.0; +pub const FRAME: usize = OpusEncoder::FRAME_SIZE; + +/// Two-pole resonator state. +struct Reson { + y1: f64, + y2: f64, +} + +impl Reson { + fn run(&mut self, x: f64, f: f64, bw: f64) -> f64 { + let r = (-std::f64::consts::PI * bw / SR).exp(); + let a1 = 2.0 * r * (2.0 * std::f64::consts::PI * f / SR).cos(); + let a2 = -r * r; + let g = 1.0 - r; + let y = g * x + a1 * self.y1 + a2 * self.y2; + self.y2 = self.y1; + self.y1 = y; + y + } +} + +/// Speech-like test signal: a glottal pulse train (100–200 Hz, gliding pitch) through three +/// formant resonators whose frequencies change per syllable, with syllable envelopes, short +/// pauses and a little aspiration noise. +pub fn speech(len: usize, seed: u32) -> Vec { + let vowels: [[f64; 3]; 5] = + [[730.0, 1090.0, 2440.0], [270.0, 2290.0, 3010.0], [530.0, 1840.0, 2480.0], [570.0, 840.0, 2410.0], [300.0, 870.0, 2240.0]]; + let syl = (0.24 * SR) as usize; + let mut out = Vec::with_capacity(len); + let mut res = [Reson { y1: 0.0, y2: 0.0 }, Reson { y1: 0.0, y2: 0.0 }, Reson { y1: 0.0, y2: 0.0 }]; + let mut phase = 0.0f64; + let mut s = seed; + let mut prev_glottal = 0.0; + for n in 0..len { + let t = n as f64 / SR; + let k = n / syl; + let pos = (n % syl) as f64 / syl as f64; + // Every fourth syllable is a pause. + let pause = k % 4 == 3; + let env = if pause { 0.0 } else { (std::f64::consts::PI * pos).sin().powf(0.7) }; + let f0 = 100.0 + 50.0 * (1.0 + (2.0 * std::f64::consts::PI * 0.9 * t).sin()) + 15.0 * ((k * 7) % 5) as f64 - 30.0 * pos; + phase += f0 / SR; + if phase >= 1.0 { + phase -= 1.0; + } + // Rosenberg-like glottal flow; its derivative excites the vocal tract. + let g = if phase < 0.4 { + 0.5 * (1.0 - (std::f64::consts::PI * phase / 0.4).cos()) + } else if phase < 0.56 { + (std::f64::consts::FRAC_PI_2 * (phase - 0.4) / 0.16).cos() + } else { + 0.0 + }; + let dg = (g - prev_glottal) * 40.0; + prev_glottal = g; + s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let noise = ((s >> 8) as f64 / (1u32 << 24) as f64 - 0.5) * 0.02; + let v = vowels[(k * 3 + 1) % 5]; + let w = vowels[(k * 3 + 4) % 5]; + let mix = pos; + let mut x = dg + noise; + let mut y = 0.0; + for (i, r) in res.iter_mut().enumerate() { + let f = v[i] * (1.0 - mix) + w[i] * mix; + y += r.run(x, f, 60.0 + 40.0 * i as f64) * [1.0, 0.6, 0.3][i]; + } + x = y * env * 1.2; + out.push(x as f32); + } + let peak = out.iter().fold(0f32, |m, v| m.max(v.abs())); + let g = 0.5 / peak.max(1e-9); + out.iter().map(|v| v * g).collect() +} + +/// Music-like test signal: three-note chords of harmonic tones (six partials each), changing +/// every half second with soft attacks and releases. +pub fn music(len: usize) -> Vec { + let chords: [[f64; 3]; 4] = [[261.63, 329.63, 392.0], [220.0, 277.18, 329.63], [174.61, 220.0, 261.63], [196.0, 246.94, 293.66]]; + let seg = (0.5 * SR) as usize; + (0..len) + .map(|n| { + let t = n as f64 / SR; + let k = n / seg; + let pos = (n % seg) as f64 / seg as f64; + let env = (pos * 20.0).min(1.0) * ((1.0 - pos) * 10.0).min(1.0); + let mut x = 0.0; + for (j, &f) in chords[k % 4].iter().enumerate() { + for h in 1..=6 { + x += (2.0 * std::f64::consts::PI * f * h as f64 * t + j as f64).sin() / h as f64; + } + } + (0.12 * env * x) as f32 + }) + .collect() +} + +pub fn interleave(planar: &[Vec]) -> Vec { + let c = planar.len(); + let len = planar[0].len(); + let mut pcm = vec![0f32; len * c]; + for (ch, p) in planar.iter().enumerate() { + for (i, &v) in p.iter().enumerate() { + pcm[i * c + ch] = v; + } + } + pcm +} + +/// Encodes planar input (padding the tail so the encoder delay is flushed). +pub fn encode(mut enc: OpusEncoder, planar: &[Vec]) -> (OpusEncoder, Vec>) { + let c = planar.len(); + let len = planar[0].len(); + let total = len + enc.pre_skip() as usize + 16; + let frames = total.div_ceil(FRAME); + let mut pcm = interleave(planar); + pcm.resize(frames * FRAME * c, 0.0); + let packets = pcm.chunks(FRAME * c).map(|f| enc.encode_float(f).unwrap()).collect(); + (enc, packets) +} + +/// Decodes with filmcraft-opus, drops the pre-skip and returns planar channels (full length). +pub fn decode(head: &[u8], packets: &[Vec]) -> Vec> { + let mut dec = craft_audio::opus::Decoder::new(head).expect("OpusHead"); + dec.set_trim_pre_skip(true); + let mut out: Vec> = vec![Vec::new(); dec.channels()]; + for p in packets { + let planes = dec.decode(Some(p)).expect("decode"); + for (o, p) in out.iter_mut().zip(planes) { + o.extend_from_slice(&p); + } + } + out +} + +/// Waveform SNR (dB) of `dec[i + shift]` against `orig[i]`, excluding the first and last 20 ms. +pub fn snr_at(orig: &[f32], dec: &[f32], shift: isize) -> f64 { + let (mut s, mut e) = (0f64, 0f64); + for i in FRAME..orig.len() - FRAME { + let j = i as isize + shift; + let d = if j >= 0 && (j as usize) < dec.len() { dec[j as usize] as f64 } else { 0.0 }; + s += (orig[i] as f64).powi(2); + e += (orig[i] as f64 - d).powi(2); + } + 10.0 * (s / e.max(1e-30)).log10() +} + +/// Best SNR over residual delays of ±`range` samples: (SNR dB, delay). +pub fn snr_search(orig: &[f32], dec: &[f32], range: isize) -> (f64, isize) { + (-range..=range).map(|d| (snr_at(orig, dec, d), d)).fold((f64::MIN, 0), |a, b| if b.0 > a.0 { b } else { a }) +} + +/// Segmental SNR (dB): mean over 20 ms segments holding signal (each clamped to [-10, 40]). +pub fn seg_snr(orig: &[f32], dec: &[f32], shift: isize) -> f64 { + let mut acc = 0f64; + let mut n = 0; + let mut i = FRAME; + while i + FRAME <= orig.len() - FRAME { + let (mut s, mut e) = (0f64, 0f64); + for k in i..i + FRAME { + let j = k as isize + shift; + let d = if j >= 0 && (j as usize) < dec.len() { dec[j as usize] as f64 } else { 0.0 }; + s += (orig[k] as f64).powi(2); + e += (orig[k] as f64 - d).powi(2); + } + if s / FRAME as f64 > 1e-5 { + acc += (10.0 * (s / e.max(1e-30)).log10()).clamp(-10.0, 40.0); + n += 1; + } + i += FRAME; + } + acc / n.max(1) as f64 +} + +/// Average bitrate (bits per second) of a packet sequence of 20 ms packets. +pub fn bitrate(packets: &[Vec]) -> f64 { + packets.iter().map(|p| p.len() * 8).sum::() as f64 / (packets.len() as f64 * 0.02) +} + +/// Low-pass filtered copy (FFT brick wall) used to compare band-limited modes fairly. +pub fn lowpass(x: &[f32], fc: f64) -> Vec { + let n = x.len().next_power_of_two(); + let mut re: Vec = x.iter().map(|&v| v as f64).collect(); + re.resize(n, 0.0); + let mut im = vec![0f64; n]; + fft(&mut re, &mut im, false); + for k in 0..n { + let f = (k.min(n - k)) as f64 * SR / n as f64; + if f > fc { + re[k] = 0.0; + im[k] = 0.0; + } + } + fft(&mut re, &mut im, true); + re[..x.len()].iter().map(|&v| (v / n as f64) as f32).collect() +} + +pub fn fft(re: &mut [f64], im: &mut [f64], inverse: bool) { + let n = re.len(); + let mut j = 0; + for i in 1..n { + let mut bit = n >> 1; + while j & bit != 0 { + j ^= bit; + bit >>= 1; + } + j |= bit; + if i < j { + re.swap(i, j); + im.swap(i, j); + } + } + let mut len = 2; + while len <= n { + let ang = if inverse { 2.0 } else { -2.0 } * std::f64::consts::PI / len as f64; + for s in (0..n).step_by(len) { + for k in 0..len / 2 { + let (wr, wi) = ((ang * k as f64).cos(), (ang * k as f64).sin()); + let (a, b) = (s + k, s + k + len / 2); + let tr = re[b] * wr - im[b] * wi; + let ti = re[b] * wi + im[b] * wr; + re[b] = re[a] - tr; + im[b] = im[a] - ti; + re[a] += tr; + im[a] += ti; + } + } + len <<= 1; + } +} + +// ---- Ogg Opus (RFC 3533 + RFC 7845) for the ffmpeg oracle ---- + +fn ogg_crc(data: &[u8]) -> u32 { + let mut crc = 0u32; + for &b in data { + crc ^= (b as u32) << 24; + for _ in 0..8 { + crc = if crc & 0x8000_0000 != 0 { (crc << 1) ^ 0x04C1_1DB7 } else { crc << 1 }; + } + } + crc +} + +fn ogg_page(out: &mut Vec, packet: &[u8], header_type: u8, granule: u64, seq: u32) { + let mut lacing = vec![255u8; packet.len() / 255]; + lacing.push((packet.len() % 255) as u8); + let start = out.len(); + out.extend_from_slice(b"OggS"); + out.push(0); + out.push(header_type); + out.extend_from_slice(&granule.to_le_bytes()); + out.extend_from_slice(&0x4543_4F50u32.to_le_bytes()); + out.extend_from_slice(&seq.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.push(lacing.len() as u8); + out.extend_from_slice(&lacing); + out.extend_from_slice(packet); + let crc = ogg_crc(&out[start..]); + out[start + 22..start + 26].copy_from_slice(&crc.to_le_bytes()); +} + +/// An Ogg Opus file holding `packets` for `len` samples of audio. +pub fn ogg_opus(enc: &OpusEncoder, packets: &[Vec], len: usize) -> Vec { + let mut out = Vec::new(); + ogg_page(&mut out, &enc.opus_head(), 0x02, 0, 0); + let vendor = b"effectcraft-opusenc"; + let mut tags = b"OpusTags".to_vec(); + tags.extend_from_slice(&(vendor.len() as u32).to_le_bytes()); + tags.extend_from_slice(vendor); + tags.extend_from_slice(&0u32.to_le_bytes()); + ogg_page(&mut out, &tags, 0, 0, 1); + let pre_skip = enc.pre_skip() as u64; + for (i, p) in packets.iter().enumerate() { + let last = i + 1 == packets.len(); + let granule = if last { pre_skip + len as u64 } else { ((i + 1) * FRAME) as u64 }; + ogg_page(&mut out, p, if last { 0x04 } else { 0 }, granule, i as u32 + 2); + } + out +} diff --git a/crates/audio/tests/codecs/opusenc/ffmpeg.rs b/crates/audio/tests/codecs/opusenc/ffmpeg.rs new file mode 100644 index 000000000..41965be20 --- /dev/null +++ b/crates/audio/tests/codecs/opusenc/ffmpeg.rs @@ -0,0 +1,83 @@ +//! ffmpeg as a second, external oracle: every mode/bandwidth written as Ogg Opus must decode +//! without errors with both ffmpeg's native `opus` decoder and `libopus`, honour the pre-skip +//! and end granule, and reproduce the input. Skipped when ffmpeg is not installed. + +use super::common; + +use std::process::Command; + +use common::*; +use craft_audio::opus::encoder::{Bandwidth, Mode, OpusEncoder}; + +/// ffmpeg, found and skipped by craft-media's oracle rules (EffectCraft looked in Homebrew's +/// directory, then `PATH`). +fn ffmpeg() -> Option { + crate::testkit::ffmpeg_or_skip("opus encoder ffmpeg oracle") +} + +/// Decodes an Ogg Opus file with ffmpeg's decoder `codec`; returns interleaved f32 output. +fn ffmpeg_decode(exe: &std::path::Path, codec: &str, file: &[u8], channels: usize, tag: &str) -> Option> { + let has = match Command::new(exe).args(["-hide_banner", "-decoders"]).output() { + Ok(out) => out, + Err(e) => return crate::common::skip(&format!("ffmpeg -decoders failed: {e}")), + }; + if !String::from_utf8_lossy(&has.stdout).lines().any(|l| l.split_whitespace().nth(1) == Some(codec)) { + return crate::common::skip(&format!("ffmpeg has no {codec} decoder")); + } + let path = std::env::temp_dir().join(format!("effectcraft-opusenc-{}-{tag}.opus", std::process::id())); + std::fs::write(&path, file).unwrap(); + let out = Command::new(exe) + .args(["-v", "error", "-c:a", codec, "-i"]) + .arg(&path) + .args(["-f", "f32le", "-ac", &channels.to_string(), "-ar", "48000", "-"]) + .output() + .expect("run ffmpeg"); + let _ = std::fs::remove_file(&path); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "ffmpeg ({codec}) failed: {stderr}"); + // ffmpeg's native decoder also makes its raw-PCM muxer print a timestamp complaint for + // narrowband SILK streams written by libopus itself; that line is about ffmpeg's own + // timestamping, not the bitstream, so it is the one message tolerated. + let errors: Vec<&str> = stderr.lines().filter(|l| !l.trim().is_empty() && !l.contains("non monotonically increasing dts to muxer")).collect(); + assert!(errors.is_empty(), "ffmpeg ({codec}) reported errors: {errors:?}"); + Some(out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()) +} + +#[test] +fn ffmpeg_decodes_every_mode() { + let Some(exe) = ffmpeg() else { + eprintln!("ffmpeg not installed; skipping the oracle test"); + return; + }; + let len = 48_000; + let sp = speech(len + 30_000, 3); + let left = sp[..len].to_vec(); + let right: Vec = sp[30_000..].iter().map(|v| v * 0.7).collect(); + let cases = [ + (1usize, Mode::Silk, Bandwidth::Narrowband, 8_000u32, 3_400.0, 8.0), + (1, Mode::Silk, Bandwidth::Mediumband, 11_000, 5_000.0, 10.0), + (1, Mode::Silk, Bandwidth::Wideband, 16_000, 7_000.0, 12.0), + (2, Mode::Silk, Bandwidth::Wideband, 32_000, 7_000.0, 12.0), + (1, Mode::Hybrid, Bandwidth::SuperWideband, 24_000, 24_000.0, 10.0), + (1, Mode::Hybrid, Bandwidth::Fullband, 32_000, 24_000.0, 10.0), + (2, Mode::Hybrid, Bandwidth::Fullband, 64_000, 24_000.0, 10.0), + (2, Mode::Celt, Bandwidth::Fullband, 96_000, 24_000.0, 10.0), + ]; + for (c, mode, bw, rate, fc, min_snr) in cases { + let planar: Vec> = if c == 1 { vec![left.clone()] } else { vec![left.clone(), right.clone()] }; + let (enc, packets) = encode(OpusEncoder::with_mode(c as u8, rate, mode, bw).unwrap(), &planar); + let file = ogg_opus(&enc, &packets, len); + for codec in ["opus", "libopus"] { + let Some(dec) = ffmpeg_decode(&exe, codec, &file, c, &format!("{mode:?}{bw:?}{c}{codec}")) else { + continue; + }; + assert_eq!(dec.len(), len * c, "{codec}: pre-skip and end granule must be honoured"); + for (ch, x) in planar.iter().enumerate() { + let d: Vec = (0..len).map(|i| dec[i * c + ch]).collect(); + let (snr, delay) = snr_search(&lowpass(x, fc), &d, 6); + eprintln!("ffmpeg {codec:7} {mode:?}/{bw:?} {c} ch @ {} kb/s, channel {ch}: SNR {snr:.1} dB (residual delay {delay})", rate / 1000); + assert!(snr > min_snr, "{codec} {mode:?}/{bw:?}: SNR {snr:.1} dB"); + } + } + } +} diff --git a/crates/audio/tests/codecs/opusenc/mod.rs b/crates/audio/tests/codecs/opusenc/mod.rs new file mode 100644 index 000000000..f2a886463 --- /dev/null +++ b/crates/audio/tests/codecs/opusenc/mod.rs @@ -0,0 +1,5 @@ +//! EffectCraft's `effectcraft-opusenc` integration tests. + +mod common; +mod ffmpeg; +mod modes; diff --git a/crates/audio/tests/codecs/opusenc/modes.rs b/crates/audio/tests/codecs/opusenc/modes.rs new file mode 100644 index 000000000..263858560 --- /dev/null +++ b/crates/audio/tests/codecs/opusenc/modes.rs @@ -0,0 +1,292 @@ +//! SILK, hybrid and CELT round trips through FilmCraft's spec-derived Opus decoder: every +//! mode/bandwidth decodes, waveform quality on speech-like and music-like signals, bitrate +//! tracking, stereo, the application tables and delay alignment. + +use super::common; + +use common::*; +use craft_audio::opus::encoder::{Application, Bandwidth, Error, Mode, OpusEncoder}; + +struct Run { + snr: f64, + seg: f64, + delay: isize, + kbps: f64, + packets: Vec>, +} + +/// Encodes `planar`, decodes, and measures each channel against `reference` (searching a +/// residual delay of up to ±6 samples). +fn run(enc: OpusEncoder, planar: &[Vec], reference: &[Vec]) -> Vec { + let (enc, packets) = encode(enc, planar); + let dec = decode(&enc.opus_head(), &packets); + let kbps = bitrate(&packets) / 1000.0; + reference + .iter() + .zip(&dec) + .map(|(r, d)| { + assert!(d.len() >= r.len(), "decoded {} < {}", d.len(), r.len()); + assert!(d.iter().all(|v| v.is_finite())); + let (snr, delay) = snr_search(r, d, 6); + Run { snr, seg: seg_snr(r, d, delay), delay, kbps, packets: packets.clone() } + }) + .collect() +} + +fn mono(mode: Mode, bw: Bandwidth, rate: u32, x: &[f32], fc: f64) -> Run { + let reference = if fc < 20_000.0 { lowpass(x, fc) } else { x.to_vec() }; + run(OpusEncoder::with_mode(1, rate, mode, bw).unwrap(), &[x.to_vec()], &[reference]).remove(0) +} + +/// Upper edge of the band a SILK bandwidth keeps (for band-limited references). +fn band_edge(bw: Bandwidth) -> f64 { + match bw { + Bandwidth::Narrowband => 3_400.0, + Bandwidth::Mediumband => 5_000.0, + Bandwidth::Wideband => 7_000.0, + _ => 24_000.0, + } +} + +const LEN: usize = 96_000; + +#[test] +fn every_mode_and_bandwidth_decodes() { + let sp = speech(LEN + 40_000, 11); + let left = sp[..LEN].to_vec(); + let right: Vec = sp[40_000..].iter().map(|v| v * 0.6).collect(); + for (mode, bw, config, rate) in [ + (Mode::Silk, Bandwidth::Narrowband, 1u8, 8_000u32), + (Mode::Silk, Bandwidth::Mediumband, 5, 11_000), + (Mode::Silk, Bandwidth::Wideband, 9, 16_000), + (Mode::Hybrid, Bandwidth::SuperWideband, 13, 24_000), + (Mode::Hybrid, Bandwidth::Fullband, 15, 32_000), + (Mode::Celt, Bandwidth::Fullband, 31, 64_000), + ] { + for c in [1usize, 2] { + let planar = if c == 1 { vec![left.clone()] } else { vec![left.clone(), right.clone()] }; + let reference: Vec> = planar.iter().map(|x| lowpass(x, band_edge(bw))).collect(); + let enc = OpusEncoder::with_mode(c as u8, rate * c as u32, mode, bw).unwrap(); + assert_eq!((enc.mode(), enc.bandwidth()), (mode, bw)); + let res = run(enc, &planar, &reference); + for p in &res[0].packets { + assert_eq!(p[0], (config << 3) | if c == 2 { 4 } else { 0 }, "TOC of {mode:?}/{bw:?}"); + assert!(p.len() >= 3 && p.len() <= 1276); + } + for (ch, r) in res.iter().enumerate() { + eprintln!( + "{mode:?}/{bw:?} {c} ch @ {} kb/s: {:.1} kb/s, channel {ch} SNR {:.1} dB, segSNR {:.1} dB, residual delay {}", + rate * c as u32 / 1000, + r.kbps, + r.snr, + r.seg, + r.delay + ); + assert!(r.snr > 8.0, "{mode:?}/{bw:?} {c} ch channel {ch}: SNR {:.1} dB", r.snr); + assert!(r.delay.abs() <= 1, "{mode:?}/{bw:?}: residual delay {} (pre-skip mismatch)", r.delay); + } + } + } +} + +#[test] +fn silk_speech_quality() { + let x = speech(LEN, 7); + for (bw, rate, min_snr) in [ + (Bandwidth::Narrowband, 8_000u32, 10.0), + (Bandwidth::Mediumband, 11_000, 14.0), + (Bandwidth::Wideband, 12_000, 14.0), + (Bandwidth::Wideband, 16_000, 18.0), + (Bandwidth::Wideband, 24_000, 24.0), + ] { + let r = mono(Mode::Silk, bw, rate, &x, band_edge(bw)); + eprintln!("SILK {bw:?} speech @ {} kb/s: {:.1} kb/s, SNR {:.1} dB, segSNR {:.1} dB", rate / 1000, r.kbps, r.snr, r.seg); + assert!(r.snr > min_snr && r.seg > min_snr - 3.0, "SILK {bw:?} @ {rate}: SNR {:.1} / seg {:.1}", r.snr, r.seg); + } +} + +#[test] +fn silk_beats_celt_on_speech_at_low_rate() { + let x = speech(LEN, 5); + // Both measured against the full-band input. + let silk = mono(Mode::Silk, Bandwidth::Wideband, 12_000, &x, 24_000.0); + let celt = mono(Mode::Celt, Bandwidth::Fullband, 12_000, &x, 24_000.0); + eprintln!( + "12 kb/s mono speech: SILK WB {:.1} dB (seg {:.1}) at {:.1} kb/s vs CELT {:.1} dB (seg {:.1}) at {:.1} kb/s", + silk.snr, silk.seg, silk.kbps, celt.snr, celt.seg, celt.kbps + ); + assert!(silk.snr > celt.snr + 3.0, "SILK {:.1} dB vs CELT {:.1} dB", silk.snr, celt.snr); + assert!(silk.seg > celt.seg + 3.0, "SILK seg {:.1} dB vs CELT seg {:.1} dB", silk.seg, celt.seg); +} + +#[test] +fn hybrid_quality() { + let sp = speech(LEN, 9); + let mu = music(LEN); + for (name, x, bw, rate, min_snr) in [ + ("speech", &sp, Bandwidth::SuperWideband, 24_000u32, 18.0), + ("speech", &sp, Bandwidth::Fullband, 32_000, 20.0), + ("music", &mu, Bandwidth::SuperWideband, 24_000, 9.0), + ("music", &mu, Bandwidth::Fullband, 32_000, 10.0), + ] { + let r = mono(Mode::Hybrid, bw, rate, x, 24_000.0); + eprintln!("hybrid {bw:?} {name} @ {} kb/s: {:.1} kb/s, SNR {:.1} dB, segSNR {:.1} dB", rate / 1000, r.kbps, r.snr, r.seg); + assert!(r.snr > min_snr, "hybrid {bw:?} {name}: SNR {:.1} dB", r.snr); + // Constant packet size. + assert!(r.packets.iter().all(|p| p.len() == rate as usize / 400)); + } +} + +#[test] +fn silk_music_quality() { + let x = music(LEN); + for (rate, min_snr) in [(12_000u32, 5.0), (16_000, 8.0), (24_000, 13.0)] { + let r = mono(Mode::Silk, Bandwidth::Wideband, rate, &x, 7_000.0); + eprintln!("SILK WB music @ {} kb/s: {:.1} kb/s, SNR {:.1} dB", rate / 1000, r.kbps, r.snr); + assert!(r.snr > min_snr, "SILK music @ {rate}: SNR {:.1} dB", r.snr); + } +} + +#[test] +fn bitrate_tracking() { + let sp = speech(LEN, 13); + let mu = music(LEN); + for (name, x) in [("speech", &sp), ("music", &mu)] { + for (mode, bw, rate) in [ + (Mode::Silk, Bandwidth::Narrowband, 6_000u32), + (Mode::Silk, Bandwidth::Narrowband, 9_000), + (Mode::Silk, Bandwidth::Mediumband, 11_000), + (Mode::Silk, Bandwidth::Wideband, 12_000), + (Mode::Silk, Bandwidth::Wideband, 20_000), + (Mode::Silk, Bandwidth::Wideband, 32_000), + (Mode::Hybrid, Bandwidth::SuperWideband, 20_000), + (Mode::Hybrid, Bandwidth::Fullband, 36_000), + ] { + let r = mono(mode, bw, rate, x, band_edge(bw)); + let ratio = r.kbps * 1000.0 / rate as f64; + eprintln!( + "{name} {mode:?}/{bw:?} target {} kb/s: actual {:.2} kb/s ({:+.0} %), SNR {:.1} dB", + rate / 1000, + r.kbps, + (ratio - 1.0) * 100.0, + r.snr + ); + assert!((0.75..=1.25).contains(&ratio), "{name} {mode:?}/{bw:?} @ {rate}: {:.2} kb/s", r.kbps); + } + } +} + +#[test] +fn stereo_silk_and_hybrid() { + let sp = speech(LEN + 40_000, 21); + let a = sp[..LEN].to_vec(); + let b: Vec = sp[40_000..].iter().map(|v| v * 0.7).collect(); + let mu = music(LEN); + let cases: Vec<(&str, Vec, Vec)> = vec![ + ("dual mono", a.clone(), a.clone()), + ("panned", a.iter().map(|v| v * 0.9).collect(), a.iter().map(|v| v * 0.35).collect()), + ("independent", a.clone(), b), + ("speech+music", a.iter().zip(&mu).map(|(x, y)| 0.8 * x + 0.3 * y).collect(), a.iter().zip(&mu).map(|(x, y)| 0.3 * x + 0.8 * y).collect()), + ]; + for (name, l, r) in &cases { + for (mode, bw, rate, min_snr) in [(Mode::Silk, Bandwidth::Wideband, 32_000u32, 9.0), (Mode::Hybrid, Bandwidth::Fullband, 64_000, 9.0)] { + let fc = band_edge(bw); + let res = run(OpusEncoder::with_mode(2, rate, mode, bw).unwrap(), &[l.clone(), r.clone()], &[lowpass(l, fc), lowpass(r, fc)]); + eprintln!( + "stereo {name} {mode:?}/{bw:?} @ {} kb/s: {:.1} kb/s, L {:.1} dB, R {:.1} dB", + rate / 1000, + res[0].kbps, + res[0].snr, + res[1].snr + ); + assert!(res[0].snr > min_snr && res[1].snr > min_snr, "stereo {name} {mode:?}: L {:.1} R {:.1}", res[0].snr, res[1].snr); + } + } +} + +#[test] +fn application_tables_and_pre_skip() { + let cases = [ + (Application::Voip, 1u8, 8_000u32, Mode::Silk, Bandwidth::Narrowband), + (Application::Voip, 1, 11_000, Mode::Silk, Bandwidth::Mediumband), + (Application::Voip, 1, 16_000, Mode::Silk, Bandwidth::Wideband), + (Application::Voip, 1, 24_000, Mode::Hybrid, Bandwidth::SuperWideband), + (Application::Voip, 1, 32_000, Mode::Hybrid, Bandwidth::Fullband), + (Application::Voip, 1, 48_000, Mode::Celt, Bandwidth::Fullband), + (Application::Voip, 2, 32_000, Mode::Silk, Bandwidth::Wideband), + (Application::Audio, 1, 12_000, Mode::Silk, Bandwidth::Wideband), + (Application::Audio, 1, 24_000, Mode::Hybrid, Bandwidth::Fullband), + (Application::Audio, 2, 48_000, Mode::Hybrid, Bandwidth::Fullband), + (Application::Audio, 1, 64_000, Mode::Celt, Bandwidth::Fullband), + (Application::Audio, 2, 128_000, Mode::Celt, Bandwidth::Fullband), + ]; + for (app, c, rate, mode, bw) in cases { + let e = OpusEncoder::with_application(c, rate, app).unwrap(); + assert_eq!((e.mode(), e.bandwidth(), e.application()), (mode, bw, app), "{app:?} {c} ch @ {rate}"); + assert_eq!(e.pre_skip(), 120, "every mode is aligned to a 120-sample delay"); + } + assert_eq!(OpusEncoder::new(2, 128_000).unwrap().mode(), Mode::Celt); + assert_eq!(OpusEncoder::new(1, 12_000).unwrap().application(), Application::Audio); +} + +/// EffectCraft's encoder panicked here; craft-audio returns an error (never crash). +#[test] +fn invalid_mode_bandwidth_is_an_error() { + assert_eq!(OpusEncoder::with_mode(1, 16_000, Mode::Silk, Bandwidth::Fullband).err(), Some(Error::ModeBandwidth(Mode::Silk, Bandwidth::Fullband))); + assert_eq!(OpusEncoder::new(3, 128_000).err(), Some(Error::Channels(3))); + assert_eq!(OpusEncoder::new(0, 128_000).err(), Some(Error::Channels(0))); + // From 86 channels the per-channel minimum bitrate passes the 510 kb/s cap. + for channels in [86, u8::MAX] { + assert_eq!(OpusEncoder::new(channels, 128_000).err(), Some(Error::Channels(channels))); + let app = OpusEncoder::with_application(channels, 128_000, Application::Voip).err(); + assert_eq!(app, Some(Error::Channels(channels))); + } +} + +#[test] +fn extreme_inputs_stay_decodable() { + let len = 24_000; + let mut s = 1u32; + let noise: Vec = (0..len) + .map(|_| { + s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (s >> 8) as f32 / (1u32 << 23) as f32 - 1.0 + }) + .collect(); + let square: Vec = (0..len).map(|i| if (i / 60) % 2 == 0 { 0.999 } else { -0.999 }).collect(); + let clicks: Vec = (0..len).map(|i| if i % 4_801 == 0 { 1.0 } else { 0.0 }).collect(); + let dc = vec![0.7f32; len]; + let nan: Vec = (0..len).map(|i| if i % 1000 == 0 { f32::NAN } else { 0.1 * (i as f32 * 0.01).sin() }).collect(); + for (name, x) in [("noise", &noise), ("square", &square), ("clicks", &clicks), ("dc", &dc), ("nan", &nan)] { + for (mode, bw, rate) in + [(Mode::Silk, Bandwidth::Narrowband, 6_000u32), (Mode::Silk, Bandwidth::Wideband, 40_000), (Mode::Hybrid, Bandwidth::Fullband, 24_000)] + { + for c in [1usize, 2] { + let planar: Vec> = if c == 1 { vec![x.clone()] } else { vec![x.clone(), x.iter().map(|v| -0.5 * v).collect()] }; + 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!(dec.iter().all(|ch| ch.iter().all(|v| v.is_finite() && v.abs() <= 4.0)), "{name} {mode:?}/{bw:?} {c} ch: bad output"); + } + } + } +} + +#[test] +fn silk_and_hybrid_silence() { + for (mode, bw, rate) in [(Mode::Silk, Bandwidth::Wideband, 16_000u32), (Mode::Hybrid, Bandwidth::Fullband, 32_000)] { + let x = vec![0f32; 48_000]; + let (enc, packets) = encode(OpusEncoder::with_mode(1, rate, mode, bw).unwrap(), std::slice::from_ref(&x)); + let dec = decode(&enc.opus_head(), &packets); + let peak = dec[0].iter().fold(0f32, |m, v| m.max(v.abs())); + let kbps = bitrate(&packets) / 1000.0; + eprintln!("{mode:?} silence: {kbps:.2} kb/s, decoded peak {peak:.2e}"); + assert!(peak < 1e-3, "{mode:?} silence decodes to peak {peak}"); + if mode == Mode::Silk { + assert!(kbps < 4.0, "SILK silence costs {kbps:.2} kb/s"); + } + } +} diff --git a/crates/audio/tests/codecs/track_decoder.rs b/crates/audio/tests/codecs/track_decoder.rs index 0607db4ac..fee8f1f97 100644 --- a/crates/audio/tests/codecs/track_decoder.rs +++ b/crates/audio/tests/codecs/track_decoder.rs @@ -1,7 +1,8 @@ //! `TrackDecoder` on streams an app's own demuxer hands over without codec configuration: -//! ADTS-framed AAC (MPEG-TS). +//! ADTS-framed AAC (MPEG-TS) and Opus without an `OpusHead` (RTP). use craft_audio::aac::{Encoder as AacEncoder, EncoderConfig}; +use craft_audio::opus::Encoder as OpusEncoder; use craft_audio::{CodecId, CodecParams, TrackDecoder}; fn tone(n: usize) -> Vec { @@ -32,3 +33,20 @@ fn adts_aac_without_extradata() { let raw = &units[0][7..]; assert!(TrackDecoder::new(&CodecParams::new(CodecId::Aac), &[raw]).is_err()); } + +#[test] +fn opus_without_opus_head() { + let mut enc = OpusEncoder::new(1, 64_000).unwrap(); + let pcm = tone(OpusEncoder::FRAME_SIZE * 10); + let packets: Vec> = pcm.chunks(OpusEncoder::FRAME_SIZE).map(|f| enc.encode_float(f).unwrap()).collect(); + + let params = CodecParams::new(CodecId::Opus).with_channels(1).with_sample_rate(48_000); + let mut dec = TrackDecoder::new(¶ms, &[]).unwrap(); + assert_eq!((dec.sample_rate(), dec.channels()), (48_000, 1)); + for p in &packets { + assert_eq!(dec.decode(p).unwrap().frames(), OpusEncoder::FRAME_SIZE); + } + + // More than two channels need the mapping an OpusHead carries. + assert!(TrackDecoder::new(&CodecParams::new(CodecId::Opus).with_channels(6), &[]).is_err()); +} diff --git a/crates/ber/Cargo.toml b/crates/ber/Cargo.toml new file mode 100644 index 000000000..fa3902e88 --- /dev/null +++ b/crates/ber/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "craft-ber" +description = "ASN.1 BER and DER (X.690): reading TLVs, BER to DER, and what an opaque signed CMS holds" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true diff --git a/crates/ber/src/lib.rs b/crates/ber/src/lib.rs new file mode 100644 index 000000000..e97c1b0f5 --- /dev/null +++ b/crates/ber/src/lib.rs @@ -0,0 +1,432 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Reading the TLVs of ASN.1 BER and DER (X.690), and turning BER into DER where they differ in +//! what CMS writers use: indefinite lengths (which streaming signers write) and OCTET STRINGs in +//! pieces (constructed). What is DER already is kept byte for byte, an element with a definite +//! length inside an indefinite one too, so that the bytes a signature covers (signed attributes, +//! a certificate's body) are those the signer wrote. For S/MIME: `craft-smime` checks +//! signatures with it, and a message's reader takes out what an opaque signed one holds +//! ([`signed_content`]). +//! +//! The input is hostile: lengths are checked against what is there, nesting is bounded +//! ([`MAX_DEPTH`]), and the work is linear in the input (times the bounded depth). +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +/// CMS's id-signedData and id-data (RFC 5652 §5.1, §4), as OBJECT IDENTIFIER values. +const SIGNED_DATA: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02]; +const DATA: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01]; + +/// What the CMS `cms` holds when it is SignedData with its content inside, of type id-data: the +/// MIME entity an opaque signed message (`application/pkcs7-mime`, RFC 8551 §3.5) signed, for +/// reading as the message. Nothing is checked here (`craft-smime` checks it); `None` for any +/// other CMS (an Encrypted message's enveloped data) or bytes that aren't one. +pub fn signed_content(cms: &[u8]) -> Option> { + let der = to_der(cms)?; + let (info, rest) = read(&der)?; + if info.tag != 0x30 || !rest.is_empty() { + return None; + } + let info = children(info.value)?; + let [oid, explicit] = info.as_slice() else { return None }; + if oid.tag != 0x06 || oid.value != SIGNED_DATA || explicit.tag != 0xa0 { + return None; + } + let (signed, rest) = read(explicit.value)?; + if signed.tag != 0x30 || !rest.is_empty() { + return None; + } + let signed = children(signed.value)?; + let [version, digests, encap, tail @ ..] = signed.as_slice() else { return None }; + if version.tag != 0x02 || !matches!(version.value, [1 | 3 | 4 | 5]) || digests.tag != 0x31 || encap.tag != 0x30 { + return None; + } + if children(digests.value)?.iter().any(|algorithm| algorithm.tag != 0x30) { + return None; + } + // Certificates and revocation lists are optional, but ordered and present at most once. + let tail = if tail.first().is_some_and(|field| field.tag == 0xa0) { tail.get(1..)? } else { tail }; + let tail = if tail.first().is_some_and(|field| field.tag == 0xa1) { tail.get(1..)? } else { tail }; + let [signers] = tail else { return None }; + if signers.tag != 0x31 || children(signers.value)?.iter().any(|signer| signer.tag != 0x30) { + return None; + } + let encap = children(encap.value)?; + let [kind, content] = encap.as_slice() else { return None }; + if kind.tag != 0x06 || kind.value != DATA || content.tag != 0xa0 { + return None; + } + let (octets, rest) = read(content.value)?; + (octets.tag == 0x04 && rest.is_empty()).then(|| octets.value.to_vec()) +} + +/// How deep elements may nest. +pub const MAX_DEPTH: usize = 48; + +/// Maximum elements materialized or indexed in one parsing operation. This bounds the +/// allocation amplification from hostile, shallow input containing many empty TLVs. +pub const MAX_ELEMENTS: usize = 65_536; + +/// The universal tag of an OCTET STRING, and of one in pieces. +const OCTET_STRING: u8 = 0x04; +const OCTET_STRING_PIECES: u8 = 0x24; + +/// One element: its tag bytes, and its value (the content octets). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Tlv<'a> { + /// The tag's first byte (class, constructed bit, number below 31). + pub tag: u8, + /// The whole element, tag and length included. + pub whole: &'a [u8], + /// Its content octets. + pub value: &'a [u8], +} + +/// The tag bytes at the start of `bytes`: one, or a high tag number in up to four more. +fn tag_len(bytes: &[u8]) -> Option { + let first = *bytes.first()?; + if first & 0x1f != 0x1f { + return Some(1); + } + // High tag number: base-128 bytes, the last without its top bit. + for (i, b) in bytes.iter().enumerate().skip(1).take(4) { + if b & 0x80 == 0 { + return i.checked_add(1); + } + } + None +} + +/// The length at the start of `bytes`: `(length, bytes it took)`, `None` for an indefinite one +/// (`Some((None, 1))`) is told apart by the caller. +fn length(bytes: &[u8]) -> Option<(Option, usize)> { + let first = *bytes.first()?; + if first < 0x80 { + return Some((Some(usize::from(first)), 1)); + } + if first == 0x80 { + return Some((None, 1)); + } + let n = usize::from(first & 0x7f); + if n > 4 { + return None; + } + let digits = bytes.get(1..n.checked_add(1)?)?; + let len = digits.iter().fold(0usize, |acc, d| (acc << 8) | usize::from(*d)); + Some((Some(len), n.checked_add(1)?)) +} + +/// The element at the start of `bytes` with a definite length, and what follows it. `None` for +/// an indefinite length, or one longer than what is there. +pub fn read(bytes: &[u8]) -> Option<(Tlv<'_>, &[u8])> { + let t = tag_len(bytes)?; + let tag = *bytes.first()?; + let (len, l) = length(bytes.get(t..)?)?; + let len = len?; + let start = t.checked_add(l)?; + let end = start.checked_add(len)?; + let value = bytes.get(start..end)?; + let whole = bytes.get(..end)?; + Some((Tlv { tag, whole, value }, bytes.get(end..)?)) +} + +/// The elements of `value`, each with a definite length; `None` when one can't be read. +pub fn children(mut value: &[u8]) -> Option>> { + let mut out = Vec::new(); + while !value.is_empty() { + if out.len() >= MAX_ELEMENTS { + return None; + } + let (tlv, rest) = read(value)?; + out.push(tlv); + value = rest; + } + Some(out) +} + +/// `bytes` as DER as far as CMS needs it: indefinite lengths made definite and OCTET STRINGs in +/// pieces joined into one, everything else as it was. One element is read, and must be all of +/// `bytes` (bar trailing zero bytes, which some writers pad with). `None` when it isn't BER. +pub fn to_der(bytes: &[u8]) -> Option> { + if let Some((_, rest)) = read(bytes) + && rest.iter().all(|b| *b == 0) + && der_shaped(bytes.get(..bytes.len().saturating_sub(rest.len()))?, 0) + { + return bytes.get(..bytes.len().saturating_sub(rest.len())).map(<[u8]>::to_vec); + } + let mut out = Vec::with_capacity(bytes.len()); + let used = element(bytes, 0, &mut out)?; + let rest = bytes.get(used..)?; + rest.iter().all(|b| *b == 0).then_some(out) +} + +/// Whether the elements of `bytes` all have definite lengths and no OCTET STRING is in pieces, +/// as deep as they go: nothing to change. +fn der_shaped(mut bytes: &[u8], depth: usize) -> bool { + if depth > MAX_DEPTH { + return false; + } + while !bytes.is_empty() { + let Some((tlv, rest)) = read(bytes) else { return false }; + if tlv.tag == OCTET_STRING_PIECES || (tlv.tag & 0x20 != 0 && !der_shaped(tlv.value, depth.saturating_add(1))) { + return false; + } + bytes = rest; + } + true +} + +/// What [`measure`] found of one element: how many bytes of the input it was, and how long its +/// content is as DER. +#[derive(Clone, Copy)] +struct Size { + used: usize, + content: usize, + /// It is DER-shaped already (a definite length, and nothing in it to change): copied as it + /// is, its lengths as the writer wrote them, since a signature may cover them. + verbatim: bool, +} + +/// The sizes of the constructed elements of the input, by where each starts in it: worked out +/// once, so that writing them is one pass with no copy of a level for each level above it. +type Sizes = std::collections::HashMap; + +/// The element at `at` in `input`: how many bytes it was, and its length as DER, header and all. +fn measure(input: &[u8], at: usize, depth: usize, sizes: &mut Sizes) -> Option<(usize, usize)> { + if depth > MAX_DEPTH || sizes.len() >= MAX_ELEMENTS { + return None; + } + let bytes = input.get(at..)?; + if let Some((tlv, _)) = read(bytes) + && der_shaped(tlv.whole, depth) + { + sizes.insert(at, Size { used: tlv.whole.len(), content: tlv.value.len(), verbatim: true }); + return Some((tlv.whole.len(), tlv.whole.len())); + } + let t = tag_len(bytes)?; + let tag = *bytes.first()?; + let (len, l) = length(bytes.get(t..)?)?; + let start = t.checked_add(l)?; + if tag & 0x20 == 0 { + let used = start.checked_add(len?)?; + bytes.get(..used)?; + return Some((used, used_der(t, used.checked_sub(start)?)?)); + } + // The children, one after another, to the end of a definite length or to the end mark. + let mut content = 0usize; + let mut pos = start; + let end = match len { + Some(len) => Some(start.checked_add(len)?), + None => None, + }; + loop { + match end { + Some(end) if pos >= end => break, + None if bytes.get(pos..)?.starts_with(&[0, 0]) => { + pos = pos.checked_add(2)?; + break; + } + _ => {} + } + // (The pieces of an OCTET STRING are OCTET STRINGs, in pieces themselves or not.) + if tag == OCTET_STRING_PIECES && !matches!(bytes.get(pos), Some(&OCTET_STRING | &OCTET_STRING_PIECES)) { + return None; + } + let (n, der) = measure(input, at.checked_add(pos)?, depth.checked_add(1)?, sizes)?; + if n == 0 { + return None; + } + // An OCTET STRING in pieces is one of their contents together. + content = content.checked_add(if tag == OCTET_STRING_PIECES { der_content(input, at.checked_add(pos)?, sizes)? } else { der })?; + pos = pos.checked_add(n)?; + } + if let Some(end) = end + && pos != end + { + return None; + } + if sizes.len() >= MAX_ELEMENTS { + return None; + } + sizes.insert(at, Size { used: pos, content, verbatim: false }); + let header_tag = if tag == OCTET_STRING_PIECES { 1 } else { t }; + Some((pos, used_der(header_tag, content)?)) +} + +/// The length of a DER element with a tag of `tag` bytes and `content` bytes of content. +fn used_der(tag: usize, content: usize) -> Option { + let mut l = Vec::new(); + put_length(&mut l, content); + tag.checked_add(l.len())?.checked_add(content) +} + +/// The DER content length of the (measured) element at `at`: a primitive's own. +fn der_content(input: &[u8], at: usize, sizes: &Sizes) -> Option { + if let Some(s) = sizes.get(&at) { + return Some(s.content); + } + let bytes = input.get(at..)?; + let t = tag_len(bytes)?; + let (len, _) = length(bytes.get(t..)?)?; + len +} + +/// Write the (measured) element at `at` in `input` to `out` as DER; how many bytes it was. +fn write(input: &[u8], at: usize, sizes: &Sizes, pieces: bool, out: &mut Vec) -> Option { + if let Some(s) = sizes.get(&at).filter(|s| s.verbatim && !pieces) { + out.extend_from_slice(input.get(at..at.checked_add(s.used)?)?); + return Some(s.used); + } + let bytes = input.get(at..)?; + let t = tag_len(bytes)?; + let tag_bytes = bytes.get(..t)?; + let tag = *tag_bytes.first()?; + let (len, l) = length(bytes.get(t..)?)?; + let start = t.checked_add(l)?; + if tag & 0x20 == 0 { + let used = start.checked_add(len?)?; + let value = bytes.get(start..used)?; + // (A piece of an OCTET STRING in pieces gives its bytes alone.) + if !pieces { + out.extend_from_slice(tag_bytes); + put_length(out, value.len()); + } + out.extend_from_slice(value); + return Some(used); + } + let size = *sizes.get(&at)?; + if tag == OCTET_STRING_PIECES { + if !pieces { + out.push(OCTET_STRING); + put_length(out, size.content); + } + } else { + out.extend_from_slice(tag_bytes); + put_length(out, size.content); + } + let inner_pieces = tag == OCTET_STRING_PIECES; + let mut pos = start; + while pos < size.used { + if bytes.get(pos..)?.starts_with(&[0, 0]) && len.is_none() { + break; + } + let n = write(input, at.checked_add(pos)?, sizes, inner_pieces, out)?; + pos = pos.checked_add(n)?; + } + Some(size.used) +} + +/// Write the element at the start of `bytes` to `out` as DER; how many bytes of `bytes` it was. +fn element(bytes: &[u8], depth: usize, out: &mut Vec) -> Option { + let mut sizes = Sizes::new(); + let (used, der) = measure(bytes, 0, depth, &mut sizes)?; + out.reserve(der); + write(bytes, 0, &sizes, false, out)?; + Some(used) +} + +/// A definite length in DER's shortest form. +fn put_length(out: &mut Vec, len: usize) { + if len < 0x80 { + out.push(len as u8); + return; + } + let bytes = len.to_be_bytes(); + let skip = bytes.iter().take_while(|b| **b == 0).count(); + let digits = bytes.get(skip..).unwrap_or_default(); + out.push(0x80 | digits.len() as u8); + out.extend_from_slice(digits); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tlv(tag: u8, value: &[u8]) -> Vec { + let mut out = vec![tag]; + put_length(&mut out, value.len()); + out.extend_from_slice(value); + out + } + + fn cms(outer_tag: u8, signed_tag: u8, oid_tag: u8, long_oid: bool, trailing: bool) -> Vec { + let oid = |value: &[u8]| { + if long_oid { + let mut out = vec![oid_tag, 0x81, 9]; + out.extend_from_slice(value); + out + } else { + tlv(oid_tag, value) + } + }; + let mut encap = oid(DATA); + encap.extend(tlv(0xa0, &tlv(0x04, b"hello"))); + let mut signed = tlv(0x02, &[1]); + signed.extend(tlv(0x31, &[])); + signed.extend(tlv(0x30, &encap)); + signed.extend(tlv(0x31, &[])); + let mut signed = tlv(signed_tag, &signed); + if trailing { + signed.extend(tlv(0x05, &[])); + } + let mut info = oid(SIGNED_DATA); + info.extend(tlv(0xa0, &signed)); + tlv(outer_tag, &info) + } + + #[test] + fn extracts_content_with_der_and_ber_oid_lengths() { + for long_oid in [false, true] { + assert_eq!(signed_content(&cms(0x30, 0x30, 0x06, long_oid, false)), Some(b"hello".to_vec())); + } + } + + #[test] + fn rejects_wrong_cms_container_and_oid_tags() { + for (outer, signed, oid) in [(0x31, 0x30, 0x06), (0x30, 0x31, 0x06), (0x30, 0x30, 0x04)] { + assert_eq!(signed_content(&cms(outer, signed, oid, false, false)), None); + } + } + + #[test] + fn rejects_missing_mandatory_signed_data_fields() { + let mut encap = tlv(0x06, DATA); + encap.extend(tlv(0xa0, &tlv(0x04, b"hello"))); + for prefix in [vec![0x05, 0, 0x05, 0], vec![0x02, 1, 1, 0x31, 0]] { + let mut malformed = prefix; + malformed.extend(tlv(0x30, &encap)); + let mut info = tlv(0x06, SIGNED_DATA); + info.extend(tlv(0xa0, &tlv(0x30, &malformed))); + assert_eq!(signed_content(&tlv(0x30, &info)), None); + } + } + + #[test] + fn rejects_extra_signed_data_inside_explicit_container() { + assert_eq!(signed_content(&cms(0x30, 0x30, 0x06, false, true)), None); + } + + #[test] + fn rejects_wide_inputs_before_unbounded_metadata_allocation() { + let children_bytes = [0x05, 0].repeat(MAX_ELEMENTS + 1); + assert!(children(&children_bytes).is_none()); + let mut indefinite = vec![0x30, 0x80]; + indefinite.extend_from_slice(&children_bytes); + indefinite.extend_from_slice(&[0, 0]); + assert!(to_der(&indefinite).is_none()); + } + + #[test] + fn joins_indefinite_octet_string_pieces() { + assert_eq!(to_der(&[0x24, 0x80, 0x04, 1, b'a', 0x04, 1, b'b', 0, 0]), Some(vec![0x04, 2, b'a', b'b'])); + } + + #[test] + fn rejects_truncated_and_over_nested_input() { + assert_eq!(to_der(&[0x04, 2, b'a']), None); + let mut nested = tlv(0x04, &[]); + for _ in 0..=MAX_DEPTH { + nested = tlv(0x30, &nested); + } + assert_eq!(to_der(&nested), None); + } +} diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index 404b5a315..c52c145f5 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -531,10 +531,32 @@ pub fn write_cube(l: &LutFile) -> String { s.push_str(&format!("DOMAIN_MAX {} {} {}\n", l.domain_max[0], l.domain_max[1], l.domain_max[2])); } s.push_str(&format!("LUT_3D_SIZE {}\n", l.size)); + write_cube_rows(&mut s, l); + s +} + +/// Writes a `.cube` file with a creator comment, section comments and an explicit input domain. +/// +/// This layout is useful for exported LUTs; [`write_cube`] keeps its compact layout for embedded +/// tables. Values retain six decimal places, and their order and quantisation belong to the +/// caller. A default domain is written as `0.0` and `1.0` for compatibility with export consumers. +pub fn write_cube_commented(l: &LutFile, creator: &str) -> String { + let mut s = format!("#Created by: {creator}\nTITLE \"{}\"\n\n#LUT size\nLUT_3D_SIZE {}\n\n#data domain\n", l.title.replace('"', "'"), l.size); + if l.domain_is_default() { + s.push_str("DOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n"); + } else { + s.push_str(&format!("DOMAIN_MIN {} {} {}\n", l.domain_min[0], l.domain_min[1], l.domain_min[2])); + s.push_str(&format!("DOMAIN_MAX {} {} {}\n", l.domain_max[0], l.domain_max[1], l.domain_max[2])); + } + s.push_str("\n#LUT data points\n"); + write_cube_rows(&mut s, l); + s +} + +fn write_cube_rows(s: &mut String, l: &LutFile) { for c in l.data.as_chunks::<3>().0 { s.push_str(&format!("{:.6} {:.6} {:.6}\n", c[0], c[1], c[2])); } - s } fn luma(c: [f32; 3]) -> f32 { @@ -602,6 +624,30 @@ pub fn builtin(id: &str) -> Option { mod tests { use super::*; + #[test] + fn commented_cube_preserves_export_header_and_rows() { + let mut lut = super::LutFile::identity(2).unwrap(); + lut.title = "A \"look\"".into(); + let text = super::write_cube_commented(&lut, "ExampleCraft"); + assert!(text.starts_with("#Created by: ExampleCraft\nTITLE \"A 'look'\"\n\n#LUT size\nLUT_3D_SIZE 2\n\n#data domain\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n\n#LUT data points\n")); + let parsed = super::parse_cube(&text).unwrap(); + assert_eq!(parsed.data, lut.data); + assert_eq!(parsed.title, "A 'look'"); + assert_eq!(text.lines().count(), 11 + 8); + let rows = |s: &str| s.lines().filter(|line| line.starts_with(|c: char| c.is_ascii_digit())).map(str::to_owned).collect::>(); + assert_eq!(rows(&text), rows(&super::write_cube(&lut))); + } + + #[test] + fn commented_cube_keeps_nondefault_domain_and_sample_precision() { + let mut lut = super::LutFile::identity(2).unwrap(); + lut.domain_min = [0.125, 0.25, 0.375]; + lut.domain_max = [0.625, 0.75, 0.875]; + lut.data[0] = 0.833344; + let parsed = super::parse_cube(&super::write_cube_commented(&lut, "ExampleCraft")).unwrap(); + assert_eq!(parsed, lut); + } + #[test] fn cube_title_hashes_and_comment_quotes_are_distinct() { let rows = "LUT_1D_SIZE 2\n0 0 0 # low\n1 1 1 # high\n"; diff --git a/crates/csv/README.md b/crates/csv/README.md index c677ec9eb..6369ce8b4 100644 --- a/crates/csv/README.md +++ b/crates/csv/README.md @@ -11,7 +11,7 @@ mapping a SYLK sheet onto a document are the caller's work. | Function | What it does | |---|---| | `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 | -| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent count per line over the first 20 non-blank lines, outside quotes | +| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 non-blank records in a 64 KiB sample; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | | `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text | | `records(text, delim, quote, max_records, max_fields)` | the same, collected | | `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing | diff --git a/crates/csv/src/decode.rs b/crates/csv/src/decode.rs index 238f7f18e..63b4bb590 100644 --- a/crates/csv/src/decode.rs +++ b/crates/csv/src/decode.rs @@ -19,6 +19,16 @@ const CP1256: [u32; 128] = [ 0x200F, 0x06D2, ]; +/// Decode strictly as UTF-8, stripping a leading UTF-8 BOM when present. +/// +/// Unlike [`decode_text`], this does not guess a legacy encoding or accept UTF-16. It is useful +/// when a format or application contract requires UTF-8 and malformed bytes must be rejected. +pub fn decode_utf8(bytes: &[u8]) -> Result { + let bytes = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes); + let text = std::str::from_utf8(bytes)?; + Ok(text.strip_prefix('\u{FEFF}').unwrap_or(text).to_string()) +} + /// Evidence that bytes which aren't UTF-8 are Windows-1256 Arabic rather than Windows-1252. #[derive(Default)] struct Cp1256Evidence { @@ -165,6 +175,16 @@ mod tests { assert_eq!(decode_text(&[0xFF, 0xFE, 0x00, 0xD8]), "\u{FFFD}", "a lone surrogate"); } + #[test] + fn strict_utf8_strips_bom_and_rejects_legacy_or_malformed_bytes() { + assert_eq!(decode_utf8(b"\xEF\xBB\xBFName,City\nAda,Town\n").unwrap(), "Name,City\nAda,Town\n"); + assert_eq!(decode_utf8("café".as_bytes()).unwrap(), "café"); + assert!(decode_utf8(&[0xFF, 0xFE, 0x00]).is_err()); + assert!(decode_utf8(b"\xEF\xBB\xBF\xFF").is_err()); + // The permissive text decoder still accepts legacy encodings for callers that want it. + assert_eq!(decode_text(&[0x80, b'a', 0xE9]), "€aé"); + } + #[test] fn windows_1256_table_matches_the_unicode_mapping() { let at = |b: u8| CP1256.get(usize::from(b - 0x80)).and_then(|&c| char::from_u32(c)); diff --git a/crates/csv/src/lib.rs b/crates/csv/src/lib.rs index a773f066f..0aec971ac 100644 --- a/crates/csv/src/lib.rs +++ b/crates/csv/src/lib.rs @@ -3,6 +3,7 @@ //! //! - [`decode_text`] turns a file's bytes into a string: byte order marks, UTF-8, else //! Windows-1256 when the bytes read as Arabic and Windows-1252 otherwise. +//! - [`decode_utf8`] requires valid UTF-8 and strips a leading UTF-8 byte order mark. //! - [`sniff_delimiter`] picks comma, semicolon or tab. //! - [`parse_records`] splits text into records of fields (RFC 4180 with the usual leniency), //! handing each record to a callback, with a cap on the fields kept per record. [`records`] @@ -27,46 +28,98 @@ mod decode; pub mod sylk; -pub use decode::decode_text; +pub use decode::{decode_text, decode_utf8}; -/// Picks comma, semicolon or tab: the candidate with the most consistent count per line -/// (outside quotes) over the first non-blank lines. A candidate must appear on every such line, otherwise comma wins. +/// Picks comma, semicolon or tab by consistent field counts in the first non-blank records. +/// Quotes start only at a candidate field boundary; candidates with incoherent quoted fields +/// are discarded when another coherent candidate separates the records. Ties prefer tab, +/// then comma, then semicolon. Comma is the fallback when no candidate separates the text. pub fn sniff_delimiter(text: &str, quote: char) -> u8 { - let mut best = (b',', 0usize, 0usize); - for d in [',', ';', '\t'] { - let mut counts = vec![]; - let mut n = 0usize; - let mut in_q = false; - let mut blank = true; - for ch in text.chars().take(64 * 1024) { - if !in_q && ch == '\n' { - // Blank lines carry no delimiter evidence. - if !blank { - counts.push(n); - } - n = 0; - blank = true; - if counts.len() >= 20 { - break; + let mut candidates = [(b'\t', 0usize, 0usize, true), (b',', 0, 0, true), (b';', 0, 0, true)]; + const SAMPLE_BYTES: usize = 64 * 1024; + let mut sample_end = text.len().min(SAMPLE_BYTES); + while !text.is_char_boundary(sample_end) { + sample_end -= 1; + } + let sample = &text[..sample_end]; + let truncated = sample_end < text.len(); + for (delimiter, min_count, total, coherent) in &mut candidates { + let mut counts = Vec::new(); + let mut count = 0usize; + let mut quoted = false; + let mut after_quote = false; + let mut field_start = true; + let mut record_has_content = false; + let mut record_coherent = true; + let mut candidate_coherent = true; + let mut reached_record_limit = false; + let mut chars = sample.chars().peekable(); + while let Some(ch) = chars.next() { + if quoted { + if ch == quote { + if chars.peek() == Some("e) { + chars.next(); + record_has_content = true; + } else { + quoted = false; + after_quote = true; + } + } else if !ch.is_whitespace() { + record_has_content = true; } continue; } - if ch != '\r' { - blank = false; + if ch == '\r' || ch == '\n' { + if ch == '\r' && chars.peek() == Some(&'\n') { + chars.next(); + } + if record_has_content { + counts.push(count); + candidate_coherent &= record_coherent; + if counts.len() >= 20 { + reached_record_limit = true; + break; + } + } + count = 0; + quoted = false; + after_quote = false; + field_start = true; + record_has_content = false; + record_coherent = true; + continue; } - if ch == quote { - in_q = !in_q; - } else if !in_q && ch == d { - n += 1; + if ch == quote && field_start { + quoted = true; + field_start = false; + record_has_content = true; + } else if ch == char::from(*delimiter) { + count += 1; + field_start = true; + after_quote = false; + } else { + record_coherent &= !after_quote || ch.is_whitespace(); + record_has_content |= !ch.is_whitespace(); + field_start = false; } } - if !blank { - counts.push(n); + if !reached_record_limit && !truncated { + if quoted { + candidate_coherent = false; + } else if record_has_content { + candidate_coherent &= record_coherent; + counts.push(count); + } } - let min = counts.iter().copied().min().unwrap_or(0); - let total: usize = counts.iter().sum(); - if min > 0 && (min, total) > (best.1, best.2) { - best = (d as u8, min, total); + *coherent &= candidate_coherent; + *min_count = counts.iter().copied().min().unwrap_or(0); + *total = counts.iter().sum(); + } + let prefer_coherent = candidates.iter().any(|(_, min, _, coherent)| *min > 0 && *coherent); + let mut best = (b',', 0usize, 0usize); + for (delimiter, min, total, coherent) in candidates { + if min > 0 && (!prefer_coherent || coherent) && (min, total) > (best.1, best.2) { + best = (delimiter, min, total); } } best.0 @@ -204,6 +257,9 @@ mod tests { assert_eq!(sniff_delimiter("a\tb\n1\t2\n", '"'), b'\t'); assert_eq!(sniff_delimiter("a,b\n\"x;y;z\",2\n", '"'), b','); assert_eq!(sniff_delimiter("single", '"'), b','); + assert_eq!(sniff_delimiter("a,b\tc\n1,2\td\n", '"'), b'\t'); + assert_eq!(sniff_delimiter("a,b;c\n1,2;c\n", '"'), b','); + assert_eq!(sniff_delimiter("a;b\tc\n1;2\td\n", '"'), b'\t'); // A delimiter missing from some lines is text, not a separator (single-column export round trip). assert_eq!(sniff_delimiter("alpha;beta\r\ngamma\r\n", '"'), b','); assert_eq!(sniff_delimiter("alpha\tbeta\r\ngamma\r\n", '"'), b','); @@ -211,6 +267,48 @@ mod tests { assert_eq!(sniff_delimiter("x;y\n1,5;2", '"'), b';'); } + #[test] + fn delimiter_sniffing_preserves_candidate_quote_boundaries() { + for ending in ["\n", "\r\n", "\r"] { + for (text, expected) in [ + (format!("Name,\"preferred\tCity\"{ending}Ada\tLondon{ending}"), b'\t'), + (format!("\"Last, First\";City{ending}Ada;London{ending}"), b';'), + (format!("\"Name\";\"Last, First\"{ending}\"Ada\";\"Lovelace, Countess\"{ending}\"Grace\";\"Hopper, Admiral\"{ending}"), b';'), + (format!("\"Name\"suffix,Title\tCity{ending}\"Ada\"suffix,Analyst\tLondon\tignored{ending}"), b'\t'), + (format!("\r\n \r\n\"Name\";City{ending}Ada;London{ending}"), b';'), + ] { + assert_eq!(sniff_delimiter(&text, '"'), expected, "{text:?}"); + } + } + } + + #[test] + fn delimiter_sniffing_counts_empty_quoted_fields_and_ignores_whitespace_records() { + assert_eq!(sniff_delimiter("\"\";name\n\"\";Ada\n", '"'), b';'); + + let blank_rows = "\t \t\n".repeat(25); + assert_eq!(sniff_delimiter(&format!("{blank_rows}a;b\nc;d\n"), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_does_not_count_the_twentieth_record_twice() { + let mut text = "a;b\tc\td\n".repeat(19); + text.push('a'); + text.push_str(&";".repeat(19)); + text.push_str("\tc\n"); + assert_eq!(sniff_delimiter(&text, '"'), b'\t'); + } + + #[test] + fn delimiter_sniffing_discards_an_incomplete_record_at_the_sample_boundary() { + let complete = "a\tb\tc\n1\t2\t3\n"; + let remaining = 64 * 1024 - complete.len(); + let partial = format!("{}x\t\"unfinished", "z".repeat(remaining - 4)); + assert!(partial.len() >= remaining); + let text = format!("{complete}{partial}\"\n"); + assert_eq!(sniff_delimiter(&text, '"'), b'\t'); + } + #[test] fn parser_stops_collecting_fields_at_the_cap() { let (max, extra) = (16_384usize, 50); diff --git a/crates/dav/src/lib.rs b/crates/dav/src/lib.rs index 87040feae..db137a050 100644 --- a/crates/dav/src/lib.rs +++ b/crates/dav/src/lib.rs @@ -74,7 +74,14 @@ pub fn parse_multistatus(bytes: &[u8]) -> Result { if !text.chars().all(craft_xml::is_xml_char) { return Err(Error::Characters); } - let limits = Limits { max_input: MAX_BYTES, max_depth: MAX_DEPTH, max_nodes: MAX_NODES, max_attrs: MAX_ATTRS, max_attrs_total: MAX_ATTRS_TOTAL }; + let limits = Limits { + max_input: MAX_BYTES, + max_depth: MAX_DEPTH, + max_nodes: MAX_NODES, + max_elements: MAX_NODES, + max_attrs: MAX_ATTRS, + max_attrs_total: MAX_ATTRS_TOTAL, + }; let options = Options { doctype: Doctype::Reject, ..Options::canonical(&CANONICAL).strict().with_limits(limits) }; let root = options.parse(bytes).map_err(Error::Xml)?; if root.name != "d:multistatus" { diff --git a/crates/designcraft-format/src/lib.rs b/crates/designcraft-format/src/lib.rs index 6256eab1c..eab431eab 100644 --- a/crates/designcraft-format/src/lib.rs +++ b/crates/designcraft-format/src/lib.rs @@ -6,7 +6,7 @@ #![forbid(unsafe_code)] use std::collections::{HashMap, HashSet}; -use std::io::{Read, Seek}; +use std::io::{Cursor, Read, Seek, Write}; pub use craft_document_bundle::Asset; use craft_document_bundle::Spec; @@ -14,9 +14,10 @@ use serde::{Serialize, de::DeserializeOwned}; use serde_json::Value; pub const MIME: &str = "application/vnd.designcraft+zip"; -pub const VERSION: u32 = 4; +pub const VERSION: u32 = 5; pub const EXTENSION: &str = "designcraft"; pub const PREVIEW: &str = "preview.png"; +pub const PROXIES_DIRECTORY: &str = "proxies"; pub const MAX_PREVIEW_BYTES: u64 = 4 << 20; const BUNDLE: Spec<'static> = Spec { @@ -26,6 +27,7 @@ const BUNDLE: Spec<'static> = Spec { document_entry: "document.json", preview_entry: PREVIEW, assets_directory: "assets", + proxies_directory: PROXIES_DIRECTORY, format_name: "designcraft", legacy_assets_field: Some("assetData"), }; @@ -57,23 +59,53 @@ impl From for Error { pub struct Loaded { pub document: T, pub assets: Vec<(String, Vec)>, + /// Proxy previews (JPEG or PNG bytes) of linked assets, keyed by asset id. + pub proxies: Vec<(String, Vec)>, } /// The reader capability required by `document`, inferred from its neutral JSON schema and -/// embedded assets. Traversal beyond 64 levels conservatively requires version 4. +/// embedded assets. Traversal beyond 64 levels conservatively requires version 4. A linked +/// asset (`/assets//storage == "linked"`) requires version 5. pub fn required_version(document: &Value, assets: &[Asset<'_>]) -> u32 { + if has_linked_asset(document) { + return 5; + } if has_version_four_feature(document) { return 4; } if assets.iter().any(|asset| craft_eps::is_eps(asset.data)) { 3 } else { 2 } } -/// Serialize a document and its external assets as a `.designcraft` ZIP bundle. -pub fn save(document: &T, generator: &str, preview: Option<&[u8]>, assets: &[Asset<'_>]) -> Result, Error> { +/// Serialize a document, its embedded assets and the proxy previews of its linked assets as a +/// `.designcraft` ZIP bundle. Linked assets have a record in the document and no `assets` entry. +pub fn save( + document: &T, + generator: &str, + preview: Option<&[u8]>, + assets: &[Asset<'_>], + proxies: &[Asset<'_>], +) -> Result, Error> { + let mut out = Cursor::new(Vec::new()); + write_to(&mut out, document, generator, preview, assets, proxies)?; + Ok(out.into_inner()) +} + +/// Like [`save`], streaming the ZIP into `out`. A writer that returns an error (to cancel a +/// long save, say) stops the write and the error is returned as [`Error::Io`]. +pub fn write_to( + out: W, + document: &T, + generator: &str, + preview: Option<&[u8]>, + assets: &[Asset<'_>], + proxies: &[Asset<'_>], +) -> Result<(), Error> { let value = serde_json::to_value(document).map_err(|error| Error::Io(error.to_string()))?; + let embedded: Vec> = assets.iter().filter(|asset| !is_linked(&value, asset.id)).copied().collect(); + let assets = embedded.as_slice(); let version = required_version(&value, assets); let json = serde_json::to_vec_pretty(&value).map_err(|error| Error::Io(error.to_string()))?; - craft_document_bundle::write(&json, version, generator, preview, assets, BUNDLE).map_err(Into::into) + craft_document_bundle::write_to(out, &json, version, generator, preview, assets, proxies, BUNDLE).map_err(Into::into) } /// Read a `.designcraft` ZIP or legacy single-file JSON, applying all versioned schema migrations @@ -82,7 +114,7 @@ pub fn load(bytes: &[u8]) -> Result, Error> { let mut package = craft_document_bundle::read(bytes, VERSION, BUNDLE)?; upgrade_legacy_json(&mut package.document, package.version); let document = serde_json::from_value(package.document).map_err(|error| Error::NotOurs(error.to_string()))?; - Ok(Loaded { document, assets: package.assets }) + Ok(Loaded { document, assets: package.assets, proxies: package.proxies }) } /// Whether `bytes` are a native DesignCraft ZIP package. @@ -100,6 +132,17 @@ pub fn read_preview(reader: R) -> Option> { craft_document_bundle::read_preview_from(reader, PREVIEW) } +fn is_linked(document: &Value, id: &str) -> bool { + document.get("assets").and_then(|assets| assets.get(id)).and_then(|asset| asset.get("storage")).and_then(Value::as_str) == Some("linked") +} + +fn has_linked_asset(document: &Value) -> bool { + document + .get("assets") + .and_then(Value::as_object) + .is_some_and(|assets| assets.values().any(|asset| asset.get("storage").and_then(Value::as_str) == Some("linked"))) +} + fn has_version_four_feature(document: &Value) -> bool { let mut stack = vec![(document, 0usize)]; let mut visited = 0usize; diff --git a/crates/designcraft-format/src/tests.rs b/crates/designcraft-format/src/tests.rs index 0ef2ca191..38cf1c34f 100644 --- a/crates/designcraft-format/src/tests.rs +++ b/crates/designcraft-format/src/tests.rs @@ -7,7 +7,7 @@ fn native_bundle_roundtrips_document_assets_and_preview() -> Result<(), Box Result<(), Box Result<(), Box> { let oversized = vec![0u8; usize::try_from(MAX_PREVIEW_BYTES + 1)?]; - let bytes = save(&json!({}), "DesignCraft test", Some(&oversized), &[])?; + let bytes = save(&json!({}), "DesignCraft test", Some(&oversized), &[], &[])?; assert_eq!(read_preview(std::io::Cursor::new(bytes)), None); Ok(()) } @@ -65,8 +65,105 @@ fn legacy_json_extracts_assets_and_applies_v1_migrations() -> Result<(), Box Result<(), Box> { - let bytes = craft_document_bundle::write(b"{", VERSION + 1, "future", None, &[], BUNDLE)?; + let bytes = craft_document_bundle::write(b"{", VERSION + 1, "future", None, &[], &[], BUNDLE)?; assert!(matches!(load::(&bytes), Err(Error::TooNew(version)) if version == u64::from(VERSION + 1))); assert!(matches!(load::(b"not a package"), Err(Error::NotOurs(_)))); Ok(()) } + +fn linked_doc() -> Value { + json!({"assets":{"7":{"storage":"linked","mime":"image/png"},"8":{"mime":"image/png"}}}) +} + +#[test] +fn embedded_documents_keep_their_version() { + assert_eq!(required_version(&json!({"assets":{"7":{"storage":"embedded"},"8":{}}}), &[]), 2); +} + +#[test] +fn a_linked_asset_requires_version_five_and_old_readers_refuse_it() -> Result<(), Box> { + assert_eq!(required_version(&linked_doc(), &[]), 5); + let bytes = save(&linked_doc(), "t", None, &[], &[])?; + assert_eq!(craft_document_bundle::read(&bytes, 4, BUNDLE), Err(craft_document_bundle::Error::TooNew(5))); + let loaded = load::(&bytes)?; + assert_eq!(loaded.document, linked_doc()); + assert!(loaded.assets.is_empty()); + Ok(()) +} + +#[test] +fn proxies_round_trip_and_unknown_or_oversized_ones_are_skipped() -> Result<(), Box> { + let big = vec![0u8; usize::try_from(craft_document_bundle::PROXY_LIMIT)? + 1]; + let proxies = [ + Asset { id: "7", mime: "image/jpeg", data: b"jpeg" }, + Asset { id: "8", mime: "image/png", data: &big }, + Asset { id: "99", mime: "image/png", data: b"unknown" }, + ]; + let bytes = save(&linked_doc(), "t", None, &[], &proxies)?; + assert_eq!(load::(&bytes)?.proxies, [("7".to_owned(), b"jpeg".to_vec())]); + Ok(()) +} + +#[test] +fn proxy_paths_must_be_exactly_proxies_id_ext() -> Result<(), Box> { + let proxies = [ + Asset { id: "../x", mime: "image/png", data: b"a" }, + Asset { id: "a/b", mime: "image/png", data: b"b" }, + Asset { id: "7/8", mime: "image/png", data: b"c" }, + ]; + let bytes = save(&linked_doc(), "t", None, &[], &proxies)?; + assert!(load::(&bytes)?.proxies.is_empty()); + Ok(()) +} + +#[test] +fn write_to_stops_when_the_writer_fails() { + struct Failing { + inner: Cursor>, + budget: usize, + failed: bool, + calls_after_failure: std::rc::Rc>, + } + impl Write for Failing { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.failed { + self.calls_after_failure.set(self.calls_after_failure.get() + 1); + } + if self.budget < buf.len() { + self.failed = true; + return Err(std::io::Error::other("cancelled")); + } + self.budget -= buf.len(); + self.inner.write(buf) + } + fn flush(&mut self) -> std::io::Result<()> { + if self.failed { + self.calls_after_failure.set(self.calls_after_failure.get() + 1); + } + self.inner.flush() + } + } + impl Seek for Failing { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + if self.failed { + self.calls_after_failure.set(self.calls_after_failure.get() + 1); + } + self.inner.seek(pos) + } + } + let data = vec![1u8; 4096]; + let assets = [Asset { id: "8", mime: "image/png", data: &data }]; + let calls = std::rc::Rc::new(std::cell::Cell::new(0)); + let out = Failing { inner: Cursor::new(Vec::new()), budget: 1024, failed: false, calls_after_failure: calls.clone() }; + let result = write_to(out, &linked_doc(), "t", None, &assets, &[]); + assert_eq!(calls.get(), 0, "no write, flush or seek reaches the writer after it failed"); + assert!(matches!(result, Err(Error::Io(message)) if message.contains("cancelled"))); +} + +#[test] +fn bytes_supplied_for_a_linked_asset_are_not_written() -> Result<(), Box> { + let assets = [Asset { id: "7", mime: "image/png", data: b"linked bytes" }, Asset { id: "8", mime: "image/png", data: b"kept" }]; + let bytes = save(&linked_doc(), "t", None, &assets, &[])?; + assert_eq!(load::(&bytes)?.assets, [("8".to_owned(), b"kept".to_vec())]); + Ok(()) +} diff --git a/crates/doc-binary/src/fib.rs b/crates/doc-binary/src/fib.rs index 7bb3ec149..4224f6962 100644 --- a/crates/doc-binary/src/fib.rs +++ b/crates/doc-binary/src/fib.rs @@ -138,7 +138,9 @@ impl Fib { } let w_ident = u16le(0); if w_ident == 0xA5DC { - return Err(DocbinError::NotWord("Word 6.0/95 format, only Word 97-2003 is supported".into())); + // `read` sends Word 6.0/95 streams to `word6` before this FIB is parsed. This keeps any + // other caller from reading one with the Word 97 layout, which it doesn't have. + return Err(DocbinError::NotWord("a Word 6.0/95 file doesn't have the Word 97 FIB layout".into())); } if w_ident != W_IDENT { return Err(DocbinError::NotWord(format!("magic 0x{w_ident:04X}, expected 0x{W_IDENT:04X}"))); diff --git a/crates/doc-binary/src/fkp.rs b/crates/doc-binary/src/fkp.rs index 3de272da2..3a795d4a4 100644 --- a/crates/doc-binary/src/fkp.rs +++ b/crates/doc-binary/src/fkp.rs @@ -29,6 +29,19 @@ pub(crate) struct Bins { sorted: bool, /// Page number (× 512 = byte offset in the WordDocument stream). pns: Vec, + /// Runs read ahead of time instead of pages (Word 6.0/95, whose FKPs and sprms are another + /// layout, translated by [`crate::word6`]): sorted by `lo`, not overlapping. + translated: Option>, +} + +/// One run of a [`Bins::translated`] table: the FCs `[lo, hi)` it covers, the paragraph style +/// (for PAPX runs) and a Word 97 grpprl. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct TranslatedRun { + pub(crate) lo: u32, + pub(crate) hi: u32, + pub(crate) istd: u16, + pub(crate) grpprl: Vec, } impl Bins { @@ -37,7 +50,7 @@ impl Bins { let fc = fc as usize; let lcb = lcb as usize; if lcb < 4 || !(lcb - 4).is_multiple_of(8) { - return Ok(Bins { fcs: Vec::new(), sorted: true, pns: Vec::new() }); + return Ok(Bins { fcs: Vec::new(), sorted: true, pns: Vec::new(), translated: None }); } let end = fc.checked_add(lcb).ok_or_else(|| DocbinError::Malformed("bin table overflow".into()))?; let plc = table.get(fc..end).ok_or_else(|| DocbinError::Malformed("bin table outside the Table stream".into()))?; @@ -56,7 +69,31 @@ impl Bins { pns.push(at(n + 1 + i).ok_or_else(|| DocbinError::Malformed("truncated bin aPn".into()))? & 0x003F_FFFF); } let sorted = fcs.windows(2).all(|w| w.first() <= w.get(1)); - Ok(Bins { fcs, sorted, pns }) + Ok(Bins { fcs, sorted, pns, translated: None }) + } + + /// A table of runs read ahead of time ([`TranslatedRun`]). Runs are sorted by start; one that + /// overlaps an earlier one (a corrupt file) or covers nothing is dropped. + pub(crate) fn translated(mut runs: Vec) -> Bins { + runs.sort_by_key(|r| r.lo); + let mut kept: Vec = Vec::with_capacity(runs.len()); + for r in runs { + if r.lo < r.hi && kept.last().is_none_or(|last| r.lo >= last.hi) { + kept.push(r); + } + } + Bins { fcs: Vec::new(), sorted: true, pns: Vec::new(), translated: Some(kept) } + } + + /// For a translated table: the run covering `fc`, or the gap `[lo, hi)` between runs that + /// holds it. + fn translated_at(runs: &[TranslatedRun], fc: u32) -> Result<&TranslatedRun, (u32, u32)> { + let i = runs.partition_point(|r| r.lo <= fc); + let prev = i.checked_sub(1).and_then(|i| runs.get(i)); + match prev { + Some(r) if fc < r.hi => Ok(r), + _ => Err((prev.map_or(0, |r| r.hi), runs.get(i).map_or(u32::MAX, |r| r.lo))), + } } /// The page containing `fc`, as a slice of the WordDocument stream, and the FC range @@ -77,13 +114,19 @@ impl Bins { /// The grpprl of the Chpx covering `fc` ([MS-DOC] ChpxFkp: rgfc u32s, rgb offsets ×2, /// crun in the last byte). - pub(crate) fn chpx<'w>(&self, word: &'w [u8], fc: u32) -> &'w [u8] { + pub(crate) fn chpx<'w>(&'w self, word: &'w [u8], fc: u32) -> &'w [u8] { self.chpx_run(word, fc).grpprl } /// [`Bins::chpx`] with the FC range over which the same grpprl is the answer, so a walk /// over consecutive characters looks it up once per run, not once per character. - pub(crate) fn chpx_run<'w>(&self, word: &'w [u8], fc: u32) -> ChpxRun<'w> { + pub(crate) fn chpx_run<'w>(&'w self, word: &'w [u8], fc: u32) -> ChpxRun<'w> { + if let Some(runs) = &self.translated { + return match Self::translated_at(runs, fc) { + Ok(r) => ChpxRun { grpprl: &r.grpprl, lo: r.lo, hi: r.hi }, + Err((lo, hi)) => ChpxRun { grpprl: &[], lo, hi }, + }; + } let none = ChpxRun { grpprl: &[], lo: 1, hi: 0 }; let Some((page, page_lo, page_hi)) = self.page(word, fc) else { return none }; let Some(&crun) = page.get(511) else { return none }; @@ -113,7 +156,13 @@ impl Bins { /// ([MS-DOC] PapxFkp: rgfc u32s — each the FC *following* a paragraph mark —, rgbx BX /// entries (1 offset byte + 12 PHE bytes), crun in the last byte; the PAPX itself is a /// PapxInFkp with the cb/cb' size quirk). Query with the FC of the character after the mark. - pub(crate) fn papx<'w>(&self, word: &'w [u8], fc: u32) -> (u16, &'w [u8]) { + pub(crate) fn papx<'w>(&'w self, word: &'w [u8], fc: u32) -> (u16, &'w [u8]) { + if let Some(runs) = &self.translated { + return match Self::translated_at(runs, fc) { + Ok(r) => (r.istd, &r.grpprl), + Err(_) => (0, &[]), + }; + } let Some((page, _, _)) = self.page(word, fc) else { return (0, &[]) }; let Some(&crun) = page.get(511) else { return (0, &[]) }; // BX is 13 bytes; cap crun at what fits before byte 511. diff --git a/crates/doc-binary/src/lib.rs b/crates/doc-binary/src/lib.rs index 386e753f5..b2d7f3729 100644 --- a/crates/doc-binary/src/lib.rs +++ b/crates/doc-binary/src/lib.rs @@ -6,6 +6,9 @@ //! like the other Craft parsers, is lenient by design (unknown structures are skipped, bad numbers //! fall back to defaults) and bounded (stream sizes, piece counts and property counts are //! capped), so hostile input yields an error or a best-effort document, never a panic. +//! +//! Word 6.0/95 files, which that specification does not cover, are read by `word6` from their +//! observed layout: their text, formatting and tables so far. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] // The code came from an app whose lints allow this. #![allow(clippy::type_complexity)] @@ -29,6 +32,7 @@ mod sections; mod sprm; mod stsh; mod table; +mod word6; use std::sync::Arc; @@ -220,6 +224,9 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> if word.len() as u64 > MAX_STREAM { return Err(DocbinError::Limit(format!("WordDocument stream is {} bytes", word.len()))); } + if word6::is_word6(&word) { + return read_word6(&comp, &word, max_paragraphs); + } let enc = fib::peek_encryption(&word); // The FIB names the Table stream (0Table or 1Table); fall back to whichever exists, // since files written by other writers sometimes carry the wrong bit. @@ -431,6 +438,55 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> Ok(doc) } +/// Read a Word 6.0/95 file ([`word6`]): its main text, with its character and paragraph +/// formatting and table rows translated to Word 97 sprms, through the same walk as a Word 97 file. +/// Its paragraph styles are read too; character styles and the other stories are not yet, and a +/// section mark reads as a page break. +fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: usize) -> Result { + let fib = word6::Fib6::parse(word)?; + let content = word6::content(word, &fib)?; + let mut doc = Document::new(); + // Word opens these files in compatibility mode 11 too. + doc.settings.compat_mode = 11; + if let Some(core) = metadata::read(comp) { + doc.core = core; + } + doc.body.clear(); + // The paragraph styles, built as for Word 97 files from their translated formatting. + doc.styles = Arc::new(fmt::stylesheet(&content.styles, &content.fonts, stsh::StandardFonts::default())); + let sheet: StyleSheet = StyleSheet::clone(&doc.styles); + // As for Word 97 files: the text read can't exceed twice the stream, nor the absolute ceiling. + let budget = std::cell::Cell::new((word.len() as u64).saturating_mul(2).min(MAX_TOTAL_CHARS)); + let work = Work::new(MAX_WORK); + let paragraphs = ParaBudget { left: std::cell::Cell::new(max_paragraphs), exceeded: std::cell::Cell::new(false) }; + let mut pics = media::Pictures::for_input(word.len()); + let ctx = WalkCtx { + word, + data: &[], + pieces: &content.pieces, + chpx_bins: &content.chpx, + papx_bins: &content.papx, + fonts: &content.fonts, + raw_styles: &content.styles, + sheet: &sheet, + notes: &[], + marks: &[], + drawn: &[], + sect_ends: &[], + budget: &budget, + paragraphs: ¶graphs, + work: &work, + }; + let paras = walk(&ctx, 0, fib.ccp_text, &mut pics); + if paragraphs.exceeded.get() { + return Err(paragraph_limit(max_paragraphs)); + } + doc.body = table::assemble(paras); + doc.ensure_nonempty(); + work.log(); + Ok(doc) +} + fn paragraph_limit(max_paragraphs: usize) -> DocbinError { DocbinError::Limit(format!("the document has more than {max_paragraphs} paragraphs and table cells")) } @@ -648,6 +704,20 @@ fn walk<'a>(ctx: &WalkCtx<'a>, cp_start: u32, cp_end: u32, pics: &mut media::Pic // querying at the mark's own FC finds that paragraph's properties. let fc_mark = ctx.pieces.fc_of_cp(cp).unwrap_or(0); let (istd, papx) = ctx.papx_bins.papx(ctx.word, fc_mark); + // The Prm of the piece holding the mark adds its paragraph sprms after the PAPX's + // ([MS-DOC] §2.4.6.1, step 5), as Word 6/95's fast saves record a paragraph change. + let extra = prm_paragraph_sprms(ctx.pieces.piece_prm(cp), ctx.work); + let combined; + let papx: &[u8] = if extra.is_empty() { + papx + } else { + // Re-framed from its Prls, so that a pad byte at its end can't swallow the + // first appended opcode. + let mut v: Vec = sprm::iter(papx).flat_map(|p| p.op.to_le_bytes().into_iter().chain(p.operand.iter().copied())).collect(); + v.extend_from_slice(&extra); + combined = v; + &combined + }; if let Some(st) = ctx.raw_styles.get(istd as usize).filter(|s| !s.name.is_empty()) { pb.props.style = Some(fmt::style_id(&st.name)); } @@ -991,13 +1061,42 @@ struct FmtState<'a> { /// paragraph style stay the same, so a Prm grpprl (up to 64 KB) is interpreted once per /// formatting change, not once per character (#3692). struct FmtMemo<'a> { - /// The CHPX grpprl, compared by address: it is a slice of the WordDocument stream. + /// The CHPX grpprl, compared by address: a slice of the WordDocument stream, or of a Word 6.0/95 + /// file's translated runs, both of which stay put for the walk. chpx: &'a [u8], prm: u16, style: Option, props: CharProps, } +/// The paragraph and table sprms (sgc 1 and 5) of a piece's Prm, as Prls to append to a +/// paragraph's PAPX: a Prm0's single sprm, or those of the Prm1's grpprl. A Prm1 grpprl is +/// charged to `work`, as for [`apply_prm`]. +fn prm_paragraph_sprms(prm: PrmRef<'_>, work: &Work) -> Vec { + let mut out = Vec::new(); + match prm { + PrmRef::Sprm0 { isprm, val } => { + if let Some(op) = sprm::from_prm0(isprm) + && matches!(Prl { op, operand: &[] }.sgc(), 1 | 5) + { + out.extend_from_slice(&op.to_le_bytes()); + out.push(val); + } + } + PrmRef::Grpprl(Some(g)) => { + if !work.charge(g.len() as u64, Cost::Formatting) { + return out; + } + for prl in sprm::iter(g).filter(|p| matches!(p.sgc(), 1 | 5)) { + out.extend_from_slice(&prl.op.to_le_bytes()); + out.extend_from_slice(prl.operand); + } + } + PrmRef::None | PrmRef::Grpprl(None) => {} + } + out +} + /// Apply a piece's Prm (Prm0 short sprm or Prm1 grpprl) to character properties. A Prm1 /// grpprl is charged to `work`; once that is spent the grpprl is skipped. fn apply_prm(props: &mut CharProps, prm: PrmRef<'_>, fonts: &[String], base: &CharProps, work: &Work) { diff --git a/crates/doc-binary/src/piece.rs b/crates/doc-binary/src/piece.rs index 5f36a8198..701a4bc67 100644 --- a/crates/doc-binary/src/piece.rs +++ b/crates/doc-binary/src/piece.rs @@ -1,20 +1,71 @@ //! The piece table ([MS-DOC] `Clx`/`Pcdt`/`PlcPcd`): where every character position lives in //! the WordDocument stream, and how it is encoded. +//! +//! Word 6.0/95 files ([`crate::word6`]) keep the same `Clx` shape, but every piece's text is at a +//! plain byte offset: 8-bit text in the code page of its piece's or run's font (or the document's), +//! or UTF-16 in a file with the FIB's fExtChar flag. -use craft_codepage::cp1252; +use craft_codepage::{code_page_byte, cp1252, is_byte_code_page}; use crate::DocbinError; /// Most pieces any real file has; more means a corrupt `PlcPcd`. const MAX_PIECES: usize = 1_000_000; -/// One piece: text at FcCompressed `fc` (30-bit offset + compression bit). +/// How a piece's characters are stored. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Text { + /// UTF-16LE at `fc`. + Utf16, + /// Windows-1252, one byte per character at `fc / 2` (Word 97 FcCompressed). + Compressed, + /// One byte per character at `fc` itself, in the code page [`PieceTable::code_page_at`] gives + /// that byte (Word 6.0/95). + Bytes, +} + +/// One piece: its text at `fc` (for Word 97, the 30-bit offset of FcCompressed). #[derive(Clone, Copy, Debug)] struct Pcd { fc: u32, - compressed: bool, - /// `Prm`: either a single sprm (Prm0) or an index into the Clx's Prc grpprls (Prm1). + text: Text, + /// `Prm`: either a single sprm (Prm0) or an index into the Clx's Prc grpprls (Prm1). In a Word + /// 6.0/95 table the Prcs hold translated grpprls ([`PieceTable::parse_word6`]), and a Prm0's + /// isprm is already the opcode [MS-DOC]'s isprm table maps. prm: u16, + /// For a Word 6.0/95 [`Text::Bytes`] piece whose Prm names a font: that font's code page, + /// which outranks the runs' ([`PieceTable::code_page_at`]). + code_page: Option, +} + +impl Pcd { + /// The byte offset of the character `step / 2` characters into the piece. `step` is twice + /// the CP offset, so one formula serves all three encodings. + fn fc_at(&self, step: u32) -> Option { + match self.text { + Text::Utf16 => self.fc.checked_add(step), + Text::Compressed => self.fc.checked_add(step)?.checked_div(2), + Text::Bytes => self.fc.checked_add(step / 2), + } + } +} + +/// The code page of the 8-bit text in the byte range `[lo, hi)` of the WordDocument stream. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct CodePageRun { + pub(crate) lo: u32, + pub(crate) hi: u32, + pub(crate) code_page: u16, +} + +/// How a Word 6.0/95 file's text is stored and decoded ([`crate::word6`]). +pub(crate) struct Word6Text { + /// UTF-16 rather than 8-bit (the FIB's fExtChar flag). + pub(crate) wide: bool, + /// The code page of 8-bit text that no piece or run gives one for. + pub(crate) default_code_page: u16, + /// The code page of each byte range, from its run's font (sorted by `lo`, not overlapping). + pub(crate) code_pages: Vec, } /// The parsed piece table plus the grpprls of the Prcs that Prm1 references. @@ -23,11 +74,58 @@ pub(crate) struct PieceTable { cps: Vec, pieces: Vec, prc_grpprls: Vec>, + /// For [`Text::Bytes`] pieces: the code page of each byte range, sorted by `lo`, not + /// overlapping. Bytes outside every range are in `default_code_page`. + code_pages: Vec, + default_code_page: u16, } impl PieceTable { /// Parse the `Clx` at `table[fc .. fc+lcb]`. pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result { + Self::parse_clx(table, fc, lcb, None) + } + + /// Parse a Word 6.0/95 `Clx` at `word[fc .. fc+lcb]`: the Word 97 shape, but every piece's text + /// is at its plain byte offset. `piece_code_page` gives the code page a piece's raw Prm + /// imposes (with the Clx's raw Prc grpprls to look Prm1 indices up in), if any; then each Prc + /// grpprl is replaced by `translate_prc`'s Word 97 sprms, which the walk applies to the piece. + pub(crate) fn parse_word6( + word: &[u8], + fc: u32, + lcb: u32, + text: Word6Text, + piece_code_page: impl Fn(u16, &[Vec]) -> Option, + translate_prc: impl Fn(&[u8]) -> Vec, + ) -> Result { + let mut t = Self::parse_clx(word, fc, lcb, Some(text.wide))?; + if !text.wide { + for p in &mut t.pieces { + p.code_page = piece_code_page(p.prm, &t.prc_grpprls); + } + } + t.prc_grpprls = t.prc_grpprls.iter().map(|g| translate_prc(g)).collect(); + t.code_pages = text.code_pages; + t.default_code_page = text.default_code_page; + Ok(t) + } + + /// One Word 6.0/95 piece: `ccp` characters from byte `fc` on. This covers a file that was not + /// fast-saved, which has no `Clx`. + pub(crate) fn contiguous_word6(fc: u32, ccp: u32, text: Word6Text) -> PieceTable { + let kind = if text.wide { Text::Utf16 } else { Text::Bytes }; + PieceTable { + cps: vec![0, ccp], + pieces: vec![Pcd { fc, text: kind, prm: 0, code_page: None }], + prc_grpprls: Vec::new(), + code_pages: text.code_pages, + default_code_page: text.default_code_page, + } + } + + /// `word6`: `None` for Word 97 and later, `Some(wide)` for a Word 6.0/95 file (whose raw Prms + /// and Prcs are kept for [`PieceTable::parse_word6`]). + fn parse_clx(table: &[u8], fc: u32, lcb: u32, word6: Option) -> Result { let fc = fc as usize; let lcb = lcb as usize; if lcb == 0 { @@ -95,9 +193,26 @@ impl PieceTable { return Err(DocbinError::Malformed("truncated aPcd".into())); }; let prm = plc.get(at + 4..at + 6).map(|b| u16::from_le_bytes([b[0], b[1]])).unwrap_or(0); - pieces.push(Pcd { fc: fc_raw & 0x3FFF_FFFF, compressed: fc_raw & 0x4000_0000 != 0, prm }); + pieces.push(match word6 { + // A plain byte offset, with no compression bit: 8-bit text, or UTF-16 in a file with + // fExtChar. The raw Prm is kept for `parse_word6`. + Some(wide) => Pcd { fc: fc_raw, text: if wide { Text::Utf16 } else { Text::Bytes }, prm, code_page: None }, + None => { + let text = if fc_raw & 0x4000_0000 != 0 { Text::Compressed } else { Text::Utf16 }; + Pcd { fc: fc_raw & 0x3FFF_FFFF, text, prm, code_page: None } + } + }); + } + Ok(PieceTable { cps, pieces, prc_grpprls, code_pages: Vec::new(), default_code_page: 1252 }) + } + + /// The code page of the 8-bit text byte at `fc` (in [`Text::Bytes`] pieces). + fn code_page_at(&self, fc: u32) -> u16 { + let i = self.code_pages.partition_point(|r| r.lo <= fc); + match i.checked_sub(1).and_then(|i| self.code_pages.get(i)) { + Some(r) if fc < r.hi => r.code_page, + _ => self.default_code_page, } - Ok(PieceTable { cps, pieces, prc_grpprls }) } /// The Prls this piece's `Prm` adds. Bit 0 (`fComplex`) discriminates: a Prm0 @@ -133,8 +248,7 @@ impl PieceTable { let p = self.piece_of(cp)?; let i = self.cps.partition_point(|&c| c <= cp).checked_sub(1)?; let cp0 = *self.cps.get(i)?; - let step = cp.checked_sub(cp0)?.checked_mul(2)?; - if p.compressed { p.fc.checked_add(step)?.checked_div(2) } else { p.fc.checked_add(step) } + p.fc_at(cp.checked_sub(cp0)?.checked_mul(2)?) } /// The piece holding `cp`, with the CP range it covers: for every CP in that range the @@ -167,13 +281,24 @@ impl PieceTable { let (Some(p), Some(&cp0)) = (self.pieces.get(i), self.cps.get(i)) else { return Err(u32::MAX) }; let Some(off) = cp.checked_sub(cp0) else { return Err(next) }; let off = off as usize; - if p.compressed { - // 8-bit, Windows-1252, one byte per character, stored at fc/2. - let at = ((p.fc / 2) as usize).checked_add(off); - return match at.and_then(|a| word.get(a)) { - Some(&b) => Ok((cp1252(b), 1)), - None => Err(next), - }; + match p.text { + Text::Compressed => { + // 8-bit, Windows-1252, one byte per character, stored at fc/2. + let at = ((p.fc / 2) as usize).checked_add(off); + return match at.and_then(|a| word.get(a)) { + Some(&b) => Ok((cp1252(b), 1)), + None => Err(next), + }; + } + Text::Bytes => { + // 8-bit, one byte per character at fc, in its run's code page. + let at = (p.fc as usize).checked_add(off); + return match at.and_then(|a| Some((u32::try_from(a).ok()?, *word.get(a)?))) { + Some((a, b)) => Ok((byte_char(p.code_page.unwrap_or_else(|| self.code_page_at(a)), b), 1)), + None => Err(next), + }; + } + Text::Utf16 => {} } // UTF-16LE, one 16-bit unit per character, stored at fc. let unit = |k: usize| -> Option { @@ -207,8 +332,7 @@ impl PieceSpan<'_> { /// [`PieceTable::fc_of_cp`] for a CP inside the span. pub(crate) fn fc_at(&self, cp: u32) -> Option { - let step = cp.checked_sub(self.cp_lo)?.checked_mul(2)?; - if self.pcd.compressed { self.pcd.fc.checked_add(step)?.checked_div(2) } else { self.pcd.fc.checked_add(step) } + self.pcd.fc_at(cp.checked_sub(self.cp_lo)?.checked_mul(2)?) } /// The raw Prm of the piece: two CPs with the same value get the same [`PrmRef`]. @@ -228,3 +352,23 @@ pub(crate) enum PrmRef<'a> { /// Prm1: a grpprl from a Prc (absent if out of range). Grpprl(Option<&'a [u8]>), } + +/// Windows' code page number for symbol fonts (CP_SYMBOL). +pub(crate) const SYMBOL_CODE_PAGE: u16 = 42; + +/// One byte of 8-bit text in `code_page`. The East Asian code pages store a character as a lead +/// and a trail byte, which one CP per byte can't represent, so their bytes above ASCII read as +/// U+FFFD rather than as unrelated Windows-1252 letters. +fn byte_char(code_page: u16, b: u8) -> char { + if code_page == SYMBOL_CODE_PAGE { + // Each character from the space up to its private-use code point, as Word reads a document + // marked as Symbol; control characters (paragraph marks, fields) stay themselves. + if b < 0x20 { char::from(b) } else { char::from_u32(0xF000 + u32::from(b)).unwrap_or('\u{FFFD}') } + } else if is_byte_code_page(code_page) { + code_page_byte(code_page, b) + } else if b.is_ascii() { + char::from(b) + } else { + '\u{FFFD}' + } +} diff --git a/crates/doc-binary/src/tests.rs b/crates/doc-binary/src/tests.rs index 80cef3257..ec5650695 100644 --- a/crates/doc-binary/src/tests.rs +++ b/crates/doc-binary/src/tests.rs @@ -10,6 +10,7 @@ use super::read; mod drawing; mod encrypted; mod metadata; +mod word6; /// Offset in the WordDocument stream where test text pieces are placed (past the FIB). const TEXT_FC: u32 = 0x600; @@ -176,12 +177,15 @@ fn wrong_magic_rejected() { } #[test] -fn word_6_95_rejected() { - let mut fib = fib_bytes(&FibSpec::default()); +fn word_6_95_magic_goes_to_the_word6_reader() { + // A Word 6.0/95 signature is no longer refused: the stream is read as that version (here an + // empty document, since a Word 97 FIB holds no Word 6 text length). The flags are cleared: + // the Word 97 default sets fExtChar, which the Word 6 reader refuses. + let mut fib = fib_bytes(&FibSpec { flags: 0, ..FibSpec::default() }); fib[0] = 0xDC; fib[1] = 0xA5; let f = cfb_file(&[("WordDocument", &fib)]); - assert!(matches!(read(&f), Err(super::DocbinError::NotWord(m)) if m.contains("6.0/95"))); + assert!(read(&f).is_ok()); } #[test] @@ -882,8 +886,6 @@ fn corpus_files_open() { let bytes = std::fs::read(&p).expect("read"); let doc = match super::read(&bytes) { Ok(d) => d, - // Word 6/95 files are a documented, intentional rejection. - Err(super::DocbinError::NotWord(m)) if m.contains("6.0/95") => continue, Err(e) => panic!("{}: {e}", p.display()), }; assert!(!doc.styles.styles.is_empty(), "{}: no styles", p.display()); @@ -2106,6 +2108,29 @@ fn one_section(text: &'static str, sepx: Vec, papx_entries: Vec<(u32, u16, V } } +#[test] +fn piece_prm_paragraph_formatting_applies_to_the_marks_paragraph() { + // [MS-DOC] §2.4.6.1 step 5: the Prm of the piece holding the paragraph mark adds its paragraph + // sprms after the PAPX's. Prm1 -> a Prc with sprmPDxaLeft80 (1440 twips) and sprmPJc80 + // (centred); Prm0 isprm 0x05 (sprmPJc) with operand 2 (right). + let prcs = vec![grpprl(&[(0x840F, &1440i16.to_le_bytes()), (0x2403, &[0x01])])]; + let para = |prm: u16| { + let spec = RichSpec { + text: "Text\r", + styles: vec![(1, 0x0FFF, "Normal", Vec::new(), Vec::new())], + fonts: vec!["Times New Roman"], + chpx_runs: vec![(0, Vec::new())], + papx_entries: vec![(4, 0, grpprl(&[(0x840F, &360i16.to_le_bytes())]))], + }; + let doc = read(&rich_doc_with(&spec, &RichExtra { prcs: prcs.clone(), prm, ..Default::default() })).expect("opens"); + let p = para0(&doc); + (p.props.indent_left, p.props.align) + }; + assert_eq!(para(0x0000), (Some(18.0), None), "no Prm: the PAPX's indent"); + assert_eq!(para(0x0001), (Some(72.0), Some(craft_wordmodel::props::Align::Center)), "Prm1: the Prc's sprms override the PAPX's"); + assert_eq!(para(0x020A), (Some(18.0), Some(craft_wordmodel::props::Align::Right)), "Prm0: sprmPJc right"); +} + #[test] fn piece_prm_character_formatting_applied() { // #458. Bit 0 of a Prm is fComplex ([MS-DOC] §2.9.215/§2.9.216): Prm0 = isprm in bits diff --git a/crates/doc-binary/src/tests/word6.rs b/crates/doc-binary/src/tests/word6.rs new file mode 100644 index 000000000..fa3f68a51 --- /dev/null +++ b/crates/doc-binary/src/tests/word6.rs @@ -0,0 +1,747 @@ +//! Word 6.0/95 fixtures, built in code. No public specification describes this version; these +//! build the layout observed in real files and described in `crate::word6`. + +use proptest::prelude::*; + +use super::{body_texts, cfb_file}; +use crate::{DocbinError, read}; + +/// Where the text starts: right after the FIB, as in every observed file. +const TEXT_AT: u32 = 0x300; + +/// One stylesheet entry as Word 6/95 stores it. +#[derive(Clone, Copy, Default)] +struct Std<'a> { + /// The built-in style id, or 0x0FFE for a user-defined style. + sti: u16, + /// 1 paragraph, 2 character. + sgc: u16, + /// The base style's index, or 0x0FFF. + base: u16, + name: &'a str, + /// Paragraph sprms (paragraph styles only). + papx: &'a [u8], + /// Character sprms. + chpx: &'a [u8], +} + +/// The stylesheet bytes for `styles`: the 14-byte header (count, fixed-part size 8, …), then per +/// style a size and the entry, or 0 for an empty slot. +fn stylesheet(styles: &[Option]) -> Vec { + let mut v = vec![14u8, 0]; + for w in [styles.len() as u16, 8, 1, 0x4B, 0x0F, 0, 0] { + v.extend_from_slice(&w.to_le_bytes()); + } + for (istd, st) in styles.iter().enumerate() { + let Some(st) = st else { + v.extend_from_slice(&[0, 0]); + continue; + }; + let cupx: u16 = if st.sgc == 1 { 2 } else { 1 }; + let mut e = Vec::new(); + for w in [st.sti, st.sgc | st.base << 4, cupx, 0] { + e.extend_from_slice(&w.to_le_bytes()); + } + e.push(st.name.len() as u8); + e.extend_from_slice(st.name.as_bytes()); + e.push(0); + let upx = |e: &mut Vec, bytes: &[u8]| { + if e.len() % 2 == 1 { + e.push(0); + } + e.extend_from_slice(&(bytes.len() as u16).to_le_bytes()); + e.extend_from_slice(bytes); + }; + if st.sgc == 1 { + let mut papx = (istd as u16).to_le_bytes().to_vec(); + papx.extend_from_slice(st.papx); + upx(&mut e, &papx); + } + upx(&mut e, st.chpx); + v.extend_from_slice(&(e.len() as u16).to_le_bytes()); + v.extend_from_slice(&e); + } + v +} + +/// What a test Word 6.0/95 file holds. Offsets in `runs` and `pieces` are into `text`. +#[derive(Clone, Default)] +struct Doc6<'a> { + nfib: u16, + flags: u16, + /// The stored 8-bit text. + text: &'a [u8], + /// (charset, name) per font index. + fonts: &'a [(u8, &'a str)], + /// The font table's entries as raw bytes instead of `fonts` (the size word is added). + raw_fonts: Option<&'a [u8]>, + /// Contiguous character runs (lo, hi, grpprl), all in one FKP page. + runs: &'a [(u32, u32, &'a [u8])], + /// Contiguous paragraph runs (lo, hi, grpprl), style 0, all in one FKP page. Each covers the + /// paragraph whose mark lies in it. + paras: &'a [(u32, u32, &'a [u8])], + /// For a fast-saved file: (length, offset) per piece, in CP order. + pieces: Option<&'a [(u32, u32)]>, + /// Each piece's Prm (0 when absent or shorter than `pieces`). + prms: &'a [u16], + /// The Clx's Prc grpprls, which a Prm1 indexes. + prcs: &'a [&'a [u8]], + /// The FIB's character set word at 0x14. + chse: u16, + /// The style of each paragraph run (0, Normal, when absent or shorter than `paras`). + para_styles: &'a [u16], + /// The stylesheet: one entry per style index, `None` for an empty slot. + styles: &'a [Option>], + /// The main text's length in characters, when it isn't the stored bytes' (16-bit text). + ccp: Option, +} + +fn put16(v: &mut [u8], at: usize, x: u16) { + v[at..at + 2].copy_from_slice(&x.to_le_bytes()); +} + +fn put32(v: &mut [u8], at: usize, x: u32) { + v[at..at + 4].copy_from_slice(&x.to_le_bytes()); +} + +/// Append one FKP page for `runs` and its bin table, and return the bin table's (fc, lcb). A +/// character page has a 1-byte entry per run and CHPXs (byte count + grpprl); a paragraph page +/// has 7-byte entries and PAPXs (word count + style 0 + grpprl padded to whole words). +fn fkp(w: &mut Vec, runs: &[(u32, u32, &[u8])], papx: bool, istds: &[u16]) -> (u32, u32) { + let (Some(first), Some(last)) = (runs.first(), runs.last()) else { return (0, 0) }; + w.resize(w.len().div_ceil(512) * 512, 0); + let pn = (w.len() / 512) as u16; + let crun = runs.len(); + let entry = if papx { 7 } else { 1 }; + let mut page = [0u8; 512]; + for (k, (lo, _, _)) in runs.iter().enumerate() { + put32(&mut page, 4 * k, TEXT_AT + lo); + } + put32(&mut page, 4 * crun, TEXT_AT + last.1); + // Records from the end of the page down, each at an even offset. + let mut top = 511usize; + for (k, (_, _, g)) in runs.iter().enumerate() { + let body: Vec = if papx { + let mut b = istds.get(k).copied().unwrap_or(0).to_le_bytes().to_vec(); + b.extend_from_slice(g); + if b.len() % 2 == 1 { + b.push(0); + } + b + } else if g.is_empty() { + continue; + } else { + g.to_vec() + }; + let at = (top - 1 - body.len()) & !1; + page[at] = if papx { (body.len() / 2) as u8 } else { body.len() as u8 }; + page[at + 1..at + 1 + body.len()].copy_from_slice(&body); + page[4 * (crun + 1) + entry * k] = (at / 2) as u8; + top = at; + } + page[511] = crun as u8; + w.extend_from_slice(&page); + let mut bte = Vec::new(); + bte.extend_from_slice(&(TEXT_AT + first.0).to_le_bytes()); + bte.extend_from_slice(&(TEXT_AT + last.1).to_le_bytes()); + bte.extend_from_slice(&pn.to_le_bytes()); + let at = w.len() as u32; + w.extend_from_slice(&bte); + (at, bte.len() as u32) +} + +/// The WordDocument stream: FIB, text, then the FKP pages, font table and piece table. +fn word_stream(d: &Doc6) -> Vec { + let mut w = vec![0u8; TEXT_AT as usize]; + w.extend_from_slice(d.text); + let ccp = match (d.ccp, d.pieces) { + (Some(ccp), _) => ccp, + (None, pieces) => match pieces { + Some(p) => p.iter().map(|(len, _)| len).sum(), + None => d.text.len() as u32, + }, + }; + let mut pairs: Vec<(usize, u32, u32)> = Vec::new(); + for (pair, runs, papx) in [(12, d.runs, false), (13, d.paras, true)] { + let (fc, lcb) = fkp(&mut w, runs, papx, d.para_styles); + if lcb > 0 { + pairs.push((pair, fc, lcb)); + } + } + if !d.styles.is_empty() { + let st = stylesheet(d.styles); + pairs.push((1, w.len() as u32, st.len() as u32)); + w.extend_from_slice(&st); + } + if !d.fonts.is_empty() || d.raw_fonts.is_some() { + let mut ffn = vec![0u8, 0]; + ffn.extend_from_slice(d.raw_fonts.unwrap_or_default()); + for (charset, name) in d.fonts { + let mut e = vec![0u8, 0x16, 0x90, 0x01, *charset, 0x00]; + e.extend_from_slice(name.as_bytes()); + e.push(0); + e[0] = (e.len() - 1) as u8; + ffn.extend_from_slice(&e); + } + let size = ffn.len() as u16; + put16(&mut ffn, 0, size); + pairs.push((15, w.len() as u32, ffn.len() as u32)); + w.extend_from_slice(&ffn); + } + if let Some(pieces) = d.pieces { + let mut plc = Vec::new(); + let mut cp = 0u32; + plc.extend_from_slice(&cp.to_le_bytes()); + for (len, _) in pieces { + cp += len; + plc.extend_from_slice(&cp.to_le_bytes()); + } + for (i, (_, off)) in pieces.iter().enumerate() { + plc.extend_from_slice(&[0, 0]); + plc.extend_from_slice(&(TEXT_AT + off).to_le_bytes()); + plc.extend_from_slice(&d.prms.get(i).copied().unwrap_or(0).to_le_bytes()); + } + let mut clx = Vec::new(); + for g in d.prcs { + clx.push(0x01); + clx.extend_from_slice(&(g.len() as u16).to_le_bytes()); + clx.extend_from_slice(g); + } + clx.push(0x02); + clx.extend_from_slice(&(plc.len() as u32).to_le_bytes()); + clx.extend_from_slice(&plc); + pairs.push((33, w.len() as u32, clx.len() as u32)); + w.extend_from_slice(&clx); + } + put16(&mut w, 0x00, 0xA5DC); + put16(&mut w, 0x02, if d.nfib == 0 { 0x0065 } else { d.nfib }); + put16(&mut w, 0x06, 0x0409); + put16(&mut w, 0x0A, d.flags | if d.pieces.is_some() { 0x0004 } else { 0 }); + put16(&mut w, 0x0C, 0x0065); + put16(&mut w, 0x14, d.chse); + put32(&mut w, 0x18, TEXT_AT); + put32(&mut w, 0x1C, TEXT_AT + d.text.len() as u32); + let len = w.len() as u32; + put32(&mut w, 0x20, len); + put32(&mut w, 0x34, ccp); + for (i, fc, lcb) in pairs { + put32(&mut w, 0x58 + i * 8, fc); + put32(&mut w, 0x58 + i * 8 + 4, lcb); + } + w +} + +/// A Word 6.0/95 file holding `d`: the WordDocument stream only, as the real ones have no Table +/// stream. +fn word6_file(d: &Doc6) -> Vec { + cfb_file(&[("WordDocument", &word_stream(d))]) +} + +fn texts(d: &Doc6) -> Vec { + body_texts(&read(&word6_file(d)).expect("a Word 6.0/95 file opens")) +} + +/// Fonts 0 (Western) and 1 (Cyrillic, charset 204), as the Russian files have. +const FONTS: &[(u8, &str)] = &[(0, "Times New Roman"), (204, "Times New Roman Cyr")]; + +#[test] +fn word_6_and_95_files_open_as_paragraphs() { + for nfib in [0x0065, 0x0068] { + let d = Doc6 { nfib, text: b"Hello\rWorld\r", ..Default::default() }; + assert_eq!(texts(&d), ["Hello", "World"], "nFib 0x{nfib:04X}"); + } +} + +#[test] +fn fast_saved_text_follows_the_piece_table() { + // Stored out of order; the pieces' fcs are plain byte offsets (Word 97 would halve them). + let d = Doc6 { text: b"World\rHello\r", pieces: Some(&[(6, 6), (6, 0)]), ..Default::default() }; + assert_eq!(texts(&d), ["Hello", "World"]); +} + +#[test] +fn fast_saved_file_without_a_piece_table_is_malformed() { + let d = Doc6 { flags: 0x0004, text: b"Hello\r", ..Default::default() }; + assert!(matches!(read(&word6_file(&d)), Err(DocbinError::Malformed(_)))); +} + +#[test] +fn a_runs_font_charset_chooses_its_code_page() { + // "Da " in font 0, then 0xC4 0xE0 ("Да" in Windows-1251) in the Cyrillic font 1. + let text = b"Da \xC4\xE0\r"; + let runs: &[(u32, u32, &[u8])] = &[(0, 3, &[]), (3, 5, &[0x5D, 0x01, 0x00]), (5, 6, &[])]; + let d = Doc6 { text, fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Da Да"]); +} + +/// Text in an East Asian code page (a Japanese font, charset 128: Shift-JIS) is refused, not +/// read a byte at a time into replacement characters (review of wordcraft#6345). +#[test] +fn east_asian_text_is_refused_not_lost() { + let fonts: &[(u8, &str)] = &[(0, "Times New Roman"), (128, "MS Mincho")]; + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &[0x5D, 0x01, 0x00]), (2, 3, &[])]; + let d = Doc6 { text: b"\x93\xfa\r", fonts, runs, ..Default::default() }; + assert!(matches!(read(&word6_file(&d)), Err(DocbinError::NotWord(e)) if e.contains("East Asian"))); + // The same file in a Western font still opens. + let d = Doc6 { text: b"\x93\xfa\r", fonts, runs: &[], ..Default::default() }; + assert_eq!(texts(&d).len(), 1); +} + +#[test] +fn the_font_sprm_is_found_after_other_sprms() { + // As in real files: bold-like toggles, a size, a picture anchor's length-prefixed sprm. + let text = b"\xC4\xE0\r"; + for g in [&[0x55, 0x81, 0x63, 0x18, 0x00, 0x5D, 0x01, 0x00][..], &[0x75, 0x01, 0x44, 0x04, 0, 0, 0, 0, 0x5D, 0x01, 0x00][..]] { + let runs: &[(u32, u32, &[u8])] = &[(0, 2, g), (2, 3, &[])]; + let d = Doc6 { text, fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Да"], "grpprl {g:02X?}"); + } +} + +#[test] +fn the_last_font_sprm_of_a_run_chooses_its_code_page() { + // Font 0, then font 1 (Cyrillic): the later sprm is the one the formatting applies. + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &[0x5D, 0x00, 0x00, 0x5D, 0x01, 0x00]), (2, 3, &[])]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Да"]); +} + +#[test] +fn an_unknown_sprm_leaves_font_0() { + // 0x99 has no known operand length, so the rest can't be framed: font 0 (Windows-1252). + let text = b"\xC4\xE0\r"; + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &[0x99, 0x5D, 0x01, 0x00]), (2, 3, &[])]; + let d = Doc6 { text, fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Äà"]); +} + +#[test] +fn the_toggle_sprms_before_the_font_are_framed() { + // 0x57 (strike, a one-byte toggle in [MS-DOC]'s Prm0 isprm table) before the font sprm: the + // font must still be found, or the Cyrillic text reads as Windows-1252. + let text = b"\xC4\xE0\r"; + for op in [0x57, 0x58, 0x59, 0x5C] { + let g = [op, 0x01, 0x5D, 0x01, 0x00]; + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &g), (2, 3, &[])]; + let d = Doc6 { text, fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Да"], "opcode 0x{op:02X}"); + } +} + +#[test] +fn a_font_entry_too_short_for_its_charset_ends_the_font_table() { + // Entry 0 says it is 3 bytes long, which can't hold the charset at offset 4. The bytes after + // it (the next entry, whose flags byte is 0xCC) must not be read as font 0's charset. + let raw: &[u8] = &[0x02, 0x16, 0x90, 0x05, 0xCC, 0x90, 0x01, 0xCC, 0x00, b'X', 0]; + let d = Doc6 { text: b"\xC4\xE0\r", raw_fonts: Some(raw), runs: &[(0, 3, &[])], ..Default::default() }; + assert_eq!(texts(&d), ["Äà"], "font 0 has no charset: Windows-1252"); +} + +#[test] +fn a_bin_table_naming_one_page_many_times_reads_it_once() { + // A hostile bin table: 1,000,000 entries, all naming one page of 50 Cyrillic runs. The text still + // reads right; that the page is read once is pinned in `word6::tests`. + let text: Vec = std::iter::repeat_n(0xC4u8, 50).chain(*b"\r").collect(); + let g: &[u8] = &[0x5D, 0x01, 0x00]; + let runs: Vec<(u32, u32, &[u8])> = (0..50).map(|i| (i, i + 1, g)).chain([(50, 51, &[][..])]).collect(); + let mut w = word_stream(&Doc6 { text: &text, fonts: FONTS, runs: &runs, ..Default::default() }); + let u32_at = |w: &[u8], at: usize| u32::from_le_bytes([w[at], w[at + 1], w[at + 2], w[at + 3]]); + let bte_fc = u32_at(&w, 0x58 + 12 * 8) as usize; + let pn = u16::from_le_bytes([w[bte_fc + 8], w[bte_fc + 9]]); + let n = 1_000_000usize; + let mut bte = Vec::with_capacity(4 * (n + 1) + 2 * n); + bte.extend_from_slice(&TEXT_AT.to_le_bytes()); + for _ in 0..n { + bte.extend_from_slice(&(TEXT_AT + 51).to_le_bytes()); + } + for _ in 0..n { + bte.extend_from_slice(&pn.to_le_bytes()); + } + let at = w.len() as u32; + w.extend_from_slice(&bte); + put32(&mut w, 0x58 + 12 * 8, at); + put32(&mut w, 0x58 + 12 * 8 + 4, bte.len() as u32); + let doc = read(&cfb_file(&[("WordDocument", &w)])).expect("opens"); + assert_eq!(body_texts(&doc), ["Д".repeat(50)]); +} + +/// `s` as UTF-16LE bytes. +fn utf16(s: &str) -> Vec { + s.encode_utf16().flat_map(u16::to_le_bytes).collect() +} + +#[test] +fn a_file_with_extended_characters_holds_utf16_text() { + // fExtChar (0x1000): Word reads the text as 16-bit units. + let text = utf16("Да ok\r"); + let d = Doc6 { flags: 0x1000, text: &text, ccp: Some(6), ..Default::default() }; + assert_eq!(texts(&d), ["Да ok"]); +} + +#[test] +fn utf16_text_stops_at_the_end_of_its_bytes() { + // Word reads no more 16-bit characters than the text's byte range (0x18..0x1C) holds, even + // when the character count says more. + let text = utf16("Hi\r"); + let d = Doc6 { flags: 0x1000, text: &text, ccp: Some(50), ..Default::default() }; + assert_eq!(texts(&d), ["Hi"]); +} + +#[test] +fn text_stops_at_the_end_of_its_bytes() { + // The same for 8-bit text: Word read 19 characters of a file whose count said 40. The font + // table after the text must not be read as body text. + let d = Doc6 { text: b"Hi\r", ccp: Some(50), fonts: FONTS, ..Default::default() }; + assert_eq!(texts(&d), ["Hi"]); +} + +#[test] +fn fast_saved_utf16_pieces_are_at_plain_byte_offsets() { + let text = utf16("World\rHello\r"); + let d = Doc6 { flags: 0x1000, text: &text, pieces: Some(&[(6, 12), (6, 0)]), ..Default::default() }; + assert_eq!(texts(&d), ["Hello", "World"]); +} + +#[test] +fn a_macintosh_document_reads_as_mac_roman() { + // FIB 0x14 = 0x0100: byte 0x8E is "é" (Mac Roman), not "Ž" (Windows-1252), even in a run whose + // font is Cyrillic. + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &[0x5D, 0x01, 0x00]), (2, 3, &[])]; + let d = Doc6 { chse: 0x0100, text: b"H\x8E\r", fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Hé"]); +} + +#[test] +fn a_symbol_document_maps_characters_to_private_use() { + // FIB 0x14 = 0x0002: every character from the space up is U+F000 + byte; marks stay marks. + let d = Doc6 { chse: 0x0002, text: b"Hi\x8E\rA\r", ..Default::default() }; + assert_eq!(texts(&d), ["\u{F048}\u{F069}\u{F08E}", "\u{F041}"]); +} + +#[test] +fn another_character_set_leaves_only_ascii_readable() { + let d = Doc6 { chse: 0x0001, text: b"H\x8Ei\r", ..Default::default() }; + assert_eq!(texts(&d), ["H\u{FFFD}i"]); +} + +#[test] +fn a_prm_on_the_marks_piece_formats_its_paragraph() { + // As Word 95 fast-saves a 1" left indent on the first paragraph: the piece holding its mark + // has Prm1 -> Prc `11 a0 05` (left indent 1440), and its PAPX says nothing. Word shows 72 pt; + // the second paragraph keeps none. + let text = b"First\rSecond\r"; + let pieces: &[(u32, u32)] = &[(5, 0), (1, 5), (7, 6)]; + let d = Doc6 { text, pieces: Some(pieces), prms: &[0, 0x0001], prcs: &[&[0x11, 0xA0, 0x05]], ..Default::default() }; + let doc = read(&word6_file(&d)).expect("opens"); + let paras: Vec<_> = doc.body.iter().filter_map(|b| b.as_para()).collect(); + assert_eq!(paras.iter().map(|p| p.text.as_str()).collect::>(), ["First", "Second"]); + assert_eq!((paras[0].props.indent_left, paras[1].props.indent_left), (Some(72.0), None)); +} + +#[test] +fn a_pieces_prm_formats_its_text() { + // As Word 95 fast-saves formatting: piece 0 has Prm1 -> a Prc setting font 1 and bold, which + // its character run doesn't. Piece 0 shows in font 1, bold (and decodes in its code page); + // piece 1 keeps the run's plain formatting. + let text = b"\xC4\xE0\xC4\xE0\r"; + let d = + Doc6 { text, fonts: FONTS, pieces: Some(&[(2, 0), (3, 2)]), prms: &[0x0001], prcs: &[&[0x5D, 0x01, 0x00, 0x55, 0x01]], ..Default::default() }; + let doc = read(&word6_file(&d)).expect("opens"); + let p = first_para(&doc); + assert_eq!(p.text, "ДаÄà"); + let first = &p.runs.first().expect("a run").props; + assert_eq!((first.font.as_deref(), first.bold), (Some("Times New Roman Cyr"), Some(true))); + let last = &p.runs.last().expect("a run").props; + assert_eq!((last.font.as_deref(), last.bold), (None, None)); +} + +#[test] +fn a_font_in_a_pieces_prm_chooses_its_code_page() { + // As Word 95 fast-saves a font change: piece 0 ("\xC4\xE0") has Prm1 -> Prc 0 = sprm 0x5D font 1 + // (Cyrillic), while its character run names no font. Piece 1 keeps the run's font 0. + let text = b"\xC4\xE0\xC4\xE0\r"; + let d = Doc6 { text, fonts: FONTS, pieces: Some(&[(2, 0), (3, 2)]), prms: &[0x0001], prcs: &[&[0x5D, 0x01, 0x00]], ..Default::default() }; + assert_eq!(texts(&d), ["ДаÄà"]); +} + +#[test] +fn a_prm_index_past_the_prcs_is_ignored() { + let d = Doc6 { text: b"\xC4\xE0\r", fonts: FONTS, pieces: Some(&[(3, 0)]), prms: &[0x0011], prcs: &[&[0x5D, 0x01, 0x00]], ..Default::default() }; + assert_eq!(texts(&d), ["Äà"]); +} + +#[test] +fn password_protected_files_are_refused() { + let d = Doc6 { flags: 0x0100, text: b"secret\r", ..Default::default() }; + assert!(matches!(read(&word6_file(&d)), Err(DocbinError::Encryption(_)))); +} + +/// The first paragraph of `doc`'s body. +fn first_para(doc: &craft_wordmodel::Document) -> &craft_wordmodel::para::Paragraph { + doc.body.iter().find_map(|b| b.as_para()).expect("a paragraph") +} + +#[test] +fn character_formatting_is_read() { + // Bold on, italic as the opposite of the (unread, so plain) style, 14 pt, red, single + // underline, font 2: the Word 6 opcodes as observed. + let g: &[u8] = &[0x55, 0x01, 0x56, 0x81, 0x63, 0x1C, 0x00, 0x62, 0x06, 0x5E, 0x01, 0x5D, 0x02, 0x00]; + let runs: &[(u32, u32, &[u8])] = &[(0, 2, g), (2, 3, &[])]; + let fonts = &[(0, "Times New Roman"), (2, "Symbol"), (0, "Arial")]; + let doc = read(&word6_file(&Doc6 { text: b"Hi\r", fonts, runs, ..Default::default() })).expect("opens"); + let p = first_para(&doc); + let c = &p.runs.first().expect("a run").props; + assert_eq!((c.bold, c.italic, c.size), (Some(true), Some(true), Some(14.0))); + assert_eq!(c.color, Some(craft_wordmodel::props::TextColor::Rgb(craft_wordmodel::props::Rgb(0xFF, 0, 0)))); + assert_eq!(c.underline, Some(craft_wordmodel::props::Underline::Single)); + assert_eq!(c.font.as_deref(), Some("Arial")); +} + +#[test] +fn unseen_operand_values_are_left_unread() { + // Underline 3 and "multiple" line spacing were never seen in a real file, so they aren't + // guessed at. + let runs: &[(u32, u32, &[u8])] = &[(0, 3, &[0x5E, 0x03])]; + let paras: &[(u32, u32, &[u8])] = &[(0, 3, &[0x14, 0xF0, 0x00, 0x01, 0x00])]; + let doc = read(&word6_file(&Doc6 { text: b"Hi\r", runs, paras, ..Default::default() })).expect("opens"); + let p = first_para(&doc); + assert_eq!(p.runs.first().and_then(|r| r.props.underline), None); + assert_eq!(p.props.line_spacing, None); +} + +#[test] +fn an_unseen_alignment_value_is_left_unread() { + // Only 0-3 were seen; 4 would otherwise become "distribute" and 0xFF "left". + for jc in [0x04u8, 0xFF] { + let g = [0x05, jc]; + let paras: &[(u32, u32, &[u8])] = &[(0, 3, &g)]; + let doc = read(&word6_file(&Doc6 { text: b"Hi\r", paras, ..Default::default() })).expect("opens"); + assert_eq!(first_para(&doc).props.align, None, "jc {jc:#04x}"); + } +} + +#[test] +fn paragraph_formatting_is_read() { + // Justified, 0.5" left and 0.25" right indents, a 0.5" hanging first line, at least 27 pt. + let g: &[u8] = &[0x05, 0x03, 0x11, 0xD0, 0x02, 0x10, 0x68, 0x01, 0x13, 0x30, 0xFD, 0x14, 0x1C, 0x02, 0x00, 0x00]; + let paras: &[(u32, u32, &[u8])] = &[(0, 3, g), (3, 6, &[0x05, 0x01])]; + let doc = read(&word6_file(&Doc6 { text: b"Hi\rHo\r", paras, ..Default::default() })).expect("opens"); + let ps: Vec<_> = doc.body.iter().filter_map(|b| b.as_para()).collect(); + let p = &ps[0].props; + assert_eq!(p.align, Some(craft_wordmodel::props::Align::Justify)); + assert_eq!((p.indent_left, p.indent_right, p.indent_first), (Some(36.0), Some(18.0), Some(-36.0))); + assert_eq!(p.line_spacing, Some(craft_wordmodel::props::LineSpacing::AtLeast(27.0))); + assert_eq!(ps[1].props.align, Some(craft_wordmodel::props::Align::Center)); +} + +/// A Word 6 table definition sprm (0xBE): the cell edges, then a 10-byte descriptor per cell +/// whose first word holds the merge flags. +fn def_table(edges: &[i16], rgfs: &[u16]) -> Vec { + let mut rest = vec![rgfs.len() as u8]; + for e in edges { + rest.extend_from_slice(&e.to_le_bytes()); + } + for r in rgfs { + rest.extend_from_slice(&r.to_le_bytes()); + rest.extend_from_slice(&[0; 8]); + } + let mut v = vec![0xBE]; + v.extend_from_slice(&((rest.len() + 1) as u16).to_le_bytes()); + v.extend_from_slice(&rest); + v +} + +/// The rows of the first table in `doc`'s body, each as its cells' texts. +fn table_rows(doc: &craft_wordmodel::Document) -> Vec> { + let t = doc.body.iter().find_map(|b| match b.as_ref() { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }); + let t = t.expect("a table"); + t.rows + .iter() + .map(|r| r.cells.iter().map(|c| c.blocks.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect::>().join("|")).collect()) + .collect() +} + +#[test] +fn table_rows_and_merged_cells_are_read() { + // Row 1: "A", "B". Row 2: "C" merged across both cells. In-table marks carry 0x18, the row + // ends 0x18, 0x19 and the table definition. + let text = b"A\x07B\x07\x07C\x07\x07\x07after\r"; + let mut row1 = vec![0x18, 1, 0x19, 1]; + row1.extend(def_table(&[0, 1440, 2880], &[0, 0])); + let mut row2 = vec![0x18, 1, 0x19, 1]; + row2.extend(def_table(&[0, 1440, 2880], &[0x0001, 0x0002])); + let cell: &[u8] = &[0x18, 1]; + let paras: &[(u32, u32, &[u8])] = &[(0, 2, cell), (2, 4, cell), (4, 5, &row1), (5, 7, cell), (7, 8, cell), (8, 9, &row2), (9, 15, &[])]; + let doc = read(&word6_file(&Doc6 { text, paras, ..Default::default() })).expect("opens"); + assert_eq!(table_rows(&doc), [vec!["A", "B"], vec!["C"]]); + assert_eq!(body_texts(&doc), ["after"], "the paragraph after the table stays outside it"); +} + +#[test] +fn several_merges_in_one_row_each_keep_their_cells() { + // Five cells merged as [A B] [C] [D E]: the second merge must not be shifted by the first. + let text = b"A\x07B\x07C\x07D\x07E\x07\x07"; + let mut row = vec![0x18, 1, 0x19, 1]; + row.extend(def_table(&[0, 100, 200, 300, 400, 500], &[0x0001, 0x0002, 0x0000, 0x0001, 0x0002])); + let cell: &[u8] = &[0x18, 1]; + let paras: &[(u32, u32, &[u8])] = &[(0, 2, cell), (2, 4, cell), (4, 6, cell), (6, 8, cell), (8, 10, cell), (10, 11, &row)]; + let doc = read(&word6_file(&Doc6 { text, paras, ..Default::default() })).expect("opens"); + assert_eq!(table_rows(&doc), [vec!["A|B", "C", "D|E"]]); +} + +#[test] +fn a_field_shows_its_cached_result() { + let d = Doc6 { text: b"Date \x13DATE \x1412/12/97\x15\r", ..Default::default() }; + let text = read(&word6_file(&d)).expect("opens").plain_text(craft_wordmodel::StoryRef::Body); + assert!(text.contains("Date 12/12/97"), "{text:?}"); + assert!(!text.contains("DATE"), "{text:?}"); +} + +/// A fixture's paragraph styles: Normal, an empty slot, then "Mine" (user-defined, centred, bold, on +/// Normal) and "Heading" stored under a local name with sti 1. +const STYLES: &[Option] = &[ + Some(Std { sti: 0, sgc: 1, base: 0x0FFF, name: "Standard", papx: &[], chpx: &[0x61, 0x09, 0x04] }), + None, + Some(Std { sti: 0x0FFE, sgc: 1, base: 0, name: "Mine", papx: &[0x05, 0x01], chpx: &[0x55, 0x01] }), + Some(Std { sti: 1, sgc: 1, base: 0, name: "Überschrift 1", papx: &[0x08, 0x01], chpx: &[0x55, 0x81, 0x63, 0x20, 0x00] }), +]; + +/// Each paragraph's style name, through the document's style sheet. +fn style_names(doc: &craft_wordmodel::Document) -> Vec { + doc.body + .iter() + .filter_map(|b| b.as_para()) + .map(|p| p.props.style.as_deref().and_then(|id| doc.styles.get(id)).map_or(String::new(), |s| s.name.clone())) + .collect() +} + +#[test] +fn paragraphs_take_their_styles() { + let paras: &[(u32, u32, &[u8])] = &[(0, 2, &[]), (2, 4, &[]), (4, 6, &[])]; + let d = Doc6 { text: b"A\rB\rC\r", paras, para_styles: &[0, 2, 3], styles: STYLES, ..Default::default() }; + let doc = read(&word6_file(&d)).expect("opens"); + // A built-in style goes by its built-in name, whatever the file stores (as in Word). + assert_eq!(style_names(&doc), ["Normal", "Mine", "Heading 1"]); +} + +#[test] +fn styles_carry_their_formatting_and_base() { + let d = Doc6 { text: b"A\r", styles: STYLES, ..Default::default() }; + let doc = read(&word6_file(&d)).expect("opens"); + let mine = doc.styles.styles.iter().find(|s| s.name == "Mine").expect("Mine"); + assert_eq!(mine.para.align, Some(craft_wordmodel::props::Align::Center)); + assert_eq!(mine.chr.bold, Some(true)); + assert_eq!(mine.based_on.as_deref().and_then(|id| doc.styles.get(id)).map(|s| s.name.as_str()), Some("Normal")); + let heading = doc.styles.styles.iter().find(|s| s.name == "Heading 1").expect("Heading 1"); + assert_eq!((heading.para.keep_next, heading.chr.size), (Some(true), Some(16.0))); +} + +#[test] +fn bulleted_styles_frame_past_their_numbering() { + // 0x0D (1 byte) and 0x0C (a count byte and its bytes) before the indents, as in the corpus. + let mut papx = vec![0x05, 0x03, 0x0D, 0x0B, 0x11, 0x1C, 0x01, 0x13, 0xE4, 0xFE, 0x0C, 4, 0xFF, 0x01, 0x00, 0x08]; + papx.extend_from_slice(&[0x0E, 0x01, 0x2C, 0x00, 0x1D, 0x60, 0x1A, 0xF8, 0xFF, 0x25, 0x02, 0x10, 0x68, 0x01]); + let styles = &[Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", papx: &papx, ..Default::default() })]; + let doc = read(&word6_file(&Doc6 { text: b"A\r", styles, ..Default::default() })).expect("opens"); + let normal = doc.styles.get("Normal").expect("Normal"); + assert_eq!((normal.para.indent_left, normal.para.indent_first, normal.para.indent_right), (Some(14.2), Some(-14.2), Some(18.0))); +} + +#[test] +fn a_runs_language_or_its_styles_chooses_the_code_page_without_a_font() { + // No font named anywhere: the style's language decides (Russian -> Windows-1251), as in Word. + let styles = &[Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", chpx: &[0x61, 0x19, 0x04], ..Default::default() })]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts: FONTS, styles, ..Default::default() }; + assert_eq!(texts(&d), ["Да"]); + // The run's own language outranks the style's. + let runs: &[(u32, u32, &[u8])] = &[(0, 3, &[0x61, 0x09, 0x04])]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts: FONTS, styles, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Äà"]); +} + +#[test] +fn font_0_is_not_a_fallback() { + // Font 0 is Cyrillic, but nothing names it and the style's language is English: Word reads + // Windows-1252. + let fonts = &[(204, "Times New Roman Cyr"), (0, "Arial")]; + let styles = &[Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", chpx: &[0x61, 0x09, 0x04], ..Default::default() })]; + // A character run that names no font (where the reader used to take font 0). + let runs: &[(u32, u32, &[u8])] = &[(0, 3, &[])]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts, styles, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Äà"]); +} + +#[test] +fn a_font_named_in_the_style_chooses_the_code_page() { + // The base style names the Cyrillic font 1; the run and its own style name none. + let styles = &[ + Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", chpx: &[0x5D, 0x01, 0x00], ..Default::default() }), + Some(Std { sti: 0x0FFE, sgc: 1, base: 0, name: "Child", ..Default::default() }), + ]; + let paras: &[(u32, u32, &[u8])] = &[(0, 3, &[])]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts: FONTS, styles, paras, para_styles: &[1], ..Default::default() }; + assert_eq!(texts(&d), ["Да"]); +} + +#[test] +fn an_ansi_font_leaves_the_code_page_to_the_language() { + // Arial (ANSI) named on the run, the style's language Russian: Word reads Cyrillic. + let fonts = &[(0, "Times New Roman"), (0, "Arial")]; + let styles = &[Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", chpx: &[0x61, 0x19, 0x04], ..Default::default() })]; + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &[0x5D, 0x01, 0x00]), (2, 3, &[])]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts, styles, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Да"]); +} + +/// A fixture with every structure read: runs, fonts and a piece table. +fn full_stream() -> Vec { + let runs: &[(u32, u32, &[u8])] = &[(0, 6, &[0x55, 0x81]), (6, 9, &[0x5D, 0x01, 0x00]), (9, 12, &[])]; + let styles = &[ + Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", chpx: &[0x61, 0x09, 0x04], ..Default::default() }), + None, + Some(Std { sti: 0x0FFE, sgc: 1, base: 0, name: "Mine", papx: &[0x05, 0x01], chpx: &[0x55, 0x01] }), + ]; + let paras: &[(u32, u32, &[u8])] = &[(0, 6, &[]), (6, 12, &[])]; + word_stream(&Doc6 { + text: b"Hello\r\xC4\xE0\rx\r\r", + fonts: FONTS, + runs, + paras, + para_styles: &[2, 0], + styles, + pieces: Some(&[(6, 0), (6, 6)]), + ..Default::default() + }) +} + +#[test] +fn the_full_fixture_reads() { + let f = cfb_file(&[("WordDocument", &full_stream())]); + let doc = read(&f).expect("opens"); + assert_eq!(body_texts(&doc), ["Hello", "Да", "x", ""]); + assert_eq!(style_names(&doc)[0], "Mine"); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn corrupt_word6_streams_never_panic(edits in proptest::collection::vec((0..0x700usize, any::()), 1..16)) { + let mut w = full_stream(); + for (at, b) in edits { + if let Some(x) = w.get_mut(at) { + *x = b; + } + } + let _ = read(&cfb_file(&[("WordDocument", &w)])); + } + + #[test] + fn truncated_word6_streams_never_panic(n in 0..0x700usize) { + let w = full_stream(); + let _ = read(&cfb_file(&[("WordDocument", &w[..n.min(w.len())])])); + } +} diff --git a/crates/doc-binary/src/word6.rs b/crates/doc-binary/src/word6.rs new file mode 100644 index 000000000..e9fab2d74 --- /dev/null +++ b/crates/doc-binary/src/word6.rs @@ -0,0 +1,842 @@ +//! Word 6.0 and Word 95 `.doc` files (`wIdent` 0xA5DC, `nFib` 0x0065 and 0x0068). +//! +//! No public specification describes this version: [MS-DOC] covers Word 97 and later. Everything +//! here is observed, from the layout of real files checked against what Word shows when it opens +//! them (its text through COM, its formatting in the `.docx` Word saves from them), plus the Word +//! 97 structures in [MS-DOC] that these files visibly share. Nothing else is assumed. +//! +//! What is read: the main text, its paragraphs and fields, the code page of each run, the +//! character and paragraph formatting listed below, table rows, and the paragraph styles (with +//! their formatting). Character styles, sections, headers and footers, notes, pictures, borders, +//! shading and tabs are not read yet. +//! +//! The layout as observed: +//! +//! - A compound file with a `WordDocument` stream and **no Table stream**: the structures that +//! Word 97 keeps in `0Table`/`1Table` live in the WordDocument stream itself. +//! - The FIB is one fixed block. The flags at 0x0A have the Word 97 meaning for bit 2 (fast-saved, +//! set exactly in the files that carry a piece table) and, as far as can be told, bit 8 +//! (encrypted). The text starts at the u32 at 0x18, and the main text's length in characters is +//! the u32 at 0x34. +//! - From 0x58, (u32 fc, u32 lcb) pairs, in the order of Word 97's `FibRgFcLcb97`. Index 12 is the +//! character bin table, 13 the paragraph bin table, 15 the font table and 33 the piece table. +//! - Text is one byte per character, in the code page of the font of its run. The FIB's language +//! does not choose it: files marked English hold Russian and Czech text that Word shows as such. +//! - Both bin tables hold 2-byte page numbers (Word 97: 4 bytes). The FKP pages have the Word 97 +//! layout, except that a paragraph page's entries are 7 bytes (an offset byte and 6 more; Word +//! 97: 13), and a PAPX is a count of 2-byte words followed by exactly that many words: the +//! 2-byte style index, then the grpprl (padded with one 0 byte to whole words). +//! - Sprms have **1-byte opcodes**. Those with a 1-byte operand match the opcodes [MS-DOC]'s +//! `Prm0` table lists for the same properties (bold 0x55, colour 0x62, in-table 0x18…); the +//! others were identified against Word. See [`chp`] and [`pap`]. +//! - A font table entry is a size byte (the entry's length − 1), a flags byte, a 2-byte weight, the +//! charset byte, one more byte, then the name in 8-bit characters. +//! - The stylesheet (pair 1) has the Word 97 shape with smaller parts: a u16 header size (14), +//! then a header of that many bytes whose first two words are the style count and the size of +//! a style's fixed part (8, Word 97: 10); +//! then per style a u16 size (0: an empty slot) and that many bytes: the fixed part (sti, then +//! kind and base style, then UPX count and next style, then a size), the name (a length byte, +//! 8-bit characters, a 0), and the UPXs, each a u16 size and its bytes, padded to even. A +//! paragraph style's first UPX is its style index and paragraph sprms, the second its character +//! sprms; a character style has one, its character sprms. + +use craft_codepage::charset_code_page; + +use crate::DocbinError; +use crate::fkp::{Bins, TranslatedRun}; +use crate::piece::{CodePageRun, PieceTable, SYMBOL_CODE_PAGE, Word6Text}; +use crate::stsh::RawStyle; + +/// `wIdent` of a Word 6.0/95 file. +const W_IDENT: u16 = 0xA5DC; +const OFF_FLAGS: usize = 0x0A; +/// Fast-saved: the text is in pieces listed by a piece table. +const F_COMPLEX: u16 = 0x0004; +/// Password-protected (Word 97's bit; no unprotected file sets it). +const F_ENCRYPTED: u16 = 0x0100; +/// Word 97's `fExtChar` bit. Word reads a Word 6.0/95 file that sets it as UTF-16 text (each +/// piece's fc a plain byte offset), and so does this reader. +const F_EXT_CHAR: u16 = 0x1000; +/// The document's character set (u16): 0 Windows, 0x0100 Macintosh (all 8-bit text is Mac Roman, +/// whatever the fonts say), 0x0002 Symbol (every byte a private-use character). Word reads the +/// bytes above ASCII of any other value as U+FFFD. +const OFF_CHSE: usize = 0x14; +const OFF_FC_MAC: usize = 0x1C; +/// Bin table entries read, as for Word 97 (`fkp::MAX_BINS`). +const MAX_BINS: usize = 100_000; +/// FKP runs read (character or paragraph): far more than any real file's, and few enough to stay small. +const MAX_RUNS: usize = 1_000_000; +const OFF_FC_MIN: usize = 0x18; +const OFF_CCP_TEXT: usize = 0x34; +const OFF_PAIRS: usize = 0x58; +/// Pairs read: up to and including the piece table's. +const PAIRS: usize = 34; +const PAIR_STSH: usize = 1; +const PAIR_BTE_CHPX: usize = 12; +const PAIR_BTE_PAPX: usize = 13; +const PAIR_FONTS: usize = 15; +const PAIR_CLX: usize = 33; +/// More characters than Word's own documents get near: the FIB is corrupt (as for Word 97). +const MAX_CCP: u32 = 100_000_000; +/// The font table's entries: more than any real file has. +const MAX_FONTS: usize = 0x1_0000; +/// FKP page size in bytes. +const PAGE: usize = 512; +/// Size of a paragraph FKP entry (offset byte + 6). +const PAPX_BX: usize = 7; +/// Most cells a row's table definition is read for (the model's own cap is 63). +const MAX_CELLS: usize = 63; +/// Styles read: style indexes stop below 0x0FFF ("no style"). +const MAX_STYLES: usize = 0x0FFE; +/// Base-style links followed when a style inherits a font or language. +const MAX_STYLE_DEPTH: usize = 16; + +/// Character sprms read, by Word 6.0/95 opcode. Each one was matched against Word's own reading of +/// the corpus files (the `.docx` it saves from them). +mod chp { + /// Bold, a toggle (0 off, 1 on, 0x80 as the style, 0x81 the opposite of the style). + pub(super) const BOLD: u8 = 0x55; + /// Italic, a toggle. + pub(super) const ITALIC: u8 = 0x56; + /// Small capitals, a toggle. + pub(super) const SMALL_CAPS: u8 = 0x5A; + /// All capitals, a toggle. + pub(super) const CAPS: u8 = 0x5B; + /// The font: a 2-byte index into the font table. + pub(super) const FONT: u8 = 0x5D; + /// Underline: 0 none, 1 single (the only values seen). + pub(super) const UNDERLINE: u8 = 0x5E; + /// Colour: an index into Word's 16-colour palette, as Word 97's `Ico`. + pub(super) const COLOR: u8 = 0x62; + /// Size in half-points (2 bytes). + pub(super) const SIZE: u8 = 0x63; + /// The language (2 bytes, a Windows LCID): with no non-ANSI font, it gives the code page. + pub(super) const LID: u8 = 0x61; +} + +/// Paragraph and table sprms read, by Word 6.0/95 opcode, matched like [`chp`]'s. +mod pap { + /// Alignment: 0 left, 1 centred, 2 right, 3 justified. + pub(super) const JC: u8 = 0x05; + /// Keep with the next paragraph (1 byte; on the heading styles H1-H6, which Word shows with + /// keepNext; [MS-DOC]'s isprm table has sprmPFKeepFollow at 0x08). + pub(super) const KEEP_NEXT: u8 = 0x08; + /// Right indent in twips (signed, 2 bytes). + pub(super) const RIGHT: u8 = 0x10; + /// Left indent in twips. + pub(super) const LEFT: u8 = 0x11; + /// First-line indent in twips, relative to the left one (negative: hanging). + pub(super) const FIRST: u8 = 0x13; + /// Line spacing: the 4-byte Word 97 `LSPD` (dyaLine, fMultLinespace). + pub(super) const LINE: u8 = 0x14; + /// The paragraph is in a table. + pub(super) const IN_TABLE: u8 = 0x18; + /// The mark ends a table row. + pub(super) const TTP: u8 = 0x19; + /// Row alignment (2 bytes): 1 centred. + pub(super) const ROW_JC: u8 = 0xB6; + /// Row height in twips (signed, 2 bytes): positive at least, negative exactly. + pub(super) const ROW_HEIGHT: u8 = 0xBD; + /// The row's cells: u16 count, cell count, (count + 1) i16 cell edges, then a 10-byte + /// descriptor per cell whose first word's bit 0 starts a horizontal merge and bit 1 continues + /// it. + pub(super) const DEF_TABLE: u8 = 0xBE; +} + +/// Word 97 opcodes the translations produce ([MS-DOC] §2.6). +mod w97 { + pub(super) const C_BOLD: u16 = 0x0835; + pub(super) const C_ITALIC: u16 = 0x0836; + pub(super) const C_SMALL_CAPS: u16 = 0x083A; + pub(super) const C_CAPS: u16 = 0x083B; + pub(super) const C_KUL: u16 = 0x2A3E; + pub(super) const C_ICO: u16 = 0x2A42; + pub(super) const C_HPS: u16 = 0x4A43; + pub(super) const C_FTC0: u16 = 0x4A4F; + pub(super) const P_JC80: u16 = 0x2403; + pub(super) const P_KEEP_FOLLOW: u16 = 0x2406; + pub(super) const P_DXA_RIGHT80: u16 = 0x840E; + pub(super) const P_DXA_LEFT80: u16 = 0x840F; + pub(super) const P_DXA_LEFT1_80: u16 = 0x8411; + pub(super) const P_DYA_LINE: u16 = 0x6412; + pub(super) const P_IN_TABLE: u16 = 0x2416; + pub(super) const P_TTP: u16 = 0x2417; + pub(super) const T_JC: u16 = 0x5400; + pub(super) const T_ROW_HEIGHT: u16 = 0x9407; + pub(super) const T_DEF_TABLE: u16 = 0xD608; + pub(super) const T_MERGE: u16 = 0x5624; +} + +/// Is this WordDocument stream a Word 6.0/95 one? +pub(crate) fn is_word6(word: &[u8]) -> bool { + word.get(0..2) == Some(&W_IDENT.to_le_bytes()[..]) +} + +/// The fields of a Word 6.0/95 FIB that are read. +#[derive(Clone, Debug)] +pub(crate) struct Fib6 { + complex: bool, + /// Text is UTF-16 (fExtChar). + wide: bool, + chse: u16, + fc_min: u32, + fc_mac: u32, + /// Characters in the main text. + pub(crate) ccp_text: u32, + pairs: [(u32, u32); PAIRS], +} + +impl Fib6 { + pub(crate) fn parse(word: &[u8]) -> Result { + let u16_at = |at: usize| word.get(at..at + 2).map(|b| u16::from_le_bytes([b[0], b[1]])); + let u32_at = |at: usize| word.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + if word.len() < OFF_PAIRS + PAIRS * 8 { + return Err(DocbinError::NotWord(format!("Word 6.0/95 WordDocument stream is {} bytes", word.len()))); + } + let flags = u16_at(OFF_FLAGS).unwrap_or(0); + if flags & F_ENCRYPTED != 0 { + return Err(DocbinError::Encryption("password-protected Word 6.0/95 files can't be opened".into())); + } + let ccp_text = u32_at(OFF_CCP_TEXT).unwrap_or(0); + if ccp_text > MAX_CCP { + return Err(DocbinError::Limit(format!("document claims {ccp_text} characters"))); + } + let mut pairs = [(0, 0); PAIRS]; + for (i, p) in pairs.iter_mut().enumerate() { + let at = OFF_PAIRS + i * 8; + *p = (u32_at(at).unwrap_or(0), u32_at(at + 4).unwrap_or(0)); + } + Ok(Fib6 { + complex: flags & F_COMPLEX != 0, + wide: flags & F_EXT_CHAR != 0, + chse: u16_at(OFF_CHSE).unwrap_or(0), + fc_min: u32_at(OFF_FC_MIN).unwrap_or(0), + fc_mac: u32_at(OFF_FC_MAC).unwrap_or(0), + ccp_text, + pairs, + }) + } + + /// The (fc, lcb) pair at index `i`, if it points at anything. + fn pair(&self, i: usize) -> Option<(u32, u32)> { + self.pairs.get(i).copied().filter(|&(_, lcb)| lcb > 0) + } +} + +/// Everything the walk needs from a Word 6.0/95 file besides its text stream. +pub(crate) struct Content { + pub(crate) pieces: PieceTable, + /// Character formatting, translated to Word 97 grpprls. + pub(crate) chpx: Bins, + /// Paragraph formatting and table rows, translated to Word 97 grpprls. + pub(crate) papx: Bins, + /// Font names by index (the walk resolves translated font sprms against them). + pub(crate) fonts: Vec, + /// The styles by index, their formatting translated to Word 97 grpprls. + pub(crate) styles: Vec, +} + +/// Read the text, formatting and fonts of a Word 6.0/95 file. +/// +/// 8-bit text decodes, as Word does, in the code page of: the document's character set when it +/// isn't Windows ([`OFF_CHSE`]); else the font a piece's Prm names (as Word 95 writes when a fast +/// save changes a font) when its charset has a code page; else, the same for the font of the +/// character run, or the one its paragraph style (or a base of it) names; else the language of +/// the run, or of its paragraph style; else Windows-1252. A font is only one named somewhere: +/// font 0 is not a fallback, and a font with the ANSI charset leaves the choice to the language. +pub(crate) fn content(word: &[u8], fib: &Fib6) -> Result { + let fonts = fib.pair(PAIR_FONTS).map(|(fc, lcb)| font_table(word, fc, lcb)).unwrap_or_default(); + let chp_runs = fib.pair(PAIR_BTE_CHPX).map(|(fc, lcb)| fkp_runs(word, fc, lcb, false)).unwrap_or_default(); + let pap_runs = fib.pair(PAIR_BTE_PAPX).map(|(fc, lcb)| fkp_runs(word, fc, lcb, true)).unwrap_or_default(); + let (styles, facts) = fib.pair(PAIR_STSH).map(|(fc, lcb)| stylesheet(word, fc, lcb)).unwrap_or_default(); + let windows = fib.chse == 0; + let default_code_page = match fib.chse { + // Text that no run covers is formatted by the Normal style. + 0 => text_code_page(&fonts, &facts, 0, None, None), + 0x0100 => MAC_ROMAN, + 0x0002 => SYMBOL_CODE_PAGE, + // Not a code page: bytes above ASCII read as U+FFFD. + _ => 0, + }; + let code_pages = if windows { code_page_runs(&chp_runs, &pap_runs, &facts, &fonts, default_code_page) } else { Vec::new() }; + // shortcut: East Asian (lead and trail byte) text is refused, as all Word 6.0/95 files were + // before; read it a character at a time when the piece walk can decode byte pairs. + let east_asian = || DocbinError::NotWord("Word 6.0/95 text in an East Asian code page is not read yet".into()); + if craft_codepage::is_multibyte_code_page(default_code_page) || code_pages.iter().any(|r| craft_codepage::is_multibyte_code_page(r.code_page)) { + return Err(east_asian()); + } + let multibyte_piece = std::cell::Cell::new(false); + let text = Word6Text { wide: fib.wide, default_code_page, code_pages }; + let pieces = if fib.complex { + let (fc, lcb) = fib.pair(PAIR_CLX).ok_or_else(|| DocbinError::Malformed("the fast-saved file has no piece table".into()))?; + // A Prm1's Prc may name the piece's font (sprm 0x5D); a Prm0 can't, its operand being one + // byte. + let piece_code_page = |prm: u16, prcs: &[Vec]| -> Option { + if !windows || prm & 1 == 0 { + return None; + } + let cp = last_font(prcs.get(usize::from(prm >> 1))?).and_then(|f| font_code_page(&fonts, f)); + if cp.is_some_and(craft_codepage::is_multibyte_code_page) { + multibyte_piece.set(true); + } + cp + }; + // The Prcs then carry Word 97 sprms, as the CHPXs and PAPXs do: the walk applies their + // character sprms to the piece's text and their paragraph sprms to the paragraph whose mark + // the piece holds. + let table = PieceTable::parse_word6(word, fc, lcb, text, piece_code_page, translate_prc)?; + if multibyte_piece.get() { + return Err(east_asian()); + } + table + } else { + // Word reads no more characters than the text's byte range (fcMin..fcMac) holds, one byte + // each or two for UTF-16, whatever the character count says. + let unit = if fib.wide { 2 } else { 1 }; + let ccp = fib.ccp_text.min(fib.fc_mac.saturating_sub(fib.fc_min) / unit); + PieceTable::contiguous_word6(fib.fc_min, ccp, text) + }; + let chpx = Bins::translated(chp_runs.iter().map(|r| TranslatedRun { lo: r.lo, hi: r.hi, istd: 0, grpprl: translate_chp(r.grpprl) }).collect()); + let papx = + Bins::translated(pap_runs.iter().map(|r| TranslatedRun { lo: r.lo, hi: r.hi, istd: r.istd, grpprl: translate_pap(r.grpprl) }).collect()); + Ok(Content { pieces, chpx, papx, fonts: fonts.into_iter().map(|f| f.name).collect(), styles }) +} + +/// Mac OS Roman, the 8-bit text of a Macintosh Word document. +const MAC_ROMAN: u16 = craft_codepage::MAC_ROMAN_CODE_PAGE; + +/// The code page of font `font`'s charset, if it has one (not for ANSI, default or symbol +/// charsets, whose text Word decodes by its language). +fn font_code_page(fonts: &[Font], font: u16) -> Option { + fonts.get(usize::from(font)).and_then(|f| charset_code_page(i32::from(f.charset))) +} + +/// Windows' ANSI code page for the language `lid` (an LCID), which Word uses for 8-bit text in a +/// font without a charset of its own. Russian (1251) and English (1252) were checked against Word; +/// the rest is the standard Windows assignment. +fn lid_code_page(lid: u16) -> u16 { + match lid & 0x03FF { + // Serbian in Cyrillic (0x0C1A, 0x1C1A); Croatian and Serbian in Latin otherwise. + 0x1A => match lid { + 0x0C1A | 0x1C1A => 1251, + _ => 1250, + }, + 0x02 | 0x19 | 0x22 | 0x23 | 0x2F | 0x3F | 0x40 | 0x44 | 0x50 => 1251, + 0x05 | 0x0E | 0x15 | 0x18 | 0x1B | 0x1C | 0x24 => 1250, + 0x08 => 1253, + 0x1F => 1254, + 0x0D => 1255, + 0x01 | 0x20 | 0x29 => 1256, + 0x25..=0x27 => 1257, + 0x2A => 1258, + 0x1E => 874, + 0x11 => 932, + 0x12 => 949, + 0x04 => match lid { + 0x0804 | 0x1004 => 936, + _ => 950, + }, + _ => 1252, + } +} + +/// A style's own font and language sprms and its base, for inheritance ([`StyleFacts::resolve`]). +#[derive(Clone, Copy, Debug, Default)] +struct StyleFacts { + base: u16, + font: Option, + lid: Option, +} + +impl StyleFacts { + /// Style `istd`'s font and language, each from the style itself or the nearest base that has + /// one. + fn resolve(facts: &[StyleFacts], istd: u16) -> (Option, Option) { + let (mut font, mut lid) = (None, None); + let mut at = istd; + for _ in 0..MAX_STYLE_DEPTH { + let Some(f) = facts.get(usize::from(at)) else { break }; + font = font.or(f.font); + lid = lid.or(f.lid); + if font.is_some() && lid.is_some() { + break; + } + at = f.base; + } + (font, lid) + } +} + +/// The styles of the stylesheet at `word[fc..fc+lcb]`, by index (an empty slot is a default +/// style, which keeps the indexes aligned), with their formatting translated, and each style's +/// own font and language. Reading stops at the first entry that runs past the table. +fn stylesheet(word: &[u8], fc: u32, lcb: u32) -> (Vec, Vec) { + let Some(st) = (fc as usize).checked_add(lcb as usize).and_then(|end| word.get(fc as usize..end)) else { return Default::default() }; + let u16_at = |b: &[u8], at: usize| b.get(at..at + 2).map(|x| u16::from_le_bytes([x[0], x[1]])); + let Some(cb_header) = u16_at(st, 0).map(usize::from) else { return Default::default() }; + let (Some(cstd), Some(cb_base)) = (u16_at(st, 2), u16_at(st, 4)) else { return Default::default() }; + let cb_base = usize::from(cb_base); + let (mut styles, mut facts) = (Vec::new(), Vec::new()); + let mut at = 2 + cb_header; + for _ in 0..usize::from(cstd).min(MAX_STYLES) { + let Some(cb) = u16_at(st, at).map(usize::from) else { break }; + let Some(std) = st.get(at + 2..at + 2 + cb) else { break }; + at += 2 + cb; + let (style, fact) = style(std, cb_base).unwrap_or_else(|| (RawStyle::default(), StyleFacts { base: 0x0FFF, ..Default::default() })); + styles.push(style); + facts.push(fact); + } + (styles, facts) +} + +/// The names of the built-in styles by sti: the "Index within built-in styles" of the reserved +/// style names in [MS-OE376] (Part 4 §2.7.3.9), which [MS-DOC]'s StdfBase says sti is. 0x0FFE +/// (user-defined) and anything past the table keep the name stored in the file. +const BUILT_IN_NAMES: [&str; 107] = [ + "Normal", + "heading 1", + "heading 2", + "heading 3", + "heading 4", + "heading 5", + "heading 6", + "heading 7", + "heading 8", + "heading 9", + "index 1", + "index 2", + "index 3", + "index 4", + "index 5", + "index 6", + "index 7", + "index 8", + "index 9", + "toc 1", + "toc 2", + "toc 3", + "toc 4", + "toc 5", + "toc 6", + "toc 7", + "toc 8", + "toc 9", + "Normal Indent", + "footnote text", + "annotation text", + "header", + "footer", + "index heading", + "caption", + "table of figures", + "envelope address", + "envelope return", + "footnote reference", + "annotation reference", + "line number", + "page number", + "endnote reference", + "endnote text", + "table of authorities", + "macro", + "toa heading", + "List", + "List Bullet", + "List Number", + "List 2", + "List 3", + "List 4", + "List 5", + "List Bullet 2", + "List Bullet 3", + "List Bullet 4", + "List Bullet 5", + "List Number 2", + "List Number 3", + "List Number 4", + "List Number 5", + "Title", + "Closing", + "Signature", + "Default Paragraph Font", + "Body Text", + "Body Text Indent", + "List Continue", + "List Continue 2", + "List Continue 3", + "List Continue 4", + "List Continue 5", + "Message Header", + "Subtitle", + "Salutation", + "Date", + "Body Text First Indent", + "Body Text First Indent 2", + "Note Heading", + "Body Text 2", + "Body Text 3", + "Body Text Indent 2", + "Body Text Indent 3", + "Block Text", + "Hyperlink", + "FollowedHyperlink", + "Strong", + "Emphasis", + "Document Map", + "Plain Text", + "E-mail Signature", + "HTML Top of Form", + "HTML Bottom of Form", + "Normal (Web)", + "HTML Acronym", + "HTML Address", + "HTML Cite", + "HTML Code", + "HTML Definition", + "HTML Keyboard", + "HTML Preformatted", + "HTML Sample", + "HTML Typewriter", + "HTML Variable", + "Normal Table", + "annotation subject", +]; + +/// One style entry (`None` for an empty slot or one too short for its fixed part and name). +fn style(std: &[u8], cb_base: usize) -> Option<(RawStyle, StyleFacts)> { + let u16_at = |at: usize| std.get(at..at + 2).map(|x| u16::from_le_bytes([x[0], x[1]])); + if cb_base < 8 { + return None; + } + let (sti, kind_base, upx_next) = (u16_at(0)? & 0x0FFF, u16_at(2)?, u16_at(4)?); + let (stk, istd_base, cupx) = ((kind_base & 0x000F) as u8, kind_base >> 4, usize::from(upx_next & 0x000F)); + let len = usize::from(*std.get(cb_base)?); + // A built-in style goes by its built-in name, as in Word, whatever name the file stores + // ("Default" or "Обычный" for Normal). Other names are 8-bit, as Word shows them + // (Windows-1252: names it couldn't store read back with '?'). + let stored = std.get(cb_base + 1..cb_base + 1 + len)?; + let name: String = match BUILT_IN_NAMES.get(usize::from(sti)) { + Some(built_in) => (*built_in).to_owned(), + None => stored.iter().map(|&b| craft_codepage::cp1252(b)).collect(), + }; + let mut upxs: Vec<&[u8]> = Vec::new(); + let mut j = cb_base + 1 + len + 1; + for _ in 0..cupx.min(3) { + j += j % 2; + let Some(n) = u16_at(j).map(usize::from) else { break }; + let Some(upx) = std.get(j + 2..j + 2 + n) else { break }; + upxs.push(upx); + j += 2 + n; + } + // A paragraph style: style index + paragraph sprms, then character sprms. A character style: + // character sprms. + let (papx, chpx) = match stk { + 1 => (upxs.first().and_then(|u| u.get(2..)).unwrap_or_default(), upxs.get(1).copied().unwrap_or_default()), + _ => (&[][..], upxs.first().copied().unwrap_or_default()), + }; + let fact = StyleFacts { base: istd_base, font: last_font(chpx), lid: last_lid(chpx) }; + Some((RawStyle { stk, istd_base, name, papx: translate_pap(papx), chpx: translate_chp(chpx) }, fact)) +} + +/// One font table entry. +struct Font { + name: String, + charset: u8, +} + +/// The fonts of the font table at `word[fc..fc+lcb]`, by index. A truncated entry ends the table. +fn font_table(word: &[u8], fc: u32, lcb: u32) -> Vec { + let Some(table) = (fc as usize).checked_add(lcb as usize).and_then(|end| word.get(fc as usize..end)) else { return Vec::new() }; + // The table starts with its own size, which bounds the entries along with `lcb`. + let size = table.get(0..2).map_or(0, |b| usize::from(u16::from_le_bytes([b[0], b[1]]))); + let table = table.get(..size.min(table.len())).unwrap_or_default(); + let mut fonts = Vec::new(); + let mut at = 2usize; + while let Some(&cb_m1) = table.get(at) { + let next = at + usize::from(cb_m1) + 1; + // The entry must lie inside the table and hold its charset (one too short is corrupt). + let Some(entry) = table.get(at..next) else { break }; + let (Some(&charset), Some(name)) = (entry.get(4), entry.get(6..)) else { break }; + if fonts.len() >= MAX_FONTS { + break; + } + // An 8-bit name; font names are ASCII in every file seen, other bytes read as Latin-1. + let name = name.split(|&b| b == 0).next().unwrap_or_default().iter().map(|&b| char::from(b)).collect(); + fonts.push(Font { name, charset }); + at = next; + } + fonts +} + +/// One FKP run as stored: its FC range, the paragraph style (PAPX runs) and its Word 6 grpprl. +struct Run<'w> { + lo: u32, + hi: u32, + istd: u16, + grpprl: &'w [u8], +} + +/// The page numbers of a bin table with `n` entries ((n+1) u32 FCs, then n u16 page numbers), +/// each once, however many entries name it: a page's runs carry their own FCs, so reading it +/// again would only repeat them. The entries read are capped as for Word 97. +fn distinct_pages(plc: &[u8], n: usize) -> Vec { + let mut pns: Vec = (0..n.min(MAX_BINS)) + .filter_map(|i| plc.get(4 * (n + 1) + 2 * i..4 * (n + 1) + 2 * i + 2).map(|b| usize::from(u16::from_le_bytes([b[0], b[1]])))) + .collect(); + pns.sort_unstable(); + pns.dedup(); + pns +} + +/// Every run of the FKP pages a bin table at `word[fc..fc+lcb]` lists, each page read once and +/// at most [`MAX_RUNS`] runs in all. Unreadable pages are skipped. +fn fkp_runs(word: &[u8], fc: u32, lcb: u32, papx: bool) -> Vec> { + let Some(plc) = (fc as usize).checked_add(lcb as usize).and_then(|end| word.get(fc as usize..end)) else { return Vec::new() }; + let Some(n) = plc.len().checked_sub(4).filter(|r| r % 6 == 0).map(|r| r / 6) else { return Vec::new() }; + let entry = if papx { PAPX_BX } else { 1 }; + let mut runs = Vec::new(); + for pn in distinct_pages(plc, n) { + if runs.len() >= MAX_RUNS { + break; + } + let Some(page) = pn.checked_mul(PAGE).and_then(|at| word.get(at..at.checked_add(PAGE)?)) else { continue }; + let crun = usize::from(page.get(PAGE - 1).copied().unwrap_or(0)); + // The FCs and the entries must fit before the count byte. + if 4 * (crun + 1) + entry * crun >= PAGE { + continue; + } + let fc_at = |k: usize| page.get(4 * k..4 * k + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + for k in 0..crun { + let (Some(lo), Some(hi)) = (fc_at(k), fc_at(k + 1)) else { break }; + let off = usize::from(page.get(4 * (crun + 1) + entry * k).copied().unwrap_or(0)) * 2; + let (istd, grpprl) = match (off, papx) { + (0, _) => (0, &[][..]), + // A CHPX: a byte count, then the grpprl. + (_, false) => (0, page.get(off).and_then(|&cb| page.get(off + 1..off + 1 + usize::from(cb))).unwrap_or_default()), + // A PAPX: a count of 2-byte words, then the style index and the grpprl. + (_, true) => { + let body = page.get(off).and_then(|&cw| page.get(off + 1..off + 1 + 2 * usize::from(cw))).unwrap_or_default(); + let istd = body.get(0..2).map_or(0, |b| u16::from_le_bytes([b[0], b[1]])); + (istd, body.get(2..).unwrap_or_default()) + } + }; + runs.push(Run { lo, hi, istd, grpprl }); + } + } + runs +} + +/// The sprms of a Word 6.0/95 grpprl as (opcode, operand). Reading stops at an opcode whose +/// operand length is not known, since the rest can't be framed, and at a lone trailing 0 (the +/// padding of a PAPX to whole words). +fn sprms(grpprl: &[u8]) -> impl Iterator { + let mut rest = grpprl; + std::iter::from_fn(move || { + let (&op, after) = rest.split_first()?; + let len = match op { + // 0x55-0x5C are the character toggles of [MS-DOC]'s Prm0 isprm table (bold, italic, + // strike, outline, shadow, small caps, caps, hidden), all one byte; 0x55, 0x56, 0x5A + // and 0x5B are also seen in real files. + // 0x0D, 0x0E, 0x1D, 0x25 and 0x2C are one-byte paragraph sprms of [MS-DOC]'s isprm table + // too (numbering level, no line numbers, frame anchoring, wrapping, no hyphenation). + 0x05 | 0x08 | 0x0D | 0x0E | 0x18 | 0x19 | 0x1D | 0x25 | 0x2C | 0x33 | 0x55..=0x5C | 0x5E | 0x62 | 0x68 | 0x75 | 0xB7 | 0xB9 => 1, + // 0x1A/0x1B: a frame's position; 0x6B: kerning in half-points (H1 has 0x0024; Word + // shows kern=36). + 0x10 | 0x11 | 0x13 | 0x15 | 0x16 | 0x1A | 0x1B | 0x26 | 0x27 | 0x28 | 0x29 | 0x2F | 0x50 | 0x5D | 0x60 | 0x61 | 0x63 | 0x6B | 0xB6 + | 0xB8 | 0xBD | 0xC0 => 2, + 0x14 => 4, + // A count byte, then that many bytes (0x0C: a bulleted style's numbering, 52 bytes). + 0x0C | 0x0F | 0x44 | 0xBF => 1 + usize::from(*after.first()?), + // A 2-byte count, then one byte fewer than it says (as Word 97's sprmTDefTable). + 0xBE => 2 + usize::from(u16::from_le_bytes([*after.first()?, *after.get(1)?])).saturating_sub(1), + _ => return None, + }; + let operand = after.get(..len)?; + rest = after.get(len..).unwrap_or_default(); + Some((op, operand)) + }) +} + +/// Append a Word 97 Prl: opcode, then operand. +fn prl(out: &mut Vec, op: u16, operand: &[u8]) { + out.extend_from_slice(&op.to_le_bytes()); + out.extend_from_slice(operand); +} + +/// A Word 6.0/95 CHPX grpprl as the Word 97 sprms it stands for. Sprms not read are left out. +fn translate_chp(grpprl: &[u8]) -> Vec { + let mut out = Vec::new(); + for (op, v) in sprms(grpprl) { + match op { + chp::BOLD => prl(&mut out, w97::C_BOLD, v), + chp::ITALIC => prl(&mut out, w97::C_ITALIC, v), + chp::SMALL_CAPS => prl(&mut out, w97::C_SMALL_CAPS, v), + chp::CAPS => prl(&mut out, w97::C_CAPS, v), + // Only none and single were seen; any other value is left unread. + chp::UNDERLINE if matches!(v, [0] | [1]) => prl(&mut out, w97::C_KUL, v), + chp::COLOR => prl(&mut out, w97::C_ICO, v), + chp::SIZE => prl(&mut out, w97::C_HPS, v), + chp::FONT => prl(&mut out, w97::C_FTC0, v), + _ => {} + } + } + out +} + +/// A Word 6.0/95 Prc grpprl as the Word 97 sprms it stands for: character and paragraph sprms +/// alike (Word 95 records a paragraph change before a fast save as a Prc on the mark's piece). +fn translate_prc(grpprl: &[u8]) -> Vec { + [translate_chp(grpprl), translate_pap(grpprl)].concat() +} + +/// A Word 6.0/95 PAPX grpprl as the Word 97 sprms it stands for, table rows included. Sprms not +/// read are left out. +fn translate_pap(grpprl: &[u8]) -> Vec { + let mut out = Vec::new(); + for (op, v) in sprms(grpprl) { + match op { + // Only 0-3 were seen: another value is left unread. + pap::JC if matches!(v, [0..=3]) => prl(&mut out, w97::P_JC80, v), + pap::KEEP_NEXT => prl(&mut out, w97::P_KEEP_FOLLOW, v), + pap::RIGHT => prl(&mut out, w97::P_DXA_RIGHT80, v), + pap::LEFT => prl(&mut out, w97::P_DXA_LEFT80, v), + pap::FIRST => prl(&mut out, w97::P_DXA_LEFT1_80, v), + // Only "at least" spacing was seen (a positive height, not a multiple): the other + // forms are left unread. + pap::LINE => { + if let [l0, l1, 0, 0] = v + && i16::from_le_bytes([*l0, *l1]) > 0 + { + prl(&mut out, w97::P_DYA_LINE, v); + } + } + pap::IN_TABLE => prl(&mut out, w97::P_IN_TABLE, v), + pap::TTP => prl(&mut out, w97::P_TTP, v), + pap::ROW_JC => prl(&mut out, w97::T_JC, v), + pap::ROW_HEIGHT => prl(&mut out, w97::T_ROW_HEIGHT, v), + pap::DEF_TABLE => def_table(&mut out, v), + _ => {} + } + } + out +} + +/// A Word 6.0/95 table definition as a Word 97 `sprmTDefTable` holding the cell edges (the only +/// part the table reader uses) and one `sprmTMerge` per horizontal merge. +fn def_table(out: &mut Vec, v: &[u8]) { + let Some(&itc) = v.get(2) else { return }; + let itc = usize::from(itc).min(MAX_CELLS); + let Some(edges) = v.get(3..3 + 2 * (itc + 1)) else { return }; + // Word 97 operand: cb (u16: the bytes after it, plus one), the cell count, the edges. + let cb = (1 + edges.len() + 1) as u16; + out.extend_from_slice(&w97::T_DEF_TABLE.to_le_bytes()); + out.extend_from_slice(&cb.to_le_bytes()); + out.push(itc as u8); + out.extend_from_slice(edges); + let cells = v.get(3 + edges.len()..).unwrap_or_default(); + let mut merges: Vec<(usize, usize)> = Vec::new(); + let mut start: Option = None; + for i in 0..=itc { + let rgf = cells.get(10 * i..10 * i + 2).map_or(0, |b| u16::from_le_bytes([b[0], b[1]])); + let continues = i < itc && rgf & 0x0002 != 0 && rgf & 0x0001 == 0; + if continues { + continue; + } + // A merge runs from its first cell through every cell that continues it. + if let Some(a) = start.take() + && i > a + 1 + { + merges.push((a, i)); + } + if i < itc && rgf & 0x0001 != 0 { + start = Some(i); + } + } + // Right to left: the table reader folds each merge's cells into its first one as it goes, so + // a merge further right must be applied before one to its left moves its cells. + for (a, b) in merges.into_iter().rev() { + prl(out, w97::T_MERGE, &[a as u8, b as u8]); + } +} + +/// The code page of text in paragraph style `istd` whose run names `run_font` and `run_lid`: the +/// run's font, else the style's (nearest in its base chain), when that font's charset has a code +/// page; else the run's language, else the style's; else Windows-1252. +fn text_code_page(fonts: &[Font], facts: &[StyleFacts], istd: u16, run_font: Option, run_lid: Option) -> u16 { + let (style_font, style_lid) = StyleFacts::resolve(facts, istd); + run_font.or(style_font).and_then(|f| font_code_page(fonts, f)).or_else(|| run_lid.or(style_lid).map(lid_code_page)).unwrap_or(1252) +} + +/// The language a grpprl names (sprm 0x61), if any: the last one. +fn last_lid(grpprl: &[u8]) -> Option { + sprms(grpprl).filter(|(op, _)| *op == chp::LID).filter_map(|(_, v)| Some(u16::from_le_bytes([*v.first()?, *v.get(1)?]))).last() +} + +/// The byte ranges whose code page is not the document default `default`, cut at every character and paragraph run +/// boundary, each stretch in [`text_code_page`]'s. Sorted by start and not overlapping. +fn code_page_runs(chp: &[Run], pap: &[Run], facts: &[StyleFacts], fonts: &[Font], default: u16) -> Vec { + let sorted = |runs: &[Run]| -> Vec<(u32, u32, usize)> { + let mut v: Vec<(u32, u32, usize)> = runs.iter().enumerate().filter(|(_, r)| r.lo < r.hi).map(|(i, r)| (r.lo, r.hi, i)).collect(); + v.sort_unstable(); + v + }; + let (chp_sorted, pap_sorted) = (sorted(chp), sorted(pap)); + let covering = |v: &[(u32, u32, usize)], fc: u32| -> Option { + let k = v.partition_point(|&(lo, _, _)| lo <= fc).checked_sub(1)?; + v.get(k).filter(|&&(_, hi, _)| fc < hi).map(|&(_, _, i)| i) + }; + let mut cuts: Vec = chp_sorted.iter().chain(pap_sorted.iter()).flat_map(|&(lo, hi, _)| [lo, hi]).collect(); + cuts.sort_unstable(); + cuts.dedup(); + let mut out: Vec = Vec::new(); + for w in cuts.windows(2) { + let (&lo, &hi) = (w.first().unwrap_or(&0), w.get(1).unwrap_or(&0)); + let run = covering(&chp_sorted, lo).and_then(|i| chp.get(i)); + let para = covering(&pap_sorted, lo).and_then(|i| pap.get(i)); + if run.is_none() && para.is_none() { + continue; + } + let run_font = run.and_then(|r| last_font(r.grpprl)); + let run_lid = run.and_then(|r| last_lid(r.grpprl)); + let code_page = text_code_page(fonts, facts, para.map_or(0, |p| p.istd), run_font, run_lid); + if code_page == default { + continue; + } + match out.last_mut() { + Some(last) if last.hi == lo && last.code_page == code_page => last.hi = hi, + _ => out.push(CodePageRun { lo, hi, code_page }), + } + } + out +} + +/// The font a CHPX or Prc grpprl names (sprm 0x5D), if any: the last one, as a later sprm +/// overrides an earlier one when the formatting is applied (a font before an opcode of unknown +/// length stands). +fn last_font(grpprl: &[u8]) -> Option { + sprms(grpprl).filter(|(op, _)| *op == chp::FONT).filter_map(|(_, v)| Some(u16::from_le_bytes([*v.first()?, *v.get(1)?]))).last() +} + +#[cfg(test)] +mod tests { + #[test] + fn a_page_named_by_many_bin_entries_is_read_once() { + // A hostile bin table: a million entries all naming page 7, and one naming page 3. + let n = 1_000_001usize; + let mut plc = vec![0u8; 4 * (n + 1)]; + for i in 0..n { + plc.extend_from_slice(&(if i == 5 { 3u16 } else { 7u16 }).to_le_bytes()); + } + assert_eq!(super::distinct_pages(&plc, n), [3, 7]); + } + + #[test] + fn bin_entries_past_the_cap_are_not_read() { + let n = super::MAX_BINS + 1; + let mut plc = vec![0u8; 4 * (n + 1)]; + for i in 0..n { + plc.extend_from_slice(&(if i == n - 1 { 9u16 } else { 7u16 }).to_le_bytes()); + } + assert_eq!(super::distinct_pages(&plc, n), [7]); + } +} diff --git a/crates/docpath/tests/long_path.rs b/crates/docpath/tests/long_path.rs new file mode 100644 index 000000000..2ecf08ba1 --- /dev/null +++ b/crates/docpath/tests/long_path.rs @@ -0,0 +1,29 @@ +//! Paths long enough that a per-level recursive descent would exhaust the stack. Parsing is +//! iterative — `resolve` and `classify` reach `parse_share` at a fixed depth — so these come +//! back; a refusal is fine, a crash is not. + +use craft_docpath::{classify, resolve}; + +/// Half a megabyte of components under a UNC share: one component per level for a parser that +/// recursed on each separator. +#[test] +fn a_half_megabyte_unc_path_comes_back() { + let mut path = String::from(r"\\?\UNC\host\share"); + for _ in 0..(1 << 18) { + path.push_str(r"\d"); + } + let _ = resolve(&path, None); + let _ = classify(&path); +} + +/// Sixteen thousand nested verbatim prefixes: each level was a candidate recursive call when the +/// UNC prefixes were first reviewed. +#[test] +fn nested_verbatim_prefixes_come_back() { + let mut path = String::new(); + for _ in 0..(1 << 14) { + path.push_str(r"\\?\UNC\"); + } + let _ = resolve(&path, None); + let _ = classify(&path); +} diff --git a/crates/document-bundle/src/lib.rs b/crates/document-bundle/src/lib.rs index 18e40a3ff..70a960a1f 100644 --- a/crates/document-bundle/src/lib.rs +++ b/crates/document-bundle/src/lib.rs @@ -6,15 +6,17 @@ //! bounded reads and extraction of legacy base64 asset maps. Entry names and MIME type are //! supplied by the format using the bundle. -use std::io::{Read, Seek}; +use std::io::{Cursor, Read, Seek, Write}; -use craft_zip::{Archive, Compression, Limits, Writer}; +use craft_zip::{Archive, Limits}; use serde_json::Value; const MAX_ENTRIES: u64 = 100_000; const JSON_LIMIT: u64 = 256 << 20; const ASSET_LIMIT: u64 = 1 << 30; const EXPANSION_LIMIT: u64 = 4 << 30; +/// Largest proxy preview read from a bundle; larger entries are skipped. +pub const PROXY_LIMIT: u64 = 1 << 20; /// Per-entry and total-expansion limits for an untrusted document bundle. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -46,6 +48,8 @@ pub struct Spec<'a> { pub preview_entry: &'a str, /// Directory prefix for embedded assets, without a trailing slash. pub assets_directory: &'a str, + /// Directory prefix for proxy previews of linked assets, without a trailing slash. + pub proxies_directory: &'a str, /// Metadata value written in the `format` field. pub format_name: &'a str, /// Old single-file JSON field containing base64 assets keyed by decimal id. @@ -72,6 +76,8 @@ pub struct Package { pub version: u64, /// Embedded asset bytes keyed by decimal asset id. pub assets: Vec<(String, Vec)>, + /// Proxy preview bytes (JPEG or PNG) keyed by decimal asset id, for ids the document lists. + pub proxies: Vec<(String, Vec)>, } /// Why a document bundle could not be read or written. @@ -116,24 +122,104 @@ pub fn starts_with_mimetype(prefix: &[u8], spec: Spec<'_>) -> bool { craft_zip::stored_mimetype(prefix).is_some_and(|mime| mime == spec.mimetype.as_bytes()) } -/// Write a ZIP document bundle containing the serialized document, metadata, preview and assets. -pub fn write(document: &[u8], version: u32, generator: &str, preview: Option<&[u8]>, assets: &[Asset<'_>], spec: Spec<'_>) -> Result, Error> { - let mut writer = Writer::new(); - writer.add(spec.mimetype_entry, spec.mimetype.as_bytes(), Compression::Stored).map_err(|e| Error::Write(e.to_string()))?; - let metadata = serde_json::json!({"format":spec.format_name, "version":version, "generator":generator}); - let metadata = serde_json::to_vec(&metadata).map_err(|e| Error::Write(e.to_string()))?; - writer.add(spec.metadata_entry, &metadata, Compression::Deflated).map_err(|e| Error::Write(e.to_string()))?; - if let Some(preview) = preview { - writer.add(spec.preview_entry, preview, Compression::Stored).map_err(|e| Error::Write(e.to_string()))?; +/// Refuses every write and seek after the first failure of the wrapped writer. Dropping a +/// `ZipWriter` after an error finalizes the archive, which must not touch a cancelled target. +struct Latch { + inner: W, + failed: bool, +} + +impl Latch { + fn latched() -> std::io::Error { + std::io::Error::other("writer already failed") } - writer.add(spec.document_entry, document, Compression::Deflated).map_err(|e| Error::Write(e.to_string()))?; +} + +impl Write for Latch { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.failed { + return Err(Self::latched()); + } + self.inner.write(buf).inspect_err(|_| self.failed = true) + } + fn flush(&mut self) -> std::io::Result<()> { + if self.failed { + return Err(Self::latched()); + } + self.inner.flush().inspect_err(|_| self.failed = true) + } +} + +impl Seek for Latch { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + if self.failed { + return Err(Self::latched()); + } + self.inner.seek(pos).inspect_err(|_| self.failed = true) + } +} + +fn write_err(e: impl std::fmt::Display) -> Error { + Error::Write(e.to_string()) +} + +/// Write a ZIP document bundle containing the serialized document, metadata, preview, assets and +/// proxy previews. +pub fn write( + document: &[u8], + version: u32, + generator: &str, + preview: Option<&[u8]>, + assets: &[Asset<'_>], + proxies: &[Asset<'_>], + spec: Spec<'_>, +) -> Result, Error> { + let mut out = Cursor::new(Vec::new()); + write_to(&mut out, document, version, generator, preview, assets, proxies, spec)?; + Ok(out.into_inner()) +} + +/// Like [`write`], streaming the archive into `out`. A writer that fails (for example to cancel +/// a long save) stops the write at the next member or buffer and the error is returned. +#[allow(clippy::too_many_arguments)] +pub fn write_to( + out: W, + document: &[u8], + version: u32, + generator: &str, + preview: Option<&[u8]>, + assets: &[Asset<'_>], + proxies: &[Asset<'_>], + spec: Spec<'_>, +) -> Result<(), Error> { + use zip::CompressionMethod::{Deflated, Stored}; + let mut zip = zip::ZipWriter::new(Latch { inner: out, failed: false }); + let mut add = |name: &str, data: &[u8], method: zip::CompressionMethod| -> Result<(), Error> { + let options = zip::write::SimpleFileOptions::default() + .compression_method(method) + .compression_level(if method == Deflated { Some(6) } else { None }) + .last_modified_time(zip::DateTime::default()) + .large_file(u64::try_from(data.len()).unwrap_or(u64::MAX) >= u64::from(u32::MAX) / 2); + zip.start_file(name, options).map_err(|e| Error::Write(format!("{name}: {e}")))?; + zip.write_all(data).map_err(|e| Error::Write(format!("{name}: {e}"))) + }; + add(spec.mimetype_entry, spec.mimetype.as_bytes(), Stored)?; + let metadata = serde_json::json!({"format":spec.format_name, "version":version, "generator":generator}); + add(spec.metadata_entry, &serde_json::to_vec(&metadata).map_err(write_err)?, Deflated)?; + if let Some(preview) = preview { + add(spec.preview_entry, preview, Stored)?; + } + add(spec.document_entry, document, Deflated)?; for asset in assets.iter().filter(|asset| !asset.data.is_empty()) { let path = format!("{}/{}.{}", spec.assets_directory, asset.id, extension(asset.mime)); - let compression = - if matches!(asset.mime, "image/png" | "image/jpeg" | "image/gif" | "image/webp") { Compression::Stored } else { Compression::Deflated }; - writer.add(&path, asset.data, compression).map_err(|e| Error::Write(e.to_string()))?; + let method = if matches!(asset.mime, "image/png" | "image/jpeg" | "image/gif" | "image/webp") { Stored } else { Deflated }; + add(&path, asset.data, method)?; } - writer.finish().map_err(|e| Error::Write(e.to_string())) + for proxy in proxies.iter().filter(|proxy| !proxy.data.is_empty()) { + let ext = if proxy.mime == "image/jpeg" { "jpg" } else { "png" }; + add(&format!("{}/{}.{ext}", spec.proxies_directory, proxy.id), proxy.data, Stored)?; + } + zip.finish().map(drop).map_err(write_err) } /// Read a ZIP bundle or legacy JSON document within bounded member sizes. @@ -186,7 +272,40 @@ pub fn read_with_limits(bytes: &[u8], supported_version: u32, spec: Spec<'_>, li embedded.push((id.to_owned(), data)); } } - Ok(Package { document, version, assets: embedded }) + let proxies = read_proxies(&mut archive, &wanted, spec); + Ok(Package { document, version, assets: embedded, proxies }) +} + +/// Proxy previews for known asset ids. Only `/.jpg|png` is accepted; entries over +/// [`PROXY_LIMIT`] or that fail to read are skipped. +fn read_proxies(archive: &mut Archive<'_>, wanted: &std::collections::HashSet, spec: Spec<'_>) -> Vec<(String, Vec)> { + let prefix = format!("{}/", spec.proxies_directory); + let mut proxies = Vec::new(); + for path in archive.names().map(|name| name.into_owned()).collect::>() { + let Some(member) = path.strip_prefix(&prefix) else { continue }; + let Some((id, ext)) = member.split_once('.') else { continue }; + if !matches!(ext, "jpg" | "png") || !wanted.contains(id) || id.parse::().is_err() { + continue; + } + if archive.declared_size(&path).is_none_or(|size| size > PROXY_LIMIT) { + continue; + } + let Some(size) = archive.declared_size(&path) else { continue }; + if archive.budget().remaining() < size { + break; + } + match archive.read(&path, PROXY_LIMIT) { + Ok(Some(data)) => proxies.push((id.to_owned(), data)), + Ok(None) => {} + // A failed read may have decompressed up to `size` bytes without being charged. + Err(_) => { + if archive.budget_mut().charge(size).is_err() { + break; + } + } + } + } + proxies } /// Read a preview with a fixed maximum size without decompressing the full bundle. @@ -235,7 +354,7 @@ fn read_legacy(bytes: &[u8], spec: Spec<'_>) -> Result { object.remove(field); } } - Ok(Package { document, version: 1, assets }) + Ok(Package { document, version: 1, assets, proxies: Vec::new() }) } fn decode_base64(input: &str) -> Vec { @@ -271,6 +390,7 @@ mod tests { document_entry: "document.json", preview_entry: "preview.png", assets_directory: "assets", + proxies_directory: "proxies", format_name: "test", legacy_assets_field: Some("assetData"), }; @@ -278,8 +398,8 @@ mod tests { #[test] fn writes_and_reads_bundle_members() { let payload = [1u8, 2, 3]; - let bytes = - write(br#"{"assets":{"7":{}}}"#, 4, "Test 0.1", Some(b"png"), &[Asset { id: "7", mime: "image/png", data: &payload }], SPEC).unwrap(); + let bytes = write(br#"{"assets":{"7":{}}}"#, 4, "Test 0.1", Some(b"png"), &[Asset { id: "7", mime: "image/png", data: &payload }], &[], SPEC) + .unwrap(); assert!(has_document(&bytes, SPEC)); assert!(starts_with_mimetype(&bytes, SPEC)); let loaded = read(&bytes, 4, SPEC).unwrap(); @@ -298,7 +418,7 @@ mod tests { #[test] fn refuses_newer_versions() { - let bytes = write(b"{}", 9, "future", None, &[], SPEC).unwrap(); + let bytes = write(b"{}", 9, "future", None, &[], &[], SPEC).unwrap(); assert_eq!(read(&bytes, 4, SPEC), Err(Error::TooNew(9))); } @@ -307,11 +427,31 @@ mod tests { let bytes = vec![7u8; 128]; let document = br#"{"assets":{"7":{}}}"#; let limits = ReadLimits { json_bytes: 1 << 20, compressed_asset_bytes: 8, expansion_bytes: 1 << 20 }; - let stored = write(document, 4, "test", None, &[Asset { id: "7", mime: "image/png", data: &bytes }], SPEC).unwrap(); + let stored = write(document, 4, "test", None, &[Asset { id: "7", mime: "image/png", data: &bytes }], &[], SPEC).unwrap(); let package = read_with_limits(&stored, 4, SPEC, limits).unwrap(); assert_eq!(package.assets, [("7".to_owned(), bytes.clone())]); - let compressed = write(document, 4, "test", None, &[Asset { id: "7", mime: "application/octet-stream", data: &bytes }], SPEC).unwrap(); + let compressed = write(document, 4, "test", None, &[Asset { id: "7", mime: "application/octet-stream", data: &bytes }], &[], SPEC).unwrap(); assert!(read_with_limits(&compressed, 4, SPEC, limits).is_err()); } + + #[test] + fn failed_proxy_reads_are_charged_and_stop_reading_when_the_budget_is_spent() { + let pad = " ".repeat(40_000); + let document = format!(r#"{{"assets":{{"1":{{}},"2":{{}},"3":{{}},"4":{{}}}},"pad":"{pad}"}}"#); + let blobs: Vec> = (1u8..=4).map(|n| vec![n.wrapping_mul(50); 1000]).collect(); + let ids = ["1", "2", "3", "4"]; + let proxies: Vec> = ids.iter().zip(&blobs).map(|(id, data)| Asset { id, mime: "image/png", data }).collect(); + let mut bytes = write(document.as_bytes(), 4, "t", None, &[], &proxies, SPEC).unwrap(); + // Corrupt proxies 1 to 3 so their reads fail their checksum. + for blob in &blobs[..3] { + let at = bytes.windows(blob.len()).position(|w| w == blob.as_slice()).unwrap(); + bytes[at + 500] ^= 0xFF; + } + let source = bytes.len() as u64; + let all = read(&bytes, 4, SPEC).unwrap(); + assert_eq!(all.proxies.len(), 1); + let tight = ReadLimits { json_bytes: 1 << 20, compressed_asset_bytes: 1 << 20, expansion_bytes: 40_100 + 2_500 - source }; + assert!(read_with_limits(&bytes, 4, SPEC, tight).unwrap().proxies.is_empty()); + } } diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 3e6ea5e61..0f95b4f76 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -119,6 +119,10 @@ pub(crate) struct Reader<'p> { pub theme_fills: shape_style::ThemeFills, /// The fill of the group being read (what its members' `a:grpFill` stands for). pub group_fill: Option, + /// The package has no default table style (no styles part, or none marked `w:default`): + /// Word then gives tables no cell margins rather than its Normal Table's 0.08". Set by + /// `read_styles`, which runs before any story with tables is read. + pub no_default_table_style: bool, } /// The package path that internal relationship `id` points at, if it has type `kind` (an `rt` @@ -193,11 +197,31 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, theme_fills: Default::default(), group_fill: None, chunks, + no_default_table_style: true, }; r.doc.missing_pictures.main = main.clone(); r.pc.major_font = r.doc.settings.major_font.clone(); r.pc.minor_font = r.doc.settings.minor_font.clone(); - let part = |t: &str| rels.by_type(t).filter(|x| !x.external).map(|x| x.target.clone()); + let part = |t: &str| { + let related = rels.by_type(t).filter(|x| !x.external).map(|x| x.target.clone()).filter(|p| pkg.get(p).is_some()); + related.or_else(|| { + // Older DesignCraft imports read these two conventional parts directly. Keep opening + // those files when a producer omitted the document relationship; the bounded package + // reader still applies the same entry and XML limits. An explicit usable relationship + // always wins, including when it points outside the conventional `word/` paths. + if !main.eq_ignore_ascii_case("word/document.xml") { + return None; + } + let fallback = match t { + rt::STYLES => "word/styles.xml", + rt::NUMBERING => "word/numbering.xml", + rt::FOOTNOTES => "word/footnotes.xml", + rt::ENDNOTES => "word/endnotes.xml", + _ => return None, + }; + pkg.get(fallback).map(|_| fallback.to_string()) + }) + }; // The font table and the fonts embedded through it ride along as opaque parts. if let Some(p) = part(rt::FONT_TABLE) { diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index 2c8d025b1..dc61b3a28 100644 --- a/crates/docx/src/read/props.rs +++ b/crates/docx/src/read/props.rs @@ -389,15 +389,22 @@ impl PropCtx { } "w:numPr" => { let num = k.child_val("w:numId").and_then(u32_of); - let ilvl = k.child_val("w:ilvl").and_then(u32_of); - let level = ilvl.unwrap_or(0).min(8) as u8; - match (num, ilvl) { - (Some(num), _) => p.numbering = Some(NumRef { num, level }), - // A level without a list: the list comes from the based-on style, as in - // a Heading 3 that only says "level 3" of Heading 2's list. Resolved once - // the styles are read (`resolve_list_levels`). - (None, Some(_)) => p.numbering = Some(NumRef { num: LEVEL_ONLY, level }), - (None, None) => {} + let ilvl_node = k.child("w:ilvl"); + let ilvl = + ilvl_node.and_then(|node| node.attr("w:val")).and_then(int).filter(|level| (0..=8).contains(level)).map(|level| level as u32); + // A missing level means level zero. A present but malformed/out-of-range + // level invalidates this numbering reference instead of silently becoming + // level zero; the latter can turn hostile input into a real list. + if ilvl_node.is_none() || ilvl.is_some() { + let level = ilvl.unwrap_or(0) as u8; + match (num, ilvl) { + (Some(num), _) => p.numbering = Some(NumRef { num, level }), + // A level without a list: the list comes from the based-on style, as in + // a Heading 3 that only says "level 3" of Heading 2's list. Resolved once + // the styles are read (`resolve_list_levels`). + (None, Some(_)) => p.numbering = Some(NumRef { num: LEVEL_ONLY, level }), + (None, None) => {} + } } } "w:pBdr" => p.borders = Some(self.borders(k)), @@ -817,20 +824,21 @@ pub fn sectpr(pc: &PropCtx, e: &El) -> (SectionProps, Vec) { s.footnote_columns = k.attr("w:val").and_then(u32_of).filter(|v| (1..=45).contains(v)); } "w:lnNumType" => { - let mut l = LineNumbering::default(); - if let Some(v) = k.attr("w:countBy").and_then(u32_of) { - l.count_by = v.clamp(1, 100); + // Word leaves line numbering off unless `w:countBy` gives an interval above 0, + // whatever `w:start`, `w:distance` and `w:restart` say (#6209, observed in Word). + if let Some(count_by) = k.attr("w:countBy").and_then(u32_of).filter(|&v| v > 0) { + let mut l = LineNumbering { count_by: count_by.clamp(1, 100), ..LineNumbering::default() }; + if let Some(v) = k.attr("w:start").and_then(int) { + l.start = (v.clamp(0, 32_767) + 1) as u32; + } + l.distance = tw(k, "w:distance").unwrap_or(0.0).max(0.0); + l.restart = match k.attr("w:restart") { + Some("newSection") => LineNumberRestart::Section, + Some("continuous") => LineNumberRestart::Continuous, + _ => LineNumberRestart::Page, + }; + s.line_numbers = Some(l); } - if let Some(v) = k.attr("w:start").and_then(int) { - l.start = (v.clamp(0, 32_767) + 1) as u32; - } - l.distance = tw(k, "w:distance").unwrap_or(0.0).max(0.0); - l.restart = match k.attr("w:restart") { - Some("newSection") => LineNumberRestart::Section, - Some("continuous") => LineNumberRestart::Continuous, - _ => LineNumberRestart::Page, - }; - s.line_numbers = Some(l); } "w:vAlign" => { s.valign = match k.attr("w:val") { diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 0550557f1..770375365 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -113,6 +113,8 @@ pub struct StoryCtx { pub story_depth: usize, /// Reading a header or footer (not a text box inside one): where Word keeps its watermark. pub in_hf: bool, + /// Reading a table cell's paragraphs (not a text box inside one). + in_cell: bool, } /// Paragraph content under construction. diff --git a/crates/docx/src/read/story/blocks.rs b/crates/docx/src/read/story/blocks.rs index e72f16bf6..38c35a02b 100644 --- a/crates/docx/src/read/story/blocks.rs +++ b/crates/docx/src/read/story/blocks.rs @@ -276,6 +276,10 @@ impl Reader<'_> { if sc.fields.iter().any(|f| f.phase == Phase::Instr) && para.plain_text().is_empty() { para.mark.hidden = Some(true); } + // A cell's paragraphs are marked once their table is read: its style counts. + if !sc.in_cell { + self.doc.styles.mark_runs_as_word_draws_them(&mut para, None); + } para.normalize(); para } @@ -314,15 +318,32 @@ impl Reader<'_> { // ---- tables ---- + /// Word gives a table no cell margins when the file has no default table style and neither the + /// table nor its style sets them; saving may write a default Normal Table, so the zeros are + /// kept as the table's own. shortcut: they stay direct formatting (a table style applied later + /// keeps them), until the model knows the file's default table style. A `w:tblCellMar` that sets + /// only some sides keeps them: only the sides it omits become 0. + fn no_default_margins(&self, props: &mut craft_wordmodel::props::TableProps) { + if self.no_default_table_style + && props.cell_margins.is_none() + && props.style.as_deref().and_then(|id| self.doc.styles.table_style(id)).is_none_or(|s| s.parts.cell_margins.is_none()) + { + props.cell_margins = Some([0.0; 4]); + } + } + fn read_table(&mut self, sc: &mut StoryCtx, t: &El, rels: &Rels, depth: usize) -> Option { let mut table = Table::default(); if let Some(p) = t.child("w:tblPr") { table.props = self.pc.tblpr(p); if let Some(ch) = p.child("w:tblPrChange") { - let old = ch.child("w:tblPr").map(|o| self.pc.tblpr(o)).unwrap_or_default(); + let mut old = ch.child("w:tblPr").map(|o| self.pc.tblpr(o)).unwrap_or_default(); + // Rejecting the change brings back these properties: with the same margins. + self.no_default_margins(&mut old); table.props.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, ch), old); } } + self.no_default_margins(&mut table.props); if let Some(g) = t.child("w:tblGrid") { table.grid = g .children("w:gridCol") @@ -355,8 +376,10 @@ impl Reader<'_> { continue; } let mut blocks = Blocks::new(); + let outer = std::mem::replace(&mut sc.in_cell, true); self.read_blocks(sc, tc, rels, &mut blocks, depth + 4); self.flush_pending(sc, &mut blocks); + sc.in_cell = outer; row.cells.push(Cell { props, blocks, controls: cell_controls }); } if !row.cells.is_empty() { @@ -370,6 +393,20 @@ impl Reader<'_> { let cols = table.cols().clamp(1, MAX_COLS); table.grid = vec![72.0; cols]; } + // The cells' paragraphs, with the run formatting the table style gives each cell (a + // table inside has marked its own). + let chrs = self.doc.styles.table_cells_chr(&table); + for (ri, row) in table.rows.iter_mut().enumerate() { + for (ci, cell) in row.cells.iter_mut().enumerate() { + let chr = chrs.as_ref().and_then(|c| c.get(ri)?.get(ci)); + for b in &mut cell.blocks { + if let Block::Para(p) = Arc::make_mut(b) { + self.doc.styles.mark_runs_as_word_draws_them(p, chr); + p.normalize(); + } + } + } + } Some(table) } } diff --git a/crates/docx/src/read/styles.rs b/crates/docx/src/read/styles.rs index edc17f21f..e12749a87 100644 --- a/crates/docx/src/read/styles.rs +++ b/crates/docx/src/read/styles.rs @@ -1,10 +1,22 @@ use super::{ - AbstractNum, DocxError, El, Level, LevelSuffix, Num, NumFormat, PartFormat, Reader, Style, StyleKind, StyleSheet, TablePart, TableStyleParts, - VAlign, flag, int, props, tw, u32_of, + AbstractNum, DocxError, El, Level, LevelSuffix, Num, NumFormat, PartFormat, Reader, RevisionKind, Style, StyleKind, StyleSheet, TablePart, + TableStyleParts, VAlign, flag, int, props, tw, u32_of, }; use crate::units::tw_i16; +use craft_wordmodel::props::PropChange; use std::sync::Arc; +fn numbering_level_index(value: Option<&str>) -> Option { + match value { + None => Some(0), + Some(value) => int(value).filter(|level| (0..=8).contains(level)).map(|level| level as usize), + } +} + +fn style_is_default(style: &El) -> bool { + style.attr("w:default").is_some_and(|value| !matches!(value.trim(), "0" | "false" | "off" | "False" | "FALSE")) +} + /// Built-in style names Word stores in lower case, and how the UI shows them. pub(crate) const LOWER_NAMES: &[(&str, &str)] = &[ ("caption", "Caption"), @@ -52,6 +64,20 @@ fn builtin_heading_level(name: &str) -> Option { } impl Reader<'_> { + /// Whether a style's kept (last) definition is a default table style. + fn has_default_table_style(&self, root: &El) -> bool { + let mut defaults: Vec = Vec::new(); + for s in root.children("w:style").take(10_000) { + let Some(raw_id) = s.attr("w:styleId").filter(|i| !i.is_empty()) else { continue }; + let id = self.pc.style_id(raw_id); + defaults.retain(|d| *d != id); + if s.attr("w:type") == Some("table") && style_is_default(s) { + defaults.push(id); + } + } + !defaults.is_empty() + } + pub(super) fn read_styles(&mut self, path: &str) -> Result<(), DocxError> { /// Largest `w:latentStyles` kept (Word's has ~380 exceptions, ~40 KB). const MAX_LATENT_STYLES_XML: usize = 1 << 20; @@ -59,9 +85,7 @@ impl Reader<'_> { // The default paragraph style must be called `Normal` in our model. let has_normal = root.children("w:style").any(|s| s.attr("w:styleId") == Some("Normal")); if !has_normal - && let Some(def) = root - .children("w:style") - .find(|s| s.attr("w:type") == Some("paragraph") && s.attr("w:default").is_some_and(|v| v == "1" || v == "true")) + && let Some(def) = root.children("w:style").find(|s| s.attr("w:type") == Some("paragraph") && style_is_default(s)) && let Some(id) = def.attr("w:styleId") { self.pc.alias.insert(id.to_string(), "Normal".into()); @@ -85,6 +109,7 @@ impl Reader<'_> { } } let mut sheet = StyleSheet::empty(); + let mut normal_is_default = None; sheet.default_para_present = root.child("w:docDefaults").and_then(|dd| dd.child("w:pPrDefault")).is_some(); if let Some(dd) = root.child("w:docDefaults") { if let Some(r) = dd.child("w:rPrDefault").and_then(|d| d.child("w:rPr")) { @@ -112,6 +137,13 @@ impl Reader<'_> { "numbering" => StyleKind::Numbering, _ => StyleKind::Paragraph, }; + if kind == StyleKind::Paragraph && id == "Normal" { + // Word treats the built-in Normal style as the paragraph default when the file + // doesn't nominate another style. Keep that fact for an explicitly declared + // Normal; the gallery later synthesizes a visually identical Normal when the + // file did not declare one, and that synthetic style is not source provenance. + normal_is_default = Some(s.attr("w:default").is_none()); + } let name = s.child_val("w:name").map(ui_style_name).unwrap_or_else(|| id.clone()); let r = |n: &str| s.child_val(n).filter(|v| !v.is_empty()).map(|v| self.pc.style_id(v)); let mut st = Style { @@ -127,7 +159,7 @@ impl Reader<'_> { builtin: !s.attr("w:customStyle").is_some_and(|v| matches!(v.trim(), "1" | "true" | "on")), locked: flag(s, "w:locked").unwrap_or(false), // Only where the writer couldn't tell from the id (it flags the English ids). - default: s.attr("w:default").is_some_and(|v| v == "1" || v == "true") + default: style_is_default(s) && !matches!( (kind, id.as_str()), (StyleKind::Paragraph, "Normal") @@ -137,26 +169,50 @@ impl Reader<'_> { ), ..Default::default() }; + let mut old_para = None; + let mut old_chr = None; if let Some(p) = s.child("w:pPr") { st.para = self.pc.ppr(p).0; + if let Some(ch) = p.child("w:pPrChange") { + let old = ch.child("w:pPr").map(|o| self.pc.ppr(o).0.formatting()).unwrap_or_default(); + old_para = Some((self.revision(RevisionKind::Format, ch), old)); + } } // Word gives its built-in heading styles their outline level whether or not the file // writes `w:outlineLvl` (some producers leave it out): "heading 2" is level 2 in the // Navigation pane and the table of contents, whatever its id (#4696). if kind == StyleKind::Paragraph && st.builtin - && st.para.outline_level.is_none() && let Some(level) = s.child_val("w:name").and_then(builtin_heading_level) { - st.para.outline_level = Some(level); + if st.para.outline_level.is_none() { + st.para.outline_level = Some(level); + } + if let Some((_, old)) = &mut old_para + && old.outline_level.is_none() + { + old.outline_level = Some(level); + } } if let Some(rp) = s.child("w:rPr") { st.chr = self.pc.rpr(rp); + if let Some(ch) = rp.child("w:rPrChange") { + let old = ch.child("w:rPr").map(|o| self.pc.rpr(o).formatting()).unwrap_or_default(); + old_chr = Some((self.revision(RevisionKind::Format, ch), old)); + } } if kind == StyleKind::Table { let parts = self.table_style_parts(s, &mut st); st.table = (parts != TableStyleParts::default()).then_some(parts); } + // CT_Style has no `stylePrChange`. Keep its two valid revision carriers separate: a + // foreign document may attribute paragraph and run changes to different authors. + if let Some((rev, old)) = old_para { + st.para_change = PropChange::boxed(rev, old); + } + if let Some((rev, old)) = old_chr { + st.chr_change = PropChange::boxed(rev, old); + } // A style defined twice (some generators write their own Heading 1 after a // placeholder one) is the last definition, whole: Word drops the earlier one rather // than merging the two (observed with synthetic documents). @@ -165,6 +221,7 @@ impl Reader<'_> { None => sheet.styles.push(st), } } + self.no_default_table_style = !self.has_default_table_style(&root); // Styles that give only a list level take the list from the style they are based on // (Heading 3: level 3 of Heading 2's outline list). let fixed: Vec> = sheet @@ -181,6 +238,30 @@ impl Reader<'_> { for (s, n) in sheet.styles.iter_mut().zip(fixed) { s.para.numbering = n; } + if !sheet.styles.iter().any(|style| style.kind == StyleKind::Paragraph && style.default) + && normal_is_default == Some(true) + && let Some(normal) = sheet.styles.iter_mut().find(|style| style.kind == StyleKind::Paragraph && style.id == "Normal") + { + normal.default = true; + } + let old_fixed: Vec>> = sheet + .styles + .iter() + .map(|s| { + s.para_change.as_ref().map(|ch| match ch.old.numbering { + Some(n) if n.num == props::LEVEL_ONLY => { + let base = s.based_on.as_deref().and_then(|b| props::chain_list(&sheet, b)); + base.map(|num| craft_wordmodel::props::NumRef { num, level: n.level }) + } + other => other, + }) + }) + .collect(); + for (s, n) in sheet.styles.iter_mut().zip(old_fixed) { + if let (Some(ch), Some(n)) = (&mut s.para_change, n) { + ch.old.numbering = n; + } + } if sheet.default_para.numbering.is_some_and(|n| n.num == props::LEVEL_ONLY) { sheet.default_para.numbering = None; } @@ -250,11 +331,11 @@ impl Reader<'_> { for a in root.children("w:abstractNum").take(10_000) { let Some(id) = a.attr("w:abstractNumId").and_then(u32_of) else { continue }; let mut levels: Vec = (0..9).map(default_level).collect(); + let mut explicit_levels = [false; 9]; for l in a.children("w:lvl") { - let i = l.attr("w:ilvl").and_then(u32_of).unwrap_or(0) as usize; - if let Some(slot) = levels.get_mut(i) { - *slot = self.level(l, i); - } + let Some(i) = numbering_level_index(l.attr("w:ilvl")) else { continue }; + levels[i] = self.level(l, i); + explicit_levels[i] = true; } if let Some(link) = a.child_val("w:numStyleLink") { links.push((id, link.to_string())); @@ -264,6 +345,7 @@ impl Reader<'_> { id, name: a.child_val("w:name").map(str::to_string), levels, + explicit_levels: Some(explicit_levels), nsid: a.child_val("w:nsid").filter(|v| hex(v)).map(str::to_ascii_uppercase), tmpl: a.child_val("w:tmpl").filter(|v| hex(v)).map(str::to_ascii_uppercase), multi_level_type: a @@ -278,7 +360,9 @@ impl Reader<'_> { let (Some(id), Some(abs)) = (n.attr("w:numId").and_then(u32_of), n.child_val("w:abstractNumId").and_then(u32_of)) else { continue }; let (mut start_overrides, mut level_overrides) = (Vec::new(), Vec::new()); for o in n.children("w:lvlOverride").take(9) { - let lvl = o.attr("w:ilvl").and_then(u32_of).unwrap_or(0).min(8) as u8; + let Some(raw_level) = o.attr("w:ilvl") else { continue }; + let Some(lvl) = numbering_level_index(Some(raw_level)) else { continue }; + let lvl = lvl as u8; if let Some(s) = o.child_val("w:startOverride").and_then(u32_of) { start_overrides.push((lvl, s)); } else if let Some(s) = o.child("w:lvl").and_then(|l| l.child_val("w:start")).and_then(u32_of) { @@ -295,9 +379,13 @@ impl Reader<'_> { for (aid, style) in links { let num = self.doc.styles.get(&self.pc.style_id(&style)).and_then(|s| s.para.numbering).map(|n| n.num); let src = num.and_then(|n| nums.iter().find(|x: &&Num| x.id == n)).map(|x| x.abstract_id); - let levels = src.filter(|s| *s != aid).and_then(|s| abstracts.iter().find(|a: &&AbstractNum| a.id == s)).map(|a| a.levels.clone()); - if let (Some(levels), Some(a)) = (levels, abstracts.iter_mut().find(|a| a.id == aid)) { + let source = src + .filter(|s| *s != aid) + .and_then(|s| abstracts.iter().find(|a: &&AbstractNum| a.id == s)) + .map(|a| (a.levels.clone(), a.explicit_levels)); + if let (Some((levels, explicit_levels)), Some(a)) = (source, abstracts.iter_mut().find(|a| a.id == aid)) { a.levels = levels; + a.explicit_levels = explicit_levels; } } Arc::make_mut(&mut self.doc.numbering).abstracts = abstracts; diff --git a/crates/docx/src/units.rs b/crates/docx/src/units.rs index 74edfb13c..295fe7621 100644 --- a/crates/docx/src/units.rs +++ b/crates/docx/src/units.rs @@ -56,8 +56,12 @@ pub fn measure(s: &str, per_pt: f32) -> Option { "emu" => v / 12_700.0, _ => return None, }; - let pt = pt as f32; - pt.is_finite().then_some(pt.clamp(-MAX_LEN_PT, MAX_LEN_PT)) + // Clamp while still in f64: a large but finite OOXML measurement can overflow f32 before + // the output limit is applied, even though its bounded point value is representable. + if pt.is_nan() { + return None; + } + Some(pt.clamp(-f64::from(MAX_LEN_PT), f64::from(MAX_LEN_PT)) as f32) } /// `w:line` under `lineRule="auto"`: the multiple of single line spacing, in 240ths (240 = @@ -196,6 +200,8 @@ mod tests { assert_eq!(measure("nan", 20.0), None); assert_eq!(measure("1e400", 20.0), None); assert_eq!(measure("99999999999999", 20.0), Some(MAX_LEN_PT)); + assert_eq!(measure("1e300pt", 20.0), Some(MAX_LEN_PT)); + assert_eq!(measure("-1e300pt", 20.0), Some(-MAX_LEN_PT)); assert_eq!(measure("x", 20.0), None); // `w:line` auto: the multiple in 240ths without a unit, through twips with one (#2329). assert_eq!(line_multiple("240"), Some(1.0)); diff --git a/crates/docx/src/write/glossary.rs b/crates/docx/src/write/glossary.rs index 35a2289bc..7d5a01791 100644 --- a/crates/docx/src/write/glossary.rs +++ b/crates/docx/src/write/glossary.rs @@ -87,7 +87,7 @@ impl Writer<'_> { } rels.add(rt::GLOSSARY, &file(part), false); push_part(entries, overrides, part, w.into_bytes(), GLOSSARY_CONTENT_TYPE, prels); - push_part(entries, overrides, styles, styles_xml(doc), &format!("{CT_WML}styles+xml"), PartRels::default()); + push_part(entries, overrides, styles, styles_xml(self), &format!("{CT_WML}styles+xml"), PartRels::default()); if lists { push_part(entries, overrides, numbering, numbering_xml(doc), &format!("{CT_WML}numbering+xml"), PartRels::default()); } diff --git a/crates/docx/src/write/parts.rs b/crates/docx/src/write/parts.rs index f1b11e8ff..4cb847276 100644 --- a/crates/docx/src/write/parts.rs +++ b/crates/docx/src/write/parts.rs @@ -126,7 +126,7 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result { } /// `w:id`, `w:author` and `w:date` of a tracked change by revision `idx`. - pub(super) fn change_attrs(&mut self, idx: u32) -> ChangeAttrs { + pub(crate) fn change_attrs(&mut self, idx: u32) -> ChangeAttrs { let (id, author, date) = self.rev_attrs(idx); let mut a = vec![("w:id", id), ("w:author", author)]; if !date.is_empty() { diff --git a/crates/docx/src/write/styles.rs b/crates/docx/src/write/styles.rs index c4013ebff..3bcf9ab97 100644 --- a/crates/docx/src/write/styles.rs +++ b/crates/docx/src/write/styles.rs @@ -1,4 +1,6 @@ -use super::{Document, Level, LevelSuffix, ParaProps, Style, StyleKind, TablePart, VAlign, W, props, xml}; +use super::{Level, LevelSuffix, ParaProps, Style, StyleKind, TablePart, VAlign, W, Writer, props, xml}; +use crate::write::props::open_change; +use craft_wordmodel::Document; /// Built-in names Word keeps in lower case in styles.xml. fn file_style_name(name: &str) -> String { @@ -16,7 +18,8 @@ fn file_style_name(name: &str) -> String { name.to_string() } -pub(super) fn styles_xml(doc: &Document) -> Vec { +pub(super) fn styles_xml(wr: &mut Writer<'_>) -> Vec { + let doc = wr.doc; let s = &doc.styles; let mut w = W::new(); let ns = xml::body_ns(); @@ -50,13 +53,15 @@ pub(super) fn styles_xml(doc: &Document) -> Vec { // Kinds whose default style the file named (`w:default`); the English ids stand in otherwise. let flagged: Vec = s.styles.iter().filter(|st| st.default).map(|st| st.kind).collect(); for st in &s.styles { - style_xml(&mut w, st, &flagged); + style_xml(wr, &mut w, st, &flagged); } w.close("w:styles"); w.into_bytes() } -fn style_xml(w: &mut W, st: &Style, flagged: &[StyleKind]) { +/// One `w:style` element. A tracked change of its paragraph/run properties is nested in the +/// corresponding property element as `w:pPrChange` / `w:rPrChange`. +fn style_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style, flagged: &[StyleKind]) { let ty = match st.kind { StyleKind::Paragraph => "paragraph", StyleKind::Character => "character", @@ -70,9 +75,14 @@ fn style_xml(w: &mut W, st: &Style, flagged: &[StyleKind]) { | (StyleKind::Table, "TableNormal") | (StyleKind::Numbering, "NoList") ); - let is_default = st.default || (english_default && !flagged.contains(&st.kind)); + let normal_is_explicitly_off = st.kind == StyleKind::Paragraph && st.id == "Normal" && !st.default && flagged.contains(&StyleKind::Paragraph); + let is_default = st.default || (english_default && !flagged.contains(&st.kind) && !normal_is_explicitly_off); let mut a = vec![("w:type", ty), ("w:styleId", st.id.as_str())]; - if is_default { + if normal_is_explicitly_off { + // Preserve a model where Normal is explicitly not default. Without this, the fallback + // `english_default` marker makes the reader infer a change on round trip. + a.push(("w:default", "0")); + } else if is_default { a.push(("w:default", "1")); } if !st.builtin { @@ -102,16 +112,7 @@ fn style_xml(w: &mut W, st: &Style, flagged: &[StyleKind]) { if st.locked { w.empty("w:locked", &[]); } - if !st.para.is_empty() && st.kind != StyleKind::Character { - w.open("w:pPr", &[]); - props::ppr_inner(w, &st.para, false, None); - w.close("w:pPr"); - } - if props::has_rpr(&st.chr) && st.kind != StyleKind::Numbering { - w.open("w:rPr", &[]); - props::rpr_inner(w, &st.chr); - w.close("w:rPr"); - } + style_property_xml(wr, w, st); if let Some(t) = &st.table { if t.borders.is_some() || t.cell_margins.is_some() || t.band_size.is_some() || t.col_band_size.is_some() { w.open("w:tblPr", &[]); @@ -179,6 +180,37 @@ fn style_xml(w: &mut W, st: &Style, flagged: &[StyleKind]) { w.close("w:style"); } +fn style_property_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style) { + let para_change = st.para_change.as_deref().filter(|ch| ch.old.formatting() != st.para.formatting()); + if (!st.para.is_empty() || para_change.is_some()) && st.kind != StyleKind::Character { + w.open("w:pPr", &[]); + props::ppr_inner(w, &st.para, false, None); + if let Some(ch) = para_change { + let a = wr.change_attrs(ch.rev); + open_change(w, "w:pPrChange", &a); + w.open("w:pPr", &[]); + props::ppr_inner(w, &ch.old, false, None); + w.close("w:pPr"); + w.close("w:pPrChange"); + } + w.close("w:pPr"); + } + let run_change = st.chr_change.as_deref().filter(|ch| ch.old.formatting() != st.chr.formatting()); + if (props::has_rpr(&st.chr) || run_change.is_some()) && st.kind != StyleKind::Numbering { + w.open("w:rPr", &[]); + props::rpr_inner(w, &st.chr); + if let Some(ch) = run_change { + let a = wr.change_attrs(ch.rev); + open_change(w, "w:rPrChange", &a); + w.open("w:rPr", &[]); + props::rpr_inner(w, &ch.old); + w.close("w:rPr"); + w.close("w:rPrChange"); + } + w.close("w:rPr"); + } +} + pub(super) fn numbering_xml(doc: &Document) -> Vec { let mut w = W::new(); let ns = xml::body_ns(); diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index ff953f43d..bb86755d9 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -373,6 +373,7 @@ fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Res max_depth: MAX_DEPTH + 1, // Text stretches count as nodes too: two for each element. max_nodes: 2 * MAX_ELEMENTS, + max_elements: MAX_ELEMENTS, max_attrs: MAX_ATTRS, max_attrs_total: 2 * MAX_ELEMENTS, }; diff --git a/crates/docx/tests/it/bidi.rs b/crates/docx/tests/it/bidi.rs index 3df1c04c9..bea7e2131 100644 --- a/crates/docx/tests/it/bidi.rs +++ b/crates/docx/tests/it/bidi.rs @@ -175,3 +175,155 @@ fn rtl_tables_and_sections_round_trip() { assert_eq!(again, vec![true, false]); assert!(r.last_section.rtl && r.last_section.columns.count == 2); } + +/// A package whose body is `body` and whose styles part holds `styles`. +fn docx_with_styles(body: &str, styles: &str) -> Vec { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let root = r#""#; + let rels = r#""#; + let doc = format!(r#"{body}"#); + let st = format!(r#"{styles}"#); + zip(&[ + ("_rels/.rels", root.as_bytes()), + ("word/_rels/document.xml.rels", rels.as_bytes()), + ("word/document.xml", doc.as_bytes()), + ("word/styles.xml", st.as_bytes()), + ]) +} + +/// Thai text draws in the complex-script formatting only where Word draws it so (measured in Word +/// for Windows; run defaults Angsana New 22 pt, complex script Tahoma 11 pt bold). Without +/// `w:cs` or `w:rtl` on the run, its paragraph style or the run defaults, Thai text measures as +/// Angsana New 22 pt, whatever its language, `w:hint` or character style. +#[test] +fn thai_text_takes_the_complex_script_formatting_only_in_a_complex_script_run() { + let thai = "ทดสอบ ภาษาไทย"; + let defaults = |extra: &str| { + format!( + r#"{extra} + + + + + + +"# + ) + }; + let latin = ("Angsana New", 22.0, false); + let complex = ("Tahoma", 11.0, true); + let run = |rpr: &str| format!(r#"{rpr}{thai}"#); + let styled = |p: &str, rpr: &str| { + format!(r#"{rpr}{thai}"#) + }; + let in_table = |style: &str| { + format!( + r#"{}"#, + run("") + ) + }; + let cs_off = r#""#; + let cases: Vec<(&str, String, String, (&str, f32, bool))> = vec![ + ("plain", defaults(""), run(""), latin), + ("bidi language", defaults(""), run(r#""#), latin), + ("hint", defaults(""), run(r#""#), latin), + ("character style", defaults(""), run(r#""#), latin), + ("character style rtl", defaults(""), run(r#""#), latin), + ("run cs", defaults(""), run(""), complex), + ("run rtl", defaults(""), run(""), complex), + ("paragraph style", defaults(""), styled("CsPara", ""), complex), + ("paragraph style, run cs off", defaults(""), styled("CsPara", r#""#), latin), + ("run defaults", defaults(""), run(""), complex), + // A character style's `w:cs w:val="0"` doesn't turn the paragraph style's or the run + // defaults' off either. + ("paragraph style, character style cs off", defaults(""), styled("CsPara", cs_off), complex), + ("run defaults, character style cs off", defaults(""), run(cs_off), complex), + // A table style's `w:cs` counts, and its sizes are the run's. + ("table style", defaults(""), in_table("CsTable"), complex), + ("table style sizes", defaults(""), in_table("SizeTable"), ("Angsana New", 15.0, false)), + ]; + let check = |d: &Document, name: &str, want: (&str, f32, bool), when: &str| { + let (p, table) = match &*d.body[0] { + craft_wordmodel::Block::Table(t) => { + (t.rows[0].cells[0].blocks[0].as_para().unwrap(), d.styles.table_cells_chr(t).map(|c| c[0][0].clone())) + } + b => (b.as_para().unwrap(), None), + }; + let rc = d.styles.resolve_char_in(p.props.style.as_deref(), table.as_ref(), &p.runs[0].props); + for ch in p.text.chars() { + let drawn = if rc.uses_complex(ch) { rc.complex() } else { rc.clone() }; + assert_eq!((drawn.font.as_str(), drawn.size, drawn.bold), want, "{name} {when}: {ch:?}"); + } + let c = &p.runs[0].props; + assert_eq!((c.font_cs.as_deref(), c.size_cs, c.bold_cs), (None, None, None), "{name} {when}: nothing is pinned"); + }; + for (name, styles, body, want) in &cases { + let d = craft_docx::read(&docx_with_styles(body, styles)).unwrap(); + check(&d, name, *want, "read"); + let again = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + check(&again, name, *want, "after a save"); + } + // Latin text and right-to-left text are left as they were. + let body = r#"Latin onlyسلام"#; + let d = craft_docx::read(&docx_with_styles(body, &defaults(""))).unwrap(); + for p in paras(&d) { + assert_eq!(p.runs[0].props.cs, None, "{}", p.text); + } + // Latin text follows the same rule (measured): a character style's `w:cs` or `w:rtl` leaves it in the + // run's own formatting, a character style's `w:cs w:val="0"` under a paragraph style's + // `w:cs` in the complex-script formatting. + let latin_in = + |p: &str, rpr: &str| format!(r#"{rpr}Latin"#); + let body = + latin_in("Normal", r#""#) + &latin_in("CsPara", cs_off) + &latin_in("Normal", r#""#); + let d = craft_docx::read(&docx_with_styles(&body, &defaults(""))).unwrap(); + let again = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + for (d, when) in [(&d, "read"), (&again, "after a save")] { + let drawn: Vec<_> = paras(d) + .iter() + .map(|p| { + let rc = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[0].props); + let c = if rc.uses_complex('L') { rc.complex() } else { rc }; + (c.font, c.size) + }) + .collect(); + assert_eq!(drawn, [("Angsana New".to_string(), 22.0), ("Tahoma".to_string(), 11.0), ("Angsana New".to_string(), 22.0)], "{when}"); + } +} + +/// Measured in Word for Windows: Thai text as a field's result follows the same rule as ordinary +/// text, also when the reader keeps the field as one object with its result. +#[test] +fn a_fields_thai_result_takes_the_complex_script_formatting_only_in_a_complex_script_run() { + let styles = r#" +"#; + let field = |rpr: &str| { + let r = |inner: &str| format!("{rpr}{inner}"); + format!( + "{}{}{}{}{}", + r(r#""#), + r(r#" QUOTE "x" "#), + r(r#""#), + r("ทดสอบ"), + r(r#""#) + ) + }; + let drawn = |d: &Document| { + let p = paras(d)[0]; + let at = p.text.find(craft_wordmodel::para::OBJ).expect("the field is one object"); + let run = p.runs.iter().scan(0, |end, r| { + let start = *end; + *end += r.len; + Some((start, r)) + }); + let (_, run) = run.into_iter().find(|(start, r)| *start <= at && at < start + r.len).unwrap(); + let rc = d.styles.resolve_char(p.props.style.as_deref(), &run.props); + if rc.uses_complex('ท') { (rc.font_cs.clone(), rc.size_cs) } else { (rc.font.clone(), rc.size) } + }; + for (what, rpr, want) in [("nothing", "", ("Angsana New", 10.0)), ("w:cs", "", ("Tahoma", 20.0))] { + let d = craft_docx::read(&docx_with_styles(&field(rpr), styles)).unwrap(); + assert_eq!(drawn(&d), (want.0.to_string(), want.1), "a run with {what}: read"); + let again = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + assert_eq!(drawn(&again), (want.0.to_string(), want.1), "a run with {what}: after a save"); + } +} diff --git a/crates/docx/tests/it/cell_margin_inheritance.rs b/crates/docx/tests/it/cell_margin_inheritance.rs index f4d8de5a5..83aafc7d0 100644 --- a/crates/docx/tests/it/cell_margin_inheritance.rs +++ b/crates/docx/tests/it/cell_margin_inheritance.rs @@ -28,3 +28,73 @@ fn partial_margin_stays_partial() { assert!(!margins.contains(") -> Vec { + const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + let mut add = |name: &str, xml: &str| { + zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(xml.as_bytes()).unwrap(); + }; + add("word/document.xml", &format!(r#"{body}"#)); + if let Some(styles) = styles { + add("word/styles.xml", &format!(r#"{styles}"#)); + add( + "word/_rels/document.xml.rels", + r#""#, + ); + } + zip.finish().unwrap().into_inner() +} + +/// Without a default table style (no styles part, or none marked `w:default`) Word gives a table +/// no cell margins: a cell that sets only its right margin has none on its other sides. +#[test] +fn no_default_table_style_means_no_cell_margins() { + let body = r#""#; + let normal_table = r#""#; + let margins = |styles: Option<&str>| { + let doc = craft_docx::read(&package(body, styles)).unwrap(); + let table = doc.body[0].as_table().unwrap(); + (table.props.cell_margins, table.rows[0].cells[0].props.resolved_margins(table.props.cell_margins.unwrap_or([0.0, 5.4, 0.0, 5.4]))) + }; + assert_eq!(margins(None), (Some([0.0; 4]), [0.0, 0.0, 0.0, 5.4])); + assert_eq!(margins(Some(r#""#)), (Some([0.0; 4]), [0.0, 0.0, 0.0, 5.4])); + // With Word's usual Normal Table the table keeps no margins of its own (the defaults apply). + assert_eq!(margins(Some(normal_table)).0, None); + // A style defined twice is its last definition: a default one redefined as not default leaves none. + let redefined = format!(r#"{normal_table}"#); + assert_eq!(margins(Some(&redefined)).0, Some([0.0; 4])); + // A custom default table style marked `on` is a default too, also after saving and reopening. + let plain = r#""#; + let doc = craft_docx::read(&package(body, Some(plain))).unwrap(); + assert_eq!(doc.body[0].as_table().unwrap().props.cell_margins, None); + let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert_eq!(reopened.body[0].as_table().unwrap().props.cell_margins, None); + // A table that sets only some sides keeps them; the sides it omits are 0. + let partial = body.replace("", r#""#); + let doc = craft_docx::read(&package(&partial, None)).unwrap(); + assert_eq!(doc.body[0].as_table().unwrap().props.cell_margins, Some([0.0, 7.2, 0.0, 0.0])); + // Rejecting a tracked change to the table's properties brings back the same zero margins. + let tracked = body.replace( + "", + r#""#, + ); + let doc = craft_docx::read(&package(&tracked, None)).unwrap(); + let change = doc.body[0].as_table().unwrap().props.fmt_change.as_deref().expect("a tracked table change"); + assert_eq!(change.old.cell_margins, Some([0.0; 4])); + // A table whose own style gives margins keeps them. + let styled = body.replace("", r#""#); + let boxed = r#""#; + let doc = craft_docx::read(&package(&styled, Some(boxed))).unwrap(); + assert_eq!(doc.body[0].as_table().unwrap().props.cell_margins, None); + // The zeros survive saving, which writes a default Normal Table. + let doc = craft_docx::read(&package(body, None)).unwrap(); + let bytes = craft_docx::write(&doc).unwrap(); + let mut xml = String::new(); + zip::ZipArchive::new(Cursor::new(bytes.clone())).unwrap().by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap(); + assert!(xml.contains(""), "{xml}"); + let reopened = craft_docx::read(&bytes).unwrap(); + assert_eq!(reopened.body[0].as_table().unwrap().props.cell_margins, Some([0.0; 4])); +} diff --git a/crates/docx/tests/it/note_comments.rs b/crates/docx/tests/it/note_comments.rs index d333c6adb..749f65897 100644 --- a/crates/docx/tests/it/note_comments.rs +++ b/crates/docx/tests/it/note_comments.rs @@ -17,6 +17,10 @@ fn note(tag: &str, mark: &str, comment: u32, text: &str) -> String { } fn read_doc() -> Document { + read_doc_with_note_relationships(true) +} + +fn read_doc_with_note_relationships(with_note_relationships: bool) -> Document { let doc = format!( r#"Body"# ); @@ -25,10 +29,15 @@ fn read_doc() -> Document { let comments = format!( r#"On the footnoteOn the endnote"# ); + let doc_rels = if with_note_relationships { + DOC_RELS + } else { + r#""# + }; let bytes = zip(&[ ("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes()), - ("word/_rels/document.xml.rels", DOC_RELS.as_bytes()), + ("word/_rels/document.xml.rels", doc_rels.as_bytes()), ("word/footnotes.xml", footnotes.as_bytes()), ("word/endnotes.xml", endnotes.as_bytes()), ("word/comments.xml", comments.as_bytes()), @@ -36,6 +45,26 @@ fn read_doc() -> Document { craft_docx::read(&bytes).unwrap() } +#[test] +fn conventional_note_parts_are_read_without_relationships() { + let d = read_doc_with_note_relationships(false); + let body = d.body[0].as_para().unwrap(); + let refs: Vec<(NoteKind, u32)> = body + .objects + .iter() + .filter_map(|o| match o { + InlineObject::NoteRef { kind, id, .. } => Some((*kind, *id)), + _ => None, + }) + .collect(); + assert_eq!(refs.iter().map(|(kind, _)| *kind).collect::>(), [NoteKind::Footnote, NoteKind::Endnote]); + for ((kind, id), wanted) in refs.into_iter().zip(["Foot.", "End."]) { + let part = d.parts.get(&id).unwrap_or_else(|| panic!("missing {kind:?} part {id}")); + let text = part.blocks[0].as_para().unwrap().plain_text(); + assert!(text.contains(wanted), "{kind:?}: {text:?}"); + } +} + /// comments.xml has to be read before the notes: a note's `w:commentRangeStart` resolves its id /// against the comments already read, and was dropped when the notes came first. #[test] diff --git a/crates/docx/tests/it/passthrough.rs b/crates/docx/tests/it/passthrough.rs index f59131e17..9d3176a76 100644 --- a/crates/docx/tests/it/passthrough.rs +++ b/crates/docx/tests/it/passthrough.rs @@ -320,6 +320,34 @@ fn list_identities_survive_and_a_copied_definition_gets_none() { assert_eq!(n.matches("1F2E3D4C").count(), 1, "{n}"); } +#[test] +fn malformed_numbering_levels_are_skipped_instead_of_becoming_level_zero() { + let numbering = r#""#; + let body = r#"default levelvalid levelnegative levelout of rangeoverflow"#; + let bytes = package(body, &[("rId1", &format!("{REL}/numbering"), "numbering.xml")], &[], &[("word/numbering.xml", numbering)]); + let doc = craft_docx::read(&bytes).unwrap(); + let paragraphs: Vec<_> = doc + .body + .iter() + .filter_map(|block| match &**block { + craft_wordmodel::Block::Para(p) => Some(p), + _ => None, + }) + .collect(); + assert_eq!(paragraphs.len(), 5); + assert!(doc.numbering.level_is_defined(1, 0)); + assert!(!doc.numbering.level_is_defined(1, 2), "effective defaults remain distinguishable from source definitions"); + assert!(doc.numbering.level(1, 2).is_some(), "Word's effective default level remains available"); + assert_eq!(paragraphs[0].props.numbering.map(|n| (n.num, n.level)), Some((1, 0)), "an omitted level defaults to zero"); + assert_eq!(paragraphs[1].props.numbering.map(|n| (n.num, n.level)), Some((1, 2)), "a valid level is preserved"); + for p in ¶graphs[2..] { + assert_eq!(p.props.numbering, None, "malformed explicit level is not treated as a real list: {}", p.text); + } + let level_zero = doc.numbering.level(1, 0).expect("the valid level zero"); + assert_eq!(level_zero.format, craft_wordmodel::section::NumFormat::Decimal); + assert_eq!(level_zero.start, 1, "invalid level overrides do not affect level zero"); +} + #[test] fn extended_properties_are_kept_without_words_counts_and_personal_ones_follow_the_privacy_setting() { let app = r#"4210740000250000Microsoft Office Word020001700falseMFirmafalse290000falsehttps://example.com/false16.0000"#; diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 0ee245180..8f3bbdd0b 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -269,6 +269,7 @@ fn styles_and_lists_round_trip() { locked: true, default: false, table: None, + ..Default::default() }); Arc::make_mut(&mut d.styles).upsert(Style { id: "MyStyleChar".into(), diff --git a/crates/docx/tests/it/undefined_style.rs b/crates/docx/tests/it/undefined_style.rs index c50394a2a..a00ac4323 100644 --- a/crates/docx/tests/it/undefined_style.rs +++ b/crates/docx/tests/it/undefined_style.rs @@ -3,12 +3,20 @@ //! `` without defining Footer. use craft_wordmodel::props::LineSpacing; use craft_wordmodel::{Block, Document, PartKind}; -use std::io::Write; +use std::io::{Read, Write}; const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; const R: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; fn package(normal_id: &str) -> Vec { + package_with_default(normal_id, true) +} + +fn package_with_default(normal_id: &str, is_default: bool) -> Vec { + package_with_body_default(normal_id, is_default, false) +} + +fn package_with_body_default(normal_id: &str, is_default: bool, has_body_default: bool) -> Vec { let root = r#""#; let doc = format!( r#"bodynormal"# @@ -16,8 +24,11 @@ fn package(normal_id: &str) -> Vec { let footer = format!( r#"1"# ); + let default_attr = if is_default { r#" w:default="1""# } else { "" }; + let body_style = + if has_body_default { r#""# } else { "" }; let styles = format!( - r#""# + r#"{body_style}"# ); let rels = r#""#; let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); @@ -34,6 +45,27 @@ fn package(normal_id: &str) -> Vec { zw.finish().unwrap().into_inner() } +#[test] +fn an_explicit_normal_style_is_the_default_even_without_w_default() { + let doc = craft_docx::read(&package_with_default("Normal", false)).unwrap(); + let normal = doc.styles.get("Normal").expect("the explicit Normal style"); + assert!(normal.default, "Word treats the explicitly declared built-in Normal style as the default"); +} + +#[test] +fn an_explicit_body_default_on_prevents_normal_inference() { + let doc = craft_docx::read(&package_with_body_default("Normal", false, true)).unwrap(); + assert!(doc.styles.styles.iter().any(|style| style.id == "Body" && style.default)); + assert!(!doc.styles.styles.iter().any(|style| style.id == "Normal" && style.default)); + let saved = craft_docx::write(&doc).unwrap(); + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(saved)).unwrap(); + let mut file = archive.by_name("word/styles.xml").unwrap(); + let mut styles = String::new(); + file.read_to_string(&mut styles).unwrap(); + assert!(styles.contains(r#"w:styleId="Normal" w:default="0""#) || styles.contains(r#"w:default="0" w:styleId="Normal""#)); + assert!(styles.contains(r#"w:styleId="Body" w:default="1""#) || styles.contains(r#"w:default="1" w:styleId="Body""#)); +} + fn footer_para(d: &Document) -> &craft_wordmodel::Paragraph { let part = d.parts.values().find(|p| p.kind == PartKind::Footer).expect("a footer"); match part.blocks.first().map(|b| &**b) { @@ -69,3 +101,37 @@ fn an_undefined_style_is_written_back_as_it_was_named() { assert_eq!(footer_para(&again).props.style.as_deref(), Some("Footer")); assert_eq!(again.styles.resolve_para(&footer_para(&again).props).space_after, 2.0); } + +#[test] +fn conventional_styles_and_numbering_parts_without_relationships_are_read() { + // The old DesignCraft reader opened these conventional paths directly. Keep that tolerated + // input behavior while preferring OPC relationships whenever they resolve successfully. + let doc = format!( + r#"text"# + ); + let styles = format!(r#""#); + let numbering = format!( + r#""# + ); + for main_path in ["word/document.xml", "WORD/DOCUMENT.XML"] { + let root = format!( + r#""# + ); + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, body) in [ + ("_rels/.rels", root.as_str()), + (main_path, doc.as_str()), + ("word/styles.xml", styles.as_str()), + ("word/numbering.xml", numbering.as_str()), + ] { + zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(body.as_bytes()).unwrap(); + } + let d = craft_docx::read(&zw.finish().unwrap().into_inner()).unwrap(); + assert!(d.styles.styles.iter().any(|style| style.id == "Body")); + let Some(Block::Para(p)) = d.body.first().map(|b| &**b) else { panic!("a body paragraph") }; + assert_eq!(p.props.style.as_deref(), Some("Body")); + assert_eq!(p.props.numbering.map(|n| (n.num, n.level)), Some((7, 0))); + assert!(d.numbering.level(7, 0).is_some()); + } +} diff --git a/crates/dwg/Cargo.toml b/crates/dwg/Cargo.toml new file mode 100644 index 000000000..d2bc8ffff --- /dev/null +++ b/crates/dwg/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "craft-dwg" +description = "Bounded DWG↔DXF byte bridge with an optional child-process worker" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +# acadrust is used unmodified and only on targets supported by its 0.6.6 platform APIs. +[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dependencies] +acadrust = { workspace = true } +log = { workspace = true } diff --git a/crates/dwg/README.md b/crates/dwg/README.md new file mode 100644 index 000000000..80088a89e --- /dev/null +++ b/crates/dwg/README.md @@ -0,0 +1,20 @@ +# craft-dwg + +A byte-level bridge between DWG and DXF. It does not expose `acadrust` types: callers pass bytes, +choose limits, and receive converted bytes plus notes about data the conversion could not preserve. +Application document mapping remains with the caller. + +The default limits reject DWG inputs over 512 MiB and stop DXF output over 1 GiB. The bridge +also catches panics from the dependency and validates its conversion diagnostics. Because a small +hostile file can declare very large internal sections, size checks alone cannot prevent an +allocation failure inside the decoder. On native applications, call `use_own_worker()` during +startup and call `serve_if_asked()` before normal argument handling. Subsequent `decode` and +`encode_*` calls then run in a child process with a 30-minute timeout; a crash or stack overflow +is contained to that child. The worker has no operating-system memory limit yet. Without a +configured worker, conversions are refused rather than run in the current process: call +`allow_in_process()` only for input that is known to be trusted (tests, or bytes this process +produced itself). Coordinates, once a worker is configured but cannot start, also fail closed. + +The bridge is not built for `wasm32` or FreeBSD/aarch64. Those targets retain the public API and +return a clear unsupported-build error. The `acadrust` 0.6.6 dependency is used unmodified under +MPL-2.0; its license and third-party notices are in `licenses/dwg/` at the workspace root. diff --git a/crates/dwg/build.rs b/crates/dwg/build.rs new file mode 100644 index 000000000..e97782ab4 --- /dev/null +++ b/crates/dwg/build.rs @@ -0,0 +1,12 @@ +//! Sets `no_dwg_bridge` on the targets built without acadrust (see Cargo.toml): the DWG functions +//! there return an error that says to use DXF. + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo::rustc-check-cfg=cfg(no_dwg_bridge)"); + let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(); + let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + if arch == "wasm32" || (os == "freebsd" && arch == "aarch64") { + println!("cargo::rustc-cfg=no_dwg_bridge"); + } +} diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs new file mode 100644 index 000000000..05c1a673c --- /dev/null +++ b/crates/dwg/src/lib.rs @@ -0,0 +1,2106 @@ +//! DWG support through a DXF bridge. +//! +//! DWG files are read with the `acadrust` crate (MPL-2.0, used unmodified as a dependency) and +//! converted to DXF bytes for the caller's DXF reader; saving goes the other way. Keeping the +//! dependency behind this byte-level API prevents its document types from leaking to consumers. +//! Native targets only (the dependency memory-maps files). +//! +//! # Guardrails around the third-party decoder +//! +//! The decoder allocates tables and section buffers from sizes a (possibly damaged or hostile) +//! file declares, and once it starts it cannot be interrupted (an allocation failure aborts the +//! process, which `catch_unwind` cannot recover). Because the dependency is used unmodified, this +//! crate guards it from the outside: +//! +//! - Both directions reject oversized input *before* the decoder runs ([`Limits::max_dwg_bytes`] +//! for DWG→DXF, [`Limits::max_dxf_bytes`] for DXF→DWG), and the DWG→DXF output is capped while +//! it is written (`CappedWriter`). +//! - The reader and writer run inside `catch_unwind`, so a decode failure is reported instead of +//! crashing. +//! +//! These bound the input- and output-size variants. A small file that declares a huge internal +//! table or section can still make the dependency allocate before any size is known, so the app +//! runs both directions in a child process ([`worker`]): what that kills is the child. +//! +//! Isolation is not optional for untrusted input. With no worker configured the conversion is +//! refused rather than run here, and a worker that cannot start is an error, so a missing worker +//! never turns into decoding a hostile file in the caller's process. [`worker::allow_in_process`] +//! is the explicit exception, for input the caller knows is trusted. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +/// DWG version codes we can write. +pub const VERSIONS: &[(&str, &str)] = + &[("AC1015", "2000"), ("AC1018", "2004"), ("AC1021", "2007"), ("AC1024", "2010"), ("AC1027", "2013"), ("AC1032", "2018")]; + +/// True when the bytes look like a DWG file (`AC10xx` magic). +pub fn is_dwg(bytes: &[u8]) -> bool { + bytes.len() > 6 && bytes.starts_with(b"AC10") && bytes.get(4..6).is_some_and(|v| v.iter().all(u8::is_ascii_digit)) +} + +/// The DWG version code of a file (e.g. "AC1032"). +pub fn version(bytes: &[u8]) -> Option { + is_dwg(bytes).then(|| String::from_utf8_lossy(bytes.get(0..6).unwrap_or_default()).to_string()) +} + +/// Size limits for reading a DWG file. DWG is compressed and the DXF text it converts to is +/// several times larger (about 6x in our tests: a 10 MB DWG becomes about 60 MB of DXF), so +/// the limits are generous for real drawings. They exist because a damaged file, or one the reader +/// misreads, can make the DWG reader produce a drawing thousands of times larger than the file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// Largest DWG file read at all (checked before reading starts). + pub max_dwg_bytes: usize, + /// Largest DXF rendition of a DWG (checked while it is written). + pub max_dxf_bytes: usize, +} + +impl Limits { + /// 512 MB of DWG, 1 GB of DXF (more than the DXF reader's group-code limit fills). + pub const DEFAULT: Limits = Limits { max_dwg_bytes: 512 << 20, max_dxf_bytes: 1 << 30 }; +} + +/// A byte count in megabytes for messages ("9.9 MB", "1024 MB"). +#[cfg_attr(no_dwg_bridge, allow(dead_code))] +fn mb(n: u64) -> String { + let m = n as f64 / f64::from(1u32 << 20); + if m >= 100.0 { format!("{m:.0} MB") } else { format!("{m:.1} MB") } +} + +#[cfg(not(no_dwg_bridge))] +pub mod worker; +#[cfg(not(no_dwg_bridge))] +pub use worker::{ + WORKER_ARG, allow_in_process, crash_worker_for_test, decode, encode_as, encode_kept_noted, encode_noted, serve_if_asked, use_own_worker, + use_worker, +}; +#[cfg(not(no_dwg_bridge))] +mod proxy_transport; + +#[cfg(not(no_dwg_bridge))] +mod native { + use std::io::{Cursor, Write}; + use std::panic::AssertUnwindSafe; + + use super::{Limits, mb}; + + /// Read DWG bytes and return an ASCII DXF rendition, within [`Limits::DEFAULT`]. + pub fn dwg_to_dxf(bytes: &[u8]) -> Result, String> { + dwg_to_dxf_with(bytes, Limits::DEFAULT) + } + + /// [`dwg_to_dxf`] with explicit limits. Both are checked before the expensive step they + /// guard: the input size before the DWG reader runs, the DXF size while it is written, so a + /// runaway conversion stops at the limit instead of filling memory first. + pub fn dwg_to_dxf_with(bytes: &[u8], limits: Limits) -> Result, String> { + dwg_to_dxf_noted(bytes, limits).map(|(dxf, _)| dxf) + } + + /// [`dwg_to_dxf_with`], also returning notes on what the read left out. The reader runs in + /// failsafe mode: an object record it can't decode is skipped instead of failing the whole + /// file, and the notes say how many were skipped and of which types, so a partial read never + /// passes for a complete one. + pub fn dwg_to_dxf_noted(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { + if bytes.len() > limits.max_dwg_bytes { + return Err(format!( + "DWG: the file is {}, larger than the {} accepted by this bridge", + mb(bytes.len() as u64), + mb(limits.max_dwg_bytes as u64) + )); + } + let outcome = std::panic::catch_unwind(|| { + acadrust::DwgReader::from_stream_with_options(Cursor::new(bytes), acadrust::DwgReadOptions::failsafe()).read_with_stats() + }) + .map_err(|_| "the DWG reader failed on this file".to_string())? + .map_err(|e| format!("DWG: {e}"))?; + // Failsafe skips records, not whole files: when the objects stream itself couldn't be + // read (a damaged header or section map, or not a DWG at all), nothing was read. + if !outcome.stats.record_stream_read { + let why = outcome.stats.diagnostics.first().map(|d| d.message.trim_start_matches("Failsafe: ").to_string()); + return Err(format!("DWG: {}", why.unwrap_or_else(|| "the file's objects couldn't be read".to_string()))); + } + let mut notes = read_notes(&outcome.stats); + let mut doc = outcome.document; + notes.extend( + guarded(AssertUnwindSafe(|| application_objects(&mut doc))).map_err(|_| "the DWG application object conversion failed".to_string())?, + ); + // After application_objects, so the proxy objects it makes are numbered as the DXF's. + notes.extend( + guarded(AssertUnwindSafe(|| super::proxy_transport::prepare(&mut doc))).map_err(|_| "the DWG proxy conversion failed".to_string())?, + ); + let orphans = guarded(AssertUnwindSafe(|| post_process(&mut doc))).map_err(|_| "the DWG post-processing failed on this file".to_string())?; + if orphans > 0 { + let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") }; + notes.push(format!("DWG: {orphans} DGN line style component{s} that no line style definition uses {were} left out")); + } + let mut out = CappedWriter { buf: Vec::new(), limit: limits.max_dxf_bytes, exceeded: false }; + let written = std::panic::catch_unwind(AssertUnwindSafe(|| { + acadrust::DxfWriter::new(&doc).write_to_writer(&mut out)?; + mtext_contents(&doc, &mut out) + })) + .map_err(|_| "the DWG→DXF conversion failed on this file".to_string())?; + if out.exceeded { + return Err(format!( + "DWG: converting this {} file produced more than {} of drawing data (the limit); \ + the file is probably damaged, or uses objects the DWG reader misreads", + mb(bytes.len() as u64), + mb(limits.max_dxf_bytes as u64) + )); + } + written.map_err(|e| format!("DWG→DXF: {e}"))?; + Ok((add_header_vars(out.buf, &doc.header), notes)) + } + + /// acadrust 0.6.6's ASCII writer treats a caret followed by a literal space as already + /// escaped, and turns line feeds into paragraph codes. Serialize affected MTEXT contents + /// from the native values instead, using its lossless string writer. All other groups, + /// including embedded-object data, remain byte-for-byte as the DXF writer emitted them. + fn mtext_contents(doc: &acadrust::CadDocument, out: &mut CappedWriter) -> acadrust::Result<()> { + use acadrust::io::dxf::{DxfStreamWriter, DxfTextWriter}; + let contents: std::collections::HashMap<_, _> = doc + .entities() + .filter_map(|e| match e { + acadrust::EntityType::MText(t) if t.value.contains(['^', '\t', '\n']) => Some((t.common.handle.value(), t.value.as_str())), + _ => None, + }) + .collect(); + if contents.is_empty() { + return Ok(()); + } + let dxf = std::mem::take(&mut out.buf); + let mut lines = dxf.split_inclusive(|b| *b == b'\n'); + let (mut mtext, mut text, mut written) = (false, None, false); + while let Some(code) = lines.next() { + let value = lines.next().ok_or_else(|| std::io::Error::other("incomplete DWG bridge DXF pair"))?; + match code.trim_ascii() { + b"0" => { + mtext = value.trim_ascii() == b"MTEXT"; + text = None; + written = false; + } + b"5" if mtext => { + text = std::str::from_utf8(value.trim_ascii()).ok().and_then(|s| u64::from_str_radix(s, 16).ok()).and_then(|h| contents.get(&h)); + } + b"101" => mtext = false, + b"1" | b"3" if mtext && text.is_some() => { + if let Some(&text) = text + && !written + { + let mut writer = DxfTextWriter::new(&mut *out); + if doc.version < acadrust::DxfVersion::AC1021 + && let Some(encoding) = acadrust::io::dxf::code_page::encoding_from_code_page(&doc.header.code_page) + { + writer.set_encoding(encoding); + } + // Each character can expand to two caret-escape characters. Keep + // those pairs together and each group within 250 characters. + let mut rest = text; + while let Some((end, _)) = rest.char_indices().nth(125) { + let (chunk, tail) = rest.split_at(end); + writer.write_xrecord_string(3, chunk)?; + rest = tail; + } + writer.write_xrecord_string(1, rest)?; + written = true; + } + continue; + } + _ => {} + } + out.write_all(code)?; + out.write_all(value)?; + } + Ok(()) + } + + #[cfg(test)] + #[test] + fn mtext_contents_keeps_other_groups_and_the_output_limit() -> acadrust::Result<()> { + for version in [acadrust::DxfVersion::AC1015, acadrust::DxfVersion::AC1032] { + let mut doc = acadrust::CadDocument::new(); + doc.version = version; + doc.header.code_page = "ANSI_1252".into(); + let mut t = acadrust::MText::with_value("é ^ C", acadrust::Vector3::ZERO); + t.common.handle = acadrust::Handle::new(0x10); + doc.add_entity(acadrust::EntityType::MText(Box::new(t)))?; + // Only the MTEXT's own 1/3 groups change. The embedded object's groups and the + // following TEXT record must survive byte-for-byte, including their spaces. + let prefix = b" 0\r\nMTEXT\r\n 5\r\n10\r\n 8\r\n0\r\n"; + let suffix = b"101\r\nEmbedded Object\r\n 1\r\n^ embedded\r\n 3\r\n^ tail\r\n 0\r\nTEXT\r\n 1\r\n^ plain\r\n"; + let raw = [prefix.as_slice(), b" 3\r\nold\r\n 1\r\ntext\r\n", suffix.as_slice()].concat(); + let mut out = CappedWriter { buf: raw.clone(), limit: 4096, exceeded: false }; + mtext_contents(&doc, &mut out)?; + let value: &[u8] = if version == acadrust::DxfVersion::AC1015 { b"\xe9 ^ C" } else { "é ^ C".as_bytes() }; + assert_eq!(out.buf, [prefix.as_slice(), b" 1\r\n", value, b"\r\n", suffix.as_slice()].concat()); + let mut limited = CappedWriter { buf: raw, limit: 1, exceeded: false }; + assert!(mtext_contents(&doc, &mut limited).is_err()); + assert!(limited.exceeded); + } + Ok(()) + } + + /// Most record types named in the skipped-records note. + const NOTE_TYPES: usize = 6; + + /// The note on object records a failsafe read skipped: how many, and how many of each type + /// (most first), or nothing when the read was complete. + pub(crate) fn read_notes(stats: &acadrust::ReadStats) -> Vec { + let skipped = stats.skipped_source_records; + if skipped == 0 { + return Vec::new(); + } + let label = |t: Option<&str>| match t.map(str::parse::) { + Some(Ok(code)) => type_name(code).map_or_else(|| format!("type {code}"), str::to_string), + Some(Err(_)) => t.unwrap_or_default().to_string(), + None => "unknown".to_string(), + }; + let mut by_type: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for d in stats.diagnostics.iter().filter(|d| d.record_handle.is_some()) { + *by_type.entry(label(d.record_type.as_deref())).or_default() += 1; + } + let mut types: Vec<(String, usize)> = by_type.into_iter().collect(); + types.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + let mut list: Vec = types.iter().take(NOTE_TYPES).map(|(t, n)| format!("{t} × {n}")).collect(); + if types.len() > NOTE_TYPES { + list.push(format!("{} more types", types.len() - NOTE_TYPES)); + } + let of = if stats.source_records > 0 { format!(" of {}", stats.source_records) } else { String::new() }; + let records = if skipped == 1 && of.is_empty() { "object record" } else { "object records" }; + let (were, them) = if skipped == 1 { ("was", "it") } else { ("were", "them") }; + let which = if list.is_empty() { String::new() } else { format!(" ({})", list.join(", ")) }; + vec![format!( + "DWG: {skipped}{of} {records} couldn't be read and {were} left out{which}; \ + saving over the original file would lose {them}" + )] + } + + /// The DXF name of a DWG object type code with a fixed number (classes, 500 and up, are + /// numbered per file). + fn type_name(code: i16) -> Option<&'static str> { + Some(match code { + 1 => "TEXT", + 2 => "ATTRIB", + 3 => "ATTDEF", + 4 => "BLOCK", + 5 => "ENDBLK", + 6 => "SEQEND", + 7 => "INSERT", + 8 => "MINSERT", + 10..=14 => "VERTEX", + 15 | 16 | 29 | 30 => "POLYLINE", + 17 => "ARC", + 18 => "CIRCLE", + 19 => "LINE", + 20..=26 => "DIMENSION", + 27 => "POINT", + 28 => "3DFACE", + 31 => "SOLID", + 32 => "TRACE", + 33 => "SHAPE", + 34 => "VIEWPORT", + 35 => "ELLIPSE", + 36 => "SPLINE", + 37 => "REGION", + 38 => "3DSOLID", + 39 => "BODY", + 40 => "RAY", + 41 => "XLINE", + 42 => "DICTIONARY", + 43 => "OLEFRAME", + 44 => "MTEXT", + 45 => "LEADER", + 46 => "TOLERANCE", + 47 => "MLINE", + 48 => "BLOCK_CONTROL", + 49 => "BLOCK_RECORD", + 50 => "LAYER_CONTROL", + 51 => "LAYER", + 52 => "STYLE_CONTROL", + 53 => "STYLE", + 56 => "LTYPE_CONTROL", + 57 => "LTYPE", + 60 => "VIEW_CONTROL", + 61 => "VIEW", + 62 => "UCS_CONTROL", + 63 => "UCS", + 64 => "VPORT_CONTROL", + 65 => "VPORT", + 66 => "APPID_CONTROL", + 67 => "APPID", + 68 => "DIMSTYLE_CONTROL", + 69 => "DIMSTYLE", + 70 => "VX_CONTROL", + 71 => "VX_TABLE_RECORD", + 72 => "GROUP", + 73 => "MLINESTYLE", + 74 => "OLE2FRAME", + 77 => "LWPOLYLINE", + 78 => "HATCH", + 79 => "XRECORD", + 80 => "ACDBPLACEHOLDER", + 82 => "LAYOUT", + _ => return None, + }) + } + + /// Merged table cells onto the cells. acadrust 0.6.3 reads a 2010+ (AC1024+) DWG table's + /// merged cells into the table's `merged_ranges` only, while its DXF writer writes each cell's + /// own merge groups (173, 175, 176), so without this the merges would be lost. Tables whose + /// cells already carry merges are left alone. Each range's first cell gets the span; the + /// cells it covers are marked merged with no span of their own, as CADCraft's DXF writer does. + fn table_merges(doc: &mut acadrust::CadDocument) { + table_merges_within(doc, MAX_MERGE_CELLS); + } + + /// The most table cells [`table_merges`] visits in one document: each range is capped, but + /// can cover rows × cols cells, so the total is bounded too. + const MAX_MERGE_CELLS: usize = 1 << 24; + + /// A table cell's own text height only when the file says it overrides the table style's. + /// acadrust's DXF writer writes a cell style's height (group 140) whenever the cell has a + /// style record, even a default 0.18 with no override flag, and CADCraft reads a 140 as an + /// override (#2501). The override is the cell style's TEXT_HEIGHT property flag or the + /// content's format override bit 128; without either the height is cleared (0 is no + /// override), so the table style's height applies. + fn table_cell_heights(doc: &mut acadrust::CadDocument) { + use acadrust::entities::table::CellStylePropertyFlags; + const CONTENT_TEXT_HEIGHT: i32 = 128; + for e in doc.entities_mut() { + let acadrust::entities::EntityType::Table(t) = e else { continue }; + for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) { + // The first content's own height (group 144) when its format override sets bit 128. + // CADCraft keeps one height for the cell's text, so a later content's override + // must not stand in for the first content's. + let content_height = cell + .contents + .first() + .filter(|c| c.format_override_flags & CONTENT_TEXT_HEIGHT != 0) + .map(|c| c.text_height) + .filter(|h| h.is_finite() && *h > 0.0); + if let Some(h) = content_height { + // CADCraft reads only the style's height (group 140), so carry it there. + cell.style.get_or_insert_with(acadrust::entities::table::CellStyle::new).text_height = h; + continue; + } + // A style overrides through its property flags or, in newer files, its override + // flags; anything else is the writer's default and is cleared. + if let Some(style) = cell.style.as_mut() + && !style.property_flags.contains(CellStylePropertyFlags::TEXT_HEIGHT) + && style.override_flags & CellStylePropertyFlags::TEXT_HEIGHT.bits() as i32 == 0 + { + style.text_height = 0.0; + } + } + } + } + + /// The fix-ups made to a document after the DWG read, returning how many orphaned DGN + /// components were dropped. The document comes from a third-party reader and is hostile. + fn post_process(doc: &mut acadrust::CadDocument) -> usize { + super::fail_in_test("post_process"); + current_style_names(doc); + table_merges(doc); + table_cell_heights(doc); + table_style_rows(doc, false); + keep_sort_handles(doc); + drop_orphaned_dgn_components(doc) + } + + /// Runs `f`, turning a panic into an error (the reader and writer are guarded the same way). + fn guarded(f: impl FnOnce() -> R + std::panic::UnwindSafe) -> Result { + std::panic::catch_unwind(f).map_err(|_| ()) + } + + /// The version a proxy record of a DWG of `version` names its format by (Open Design + /// Specification for .dwg, proxy objects): 19 for R13, 21 for R14, 23 for 2000, 25 for 2004, + /// 27 for 2007, 29 for 2010, 31 for 2013 and 33 for 2018; `None` for any other version. + pub(super) fn proxy_dwg_version(version: acadrust::DxfVersion) -> Option { + Some(match version.version_code() { + 1012 => 19, + 1014 => 21, + 1015 => 23, + 1018 => 25, + 1021 => 27, + 1024 => 29, + 1027 => 31, + 1032 => 33, + _ => return None, + }) + } + + /// Objects of another application's class that acadrust keeps only as their DWG record + /// (`ObjectType::Unknown`, which has no DXF form): its DXF writer left them out, and the + /// references to them went with them (a dimension's extension dictionary entry naming its + /// application data, say), with no note. Each is carried as a proxy object of its class instead + /// (DXF Reference, ACAD_PROXY_OBJECT), so the DXF keeps it and a DWG written from that DXF has it + /// again: its common object data (owner, reactors, extension dictionary) and the streams after + /// it (data bits, R2007+ strings, object references), as the Open Design Specification for .dwg + /// splits an object record. Objects of the drawing database's own classes are not turned into + /// another application's proxies. What is still without a DXF form is named in the notes, so a + /// save over the original is not mistaken for a complete one. + fn application_objects(doc: &mut acadrust::CadDocument) -> Vec { + use acadrust::objects::{ObjectType, ProxyObject}; + let classes: Vec = doc.classes.iter().cloned().collect(); + let source = doc.dwg_source_version.unwrap_or(doc.version); + if let Some(dwg_version) = proxy_dwg_version(source) { + let maintenance = i32::from(doc.maintenance_version); + for object in doc.objects.values_mut() { + let ObjectType::Unknown { handle, raw_dwg_data: Some(data), raw_dwg_handle_bits, raw_dwg_version: Some(version), type_name, .. } = + &*object + else { + continue; + }; + if !application_class(&classes, type_name) { + continue; + } + let raw = acadrust::entities::RawRecord { data: data.clone(), handle_bits: *raw_dwg_handle_bits, version: *version }; + let handle = *handle; + // A record that doesn't split stays as it was, and is named below. + let Ok(Ok(record)) = std::panic::catch_unwind(AssertUnwindSafe(|| object_record(&raw, handle.value()))) else { continue }; + let Some(class) = classes.iter().find(|c| c.class_number == record.kind && !c.is_an_entity) else { continue }; + *object = ObjectType::ProxyObject(ProxyObject { + handle, + owner: record.owner, + reactors: record.reactors, + xdictionary_handle: record.xdictionary, + proxy_id: 499, + class_id: i32::from(class.class_number), + dwg_version, + maintenance_version: maintenance, + version: (maintenance << 16) | dwg_version, + payload: record.payload, + text_payload: record.text_payload, + object_ids: record.object_ids, + ..Default::default() + }); + } + } + let mut left: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); + for object in doc.objects.values() { + if let ObjectType::Unknown { type_name, raw_dxf_codes: None, .. } = object { + let n = left.entry(type_name.as_str()).or_insert(0); + *n = n.saturating_add(1); + } + } + if left.is_empty() { + return Vec::new(); + } + let total = left.values().fold(0usize, |a, n| a.saturating_add(*n)); + let mut list: Vec = left.iter().take(NOTE_TYPES).map(|(t, n)| format!("{t:.60} × {n}")).collect(); + if left.len() > NOTE_TYPES { + list.push(format!("{} more types", left.len() - NOTE_TYPES)); + } + vec![format!( + "DWG: {total} objects of types this bridge can't preserve were left out ({}); saving over the original file would lose them", + list.join(", ") + )] + } + + /// Whether `name` is an object class of another application, which only that application + /// rebuilds: not one of the drawing database's own classes (`AcDb…`/`ACDB…`/`ACAD_…`), whose + /// leftovers the database regenerates itself. + fn application_class(classes: &[acadrust::classes::DxfClass], name: &str) -> bool { + classes.iter().any(|c| { + !c.is_an_entity + && c.dxf_name.eq_ignore_ascii_case(name) + && !c.cpp_class_name.starts_with("AcDb") + && !["ACDB", "ACAD_", "ACAD"].iter().any(|p| c.dxf_name.to_ascii_uppercase().starts_with(p)) + }) + } + + /// An application object acadrust kept only as its record: the parts a proxy object carries. + struct ObjectRecord { + kind: i16, + owner: acadrust::types::Handle, + reactors: Vec, + xdictionary: Option, + payload: acadrust::objects::ProxyPayload, + text_payload: acadrust::objects::ProxyPayload, + object_ids: Vec, + } + + /// Split an object record into its common object data and the uninterpreted streams after it + /// (data bits, R2007+ strings and object references), as an application object's proxy holds + /// them (Open Design Specification for .dwg, common object data and proxy objects). The record + /// is hostile: sizes are checked against it, and acadrust's checked stream reader does the rest. + fn object_record(raw: &acadrust::entities::RawRecord, handle: u64) -> Result { + use acadrust::io::dwg::{ + DwgVersion, dwg_reference_type::DwgReferenceType, dwg_stream_readers::object_reader::DwgObjectReader, + dwg_stream_writers::bit_writer::DwgBitWriter, + }; + use acadrust::objects::{ProxyObjectReference, ProxyPayload, ProxyReferenceKind}; + use acadrust::types::{DxfVersion, Handle}; + if raw.data.len() > 32 << 20 { + return Err("object record exceeds the transport limit".into()); + } + let handle_bits = usize::try_from(raw.handle_bits).map_err(|_| "object has a negative handle stream size")?; + let total_bits = raw.data.len().checked_mul(8).ok_or("object record is too large")?; + if handle_bits > total_bits { + return Err("object handle stream exceeds its record".into()); + } + let version = DwgVersion::from_dxf_version(raw.version).map_err(|e| e.to_string())?; + let mut frame = DwgBitWriter::new(version, raw.version); + frame.write_modular_short(raw.data.len()); + if raw.version >= DxfVersion::AC1024 { + frame.write_modular_char(handle_bits); + } + frame.write_bytes(&raw.data); + let reader = DwgObjectReader::new(frame.into_bytes(), raw.version, std::collections::HashMap::new()).map_err(|e| e.to_string())?; + let (kind, mut streams) = reader.read_record_at(0).map_err(|e| e.to_string())?; + if kind < 500 { + return Err("object has no application class".into()); + } + let common = reader.read_common_non_entity_data(&mut streams, kind); + streams.check_error().map_err(|e| e.to_string())?; + if common.common.handle != handle { + return Err("object record names another handle".into()); + } + let read_bits = |count: usize, bit: &mut dyn FnMut() -> bool| -> Result { + if count > total_bits { + return Err("object stream exceeds its record".into()); + } + let n = u32::try_from(count).map_err(|_| "object stream is too large")?; + let mut bytes = vec![0u8; count.div_ceil(8)]; + for index in 0..count { + if bit() + && let Some(b) = bytes.get_mut(index / 8) + { + *b |= 0x80 >> (index % 8); + } + } + Ok(ProxyPayload::from_bits(&bytes, n)) + }; + let main = usize::try_from(streams.main_remaining_bits()).map_err(|_| "object body has an invalid size")?; + let payload = read_bits(main, &mut || streams.read_bit())?; + let text_payload = if raw.version >= DxfVersion::AC1021 { + let bits = usize::try_from(streams.text_remaining_bits()).map_err(|_| "object has a negative string stream size")?; + read_bits(bits, &mut || streams.read_text_bit())? + } else { + ProxyPayload::default() + }; + // Every reference to the end of the handle stream, null ones too: an object keeps a null pointer in its + // field's place, and the references after it are the next fields' (as acadrust reads a proxy's own). R2010+ + // records give the stream's exact length; the bits of its last byte past it are padding. + let mut object_ids = Vec::new(); + let mut left = if raw.version >= DxfVersion::AC1024 { + streams.get_handle_bits().max(0).min(streams.handle_remaining_bits()) + } else { + streams.handle_remaining_bits() + }; + while left >= 8 { + if object_ids.len() >= 100_000 { + return Err("object has too many references".into()); + } + let before = streams.handle_remaining_bits(); + let (target, reference) = streams.read_handle_reference(handle); + let used = before.saturating_sub(streams.handle_remaining_bits()); + if used <= 0 || used > left { + break; + } + left -= used; + let kind = match reference { + DwgReferenceType::SoftOwnership => ProxyReferenceKind::SoftOwnership, + DwgReferenceType::HardOwnership => ProxyReferenceKind::HardOwnership, + DwgReferenceType::SoftPointer => ProxyReferenceKind::SoftPointer, + DwgReferenceType::HardPointer => ProxyReferenceKind::HardPointer, + DwgReferenceType::Undefined => ProxyReferenceKind::Undefined, + }; + object_ids.push(ProxyObjectReference { handle: Handle::from(target), kind }); + } + streams.check_error().map_err(|e| e.to_string())?; + Ok(ObjectRecord { + kind, + owner: Handle::from(common.owner_handle), + reactors: common.reactors.into_iter().map(Handle::from).collect(), + xdictionary: common.xdictionary_handle.map(Handle::from), + payload, + text_payload, + object_ids, + }) + } + + /// [`table_merges`] visiting at most `budget` cells in all; a range that would pass it is + /// left unmerged. Returns the cells visited. + fn table_merges_within(doc: &mut acadrust::CadDocument, budget: usize) -> usize { + let mut left = budget; + for e in doc.entities_mut() { + let acadrust::entities::EntityType::Table(t) = e else { continue }; + if t.merged_ranges.is_empty() || t.rows.iter().flat_map(|r| &r.cells).any(|c| c.merge_width > 1 || c.merge_height > 1) { + continue; + } + let (rows, cols) = (t.rows.len(), t.columns.len()); + // A real table has at most one merge per cell; more ranges than that come from a + // damaged file and would only make this rows × cols × ranges. + let max_ranges = rows.saturating_mul(cols).min(1 << 16); + for r in t.merged_ranges.iter().take(max_ranges).cloned().collect::>() { + // Clamp to the table: the ranges come from the file. + let (bottom, right) = (r.bottom_row.min(rows.saturating_sub(1)), r.right_col.min(cols.saturating_sub(1))); + if r.top_row > bottom || r.left_col > right || rows == 0 || cols == 0 || (r.top_row, r.left_col) == (bottom, right) { + continue; + } + let area = (bottom - r.top_row + 1).saturating_mul(right - r.left_col + 1); + if area > left { + continue; + } + left -= area; + let span = |n: usize| i32::try_from(n + 1).unwrap_or(i32::MAX); + for (ri, row) in t.rows.iter_mut().enumerate().take(bottom + 1).skip(r.top_row) { + for (ci, cell) in row.cells.iter_mut().enumerate().take(right + 1).skip(r.left_col) { + cell.merged = 1; + let first = (ri, ci) == (r.top_row, r.left_col); + cell.merge_width = if first { span(right - r.left_col) } else { 0 }; + cell.merge_height = if first { span(bottom - r.top_row) } else { 0 }; + } + } + } + } + budget - left + } + + /// Draw-order tables (SORTENTSTABLE) keep the sort handles the file gave them. acadrust's DXF + /// writer renumbers them past every entity handle, but an entity left out of a table sorts by + /// its own handle, so after renumbering it would draw below every listed entity (#2410). Giving + /// the table its codes verbatim makes the writer emit them unchanged. + fn keep_sort_handles(doc: &mut acadrust::CadDocument) { + use acadrust::objects::ObjectType; + let version = doc.version; + for o in doc.objects.values_mut() { + let ObjectType::SortEntitiesTable(t) = o else { continue }; + let hex = |h: acadrust::types::Handle| format!("{:X}", h.value()); + let mut codes = + vec![(5, hex(t.handle)), (330, hex(t.owner_handle)), (100, "AcDbSortentsTable".to_string()), (330, hex(t.block_owner_handle))]; + for e in t.entries() { + codes.push((331, hex(e.entity_handle))); + codes.push((5, hex(e.sort_handle))); + } + t.raw_dxf_codes = Some(codes); + t.raw_dxf_version = Some(version); + } + } + + /// Table styles' title and header suppression between the two places acadrust 0.6.3 keeps + /// it. 2010+ (AC1024+) DWG stores it only in the style's flags (title 1, header 2), while + /// acadrust's DXF reader and writer use the `title_suppressed`/`header_suppressed` fields + /// (groups 280, 281). `to_flags` copies the fields into the flags before a DWG is written; + /// otherwise the flags are copied into the fields after one is read. Older versions store + /// both and are left alone. + fn table_style_rows(doc: &mut acadrust::CadDocument, to_flags: bool) { + use acadrust::objects::{ObjectType, TableStyleFlags}; + if doc.version < acadrust::DxfVersion::AC1024 { + return; + } + for o in doc.objects.values_mut() { + let ObjectType::TableStyle(s) = o else { continue }; + for (bit, suppressed) in + [(TableStyleFlags::TITLE_SUPPRESSED, &mut s.title_suppressed), (TableStyleFlags::HEADER_SUPPRESSED, &mut s.header_suppressed)] + { + if to_flags { + s.flags.set(bit, *suppressed); + } else { + *suppressed = s.flags.contains(bit); + } + } + } + } + + /// The DWG dimension flags byte. Its bit 1 is DXF group 70's bit 32 (ODA DWG specification, + /// common dimension data), which acadrust keeps no copy of from DXF: it is set here as + /// CADCraft's DXF writer always sets it (#1094). Bit 0, the opposite of group 70's bit 128, + /// acadrust 0.6.6 reads and writes itself. + fn dimension_flags(doc: &mut acadrust::CadDocument) { + for e in doc.entities_mut() { + let acadrust::entities::EntityType::Dimension(d) = e else { continue }; + d.base_mut().dwg_flags_byte |= 0x02; + } + } + + /// Leave out DGN line style components (`LS*COMPONENT`) that no line style definition uses + /// (#1482). A drawing that once came from MicroStation can carry hundreds of thousands of + /// them, orphaned copies piled up by earlier DGN imports and copy-pastes (AutoCAD's PURGE + /// removes them as orphaned data): in a real 83 MB site plan they were 888,483 of 889,053 + /// components and made its DXF rendition 1.2 GB, over [`Limits::DEFAULT`], so the file + /// didn't open at all. No definition that was read refers to them (a definition the reader + /// skipped can't use them either) and CADCraft doesn't draw DGN line styles, so nothing + /// visible is lost. + /// Every component a definition reaches (directly, or through compound and point + /// components) is kept, as are the definitions; dictionary entries that named a dropped + /// component go with it. Returns how many were left out. + fn drop_orphaned_dgn_components(doc: &mut acadrust::CadDocument) -> usize { + use acadrust::objects::{DgnLineStyleData, ObjectType}; + use std::collections::{HashMap, HashSet}; + // Each component's references, and the definitions' root components to start from. + let mut refs: HashMap> = HashMap::new(); + let mut stack: Vec = Vec::new(); + for (h, o) in &doc.objects { + let ObjectType::DgnLineStyle(ls) = o else { continue }; + match &ls.data { + DgnLineStyleData::Definition { root_component, .. } => stack.push(*root_component), + DgnLineStyleData::Component { component, .. } => { + refs.insert(*h, component.references()); + } + DgnLineStyleData::Registered { .. } => {} + } + } + if refs.is_empty() { + return 0; + } + // Each component is visited once, so cycles and shared subtrees end. + let mut used: HashSet = HashSet::new(); + while let Some(h) = stack.pop() { + if let Some(r) = refs.get(&h) + && used.insert(h) + { + stack.extend(r.iter().copied()); + } + } + let orphans: HashSet = refs.into_keys().filter(|h| !used.contains(h)).collect(); + if orphans.is_empty() { + return 0; + } + doc.objects.retain(|h, _| !orphans.contains(h)); + doc.dgn_ls_components.retain(|h, _| !orphans.contains(h)); + for o in doc.objects.values_mut() { + let ObjectType::Dictionary(d) = o else { continue }; + if d.entries.iter().any(|(_, e)| orphans.contains(e)) { + d.entries.retain(|(_, e)| !orphans.contains(e)); + let keys: HashSet<&str> = d.entries.iter().map(|(k, _)| k.as_str()).collect(); + d.hard_owner_entries.retain(|k| keys.contains(k.as_str())); + } + } + orphans.len() + } + + /// Leave out what acadrust can't write as this DWG version: other programs' custom entities + /// and objects without raw DWG data of that version. acadrust 0.6.4 refuses the whole file + /// for one of them (0.6.3 left them out); CADCraft already tells the user which entity types + /// a DWG doesn't keep (`not_saved`), so the rest of the drawing is written. Returns how many + /// records of each DXF type were left out, so a save can say so. + fn drop_unwritable(doc: &mut acadrust::CadDocument) -> super::Unwritten { + let version = doc.version; + let mut dropped = super::Unwritten::new(); + let mut count = |name: &str| { + let n = dropped.entry(name.trim().to_ascii_uppercase()).or_insert(0); + *n = n.saturating_add(1); + }; + let unwritable: Vec = doc + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Unknown(u) + if u.raw_dwg_data.is_none() || u.dwg_source_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 => + { + count(&u.dxf_name); + Some(u.common.handle) + } + _ => None, + }) + .collect(); + for h in &unwritable { + doc.remove_entity(*h); + } + let objects: Vec = doc + .objects + .iter() + .filter_map(|(h, o)| match o { + acadrust::objects::ObjectType::Unknown { type_name, raw_dwg_data, raw_dwg_version, .. } + if raw_dwg_data.is_none() || raw_dwg_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 => + { + count(type_name); + Some(*h) + } + _ => None, + }) + .collect(); + for h in &objects { + doc.objects.remove(h); + } + dropped + } + + /// Header variables the DWG reader fills in but acadrust's DXF writer (0.6.3) leaves out of + /// the HEADER section: (name, group code, value). + fn unwritten_header_vars(h: &acadrust::document::HeaderVariables) -> [(&'static str, i32, String); 7] { + [ + // DWG holds radians; `$ANGBASE` is in degrees. + ("$ANGBASE", 50, h.angle_base.to_degrees().to_string()), + ("$ANGDIR", 70, h.angle_direction.to_string()), + ("$FILLETRAD", 40, h.fillet_radius.to_string()), + ("$CHAMFERA", 40, h.chamfer_distance_a.to_string()), + ("$CHAMFERB", 40, h.chamfer_distance_b.to_string()), + ("$ELEVATION", 40, h.elevation.to_string()), + ("$THICKNESS", 40, h.thickness.to_string()), + ] + } + + /// Add the [`unwritten_header_vars`] to the HEADER section of acadrust's DXF text, before its + /// ENDSEC; a variable the writer already wrote is left alone. Text of another layout than + /// acadrust's (` 0\r\nSECTION\r\n 2\r\nHEADER\r\n` … ` 0\r\nENDSEC\r\n`) is returned unchanged. + fn add_header_vars(mut dxf: Vec, h: &acadrust::document::HeaderVariables) -> Vec { + const START: &[u8] = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n"; + const END: &[u8] = b"\r\n 0\r\nENDSEC\r\n"; + if !dxf.starts_with(START) { + return dxf; + } + let Some(end) = dxf.windows(END.len()).position(|w| w == END).map(|p| p + 2) else { return dxf }; + let section = dxf.get(..end).unwrap_or_default(); + let mut add = String::new(); + for (name, code, value) in unwritten_header_vars(h) { + let written = section.windows(name.len() + 2).any(|w| w.starts_with(name.as_bytes()) && w.ends_with(b"\r\n")); + if !written && value.parse::().is_ok_and(f64::is_finite) { + add.push_str(&format!(" 9\r\n{name}\r\n{code:>3}\r\n{value}\r\n")); + } + } + dxf.splice(end..end, add.into_bytes()); + dxf + } + + /// Collects the DXF text and fails the write once it would grow past `limit`. + struct CappedWriter { + buf: Vec, + limit: usize, + exceeded: bool, + } + + impl Write for CappedWriter { + fn write(&mut self, b: &[u8]) -> std::io::Result { + // Sticky: once over, every later write fails too. + if self.exceeded || self.buf.len().saturating_add(b.len()) > self.limit { + self.exceeded = true; + return Err(std::io::Error::other("DXF size limit reached")); + } + self.buf.extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + /// Oldest DWG version written; older DXF input is written as this version. + const MIN_DWG_VERSION: acadrust::DxfVersion = acadrust::DxfVersion::AC1018; + + /// Convert DXF bytes into a DWG file of the DXF's version, and at least AutoCAD 2004 + /// (AC1018). + pub fn dxf_to_dwg(dxf: &[u8]) -> Result, String> { + convert(dxf, None, None).map(|(dwg, _)| dwg) + } + + /// Convert DXF bytes into a DWG file of `version`, a code from [`super::VERSIONS`] ("AC1032"), + /// whatever version the DXF declares. + pub fn dxf_to_dwg_as(dxf: &[u8], version: &str) -> Result, String> { + dxf_to_dwg_noted(dxf, version).map(|(dwg, _)| dwg) + } + + /// [`dxf_to_dwg_as`], also returning what the DWG writer left out: how many records of each + /// DXF type it can't write (other programs' custom entities and objects that the DWG reader + /// didn't read from a DWG of this version), empty when the DWG keeps everything. + pub fn dxf_to_dwg_noted(dxf: &[u8], version: &str) -> Result<(Vec, super::Unwritten), String> { + convert(dxf, Some(writable(version)?), None) + } + + /// Like [`dxf_to_dwg_as`], for a DXF that declares an older version than the groups it carries + /// over from another file. CADCraft's R2000 DWG bridge holds the objects it keeps without + /// modelling them (render settings, fields, associative and dynamic block data) as they were + /// read from a file of version `kept` ("AC1032"), and acadrust reads several of those + /// differently by version: read as R2000, an AC1032 file's mental ray render settings came out + /// a class version too high, for which the ODA rejects the whole DWG, and a field lost its + /// cached value. So the DXF is read as `kept` declares. A `kept` version that is unknown, or + /// not newer than the DXF's own, changes nothing. + pub fn dxf_to_dwg_kept_as(dxf: &[u8], version: &str, kept: &str) -> Result, String> { + dxf_to_dwg_kept_noted(dxf, version, kept).map(|(dwg, _)| dwg) + } + + /// [`dxf_to_dwg_kept_as`], also returning what the DWG writer left out, as + /// [`dxf_to_dwg_noted`] does. + pub fn dxf_to_dwg_kept_noted(dxf: &[u8], version: &str, kept: &str) -> Result<(Vec, super::Unwritten), String> { + let kept = acadrust::DxfVersion::from_version_string(kept.trim().to_ascii_uppercase().as_str()); + let kept = (kept != acadrust::DxfVersion::Unknown).then_some(kept); + convert(dxf, Some(writable(version)?), kept) + } + + /// The DWG version for a code from [`super::VERSIONS`]. + fn writable(version: &str) -> Result { + Ok(match version.trim().to_ascii_uppercase().as_str() { + "AC1015" => acadrust::DxfVersion::AC1015, + "AC1018" => acadrust::DxfVersion::AC1018, + "AC1021" => acadrust::DxfVersion::AC1021, + "AC1024" => acadrust::DxfVersion::AC1024, + "AC1027" => acadrust::DxfVersion::AC1027, + "AC1032" => acadrust::DxfVersion::AC1032, + _ => return Err(super::unsupported(version)), + }) + } + + /// The ASCII DXF with its `$ACADVER` set to `kept` when that is newer than the version it + /// declares, or `None` to read it as it is (binary, no `$ACADVER`, or non-ASCII text without a + /// `$DWGCODEPAGE` to decode it by). From AutoCAD 2007 (AC1021) a DXF is UTF-8, so other bytes + /// are first decoded with the code page the DXF declares; `\U+XXXX` escapes read the same in + /// every version, and CADCraft's R2000 DXF is ASCII with such escapes. + pub(super) fn declare_version(dxf: &[u8], kept: acadrust::DxfVersion) -> Option> { + if dxf.starts_with(b"AutoCAD Binary DXF") { + return None; + } + let (_, declared) = header_value(dxf, b"$ACADVER")?; + let declared = acadrust::DxfVersion::from_version_string(std::str::from_utf8(declared).ok()?); + if declared >= kept { + return None; + } + let text: std::borrow::Cow<'_, [u8]> = if dxf.is_ascii() || kept < acadrust::DxfVersion::AC1021 { + std::borrow::Cow::Borrowed(dxf) + } else { + // As acadrust decodes an older DXF: by its code page, Windows-1252 for one it doesn't + // know; a code page that names UTF-8 needs no decoding. + let (_, code_page) = header_value(dxf, b"$DWGCODEPAGE")?; + match acadrust::io::dxf::code_page::encoding_from_code_page(std::str::from_utf8(code_page).ok()?) { + Some(encoding) => { + let (text, errors) = encoding.decode_without_bom_handling(dxf); + if errors { + return None; + } + std::borrow::Cow::Owned(text.into_owned().into_bytes()) + } + None => std::borrow::Cow::Borrowed(std::str::from_utf8(dxf).ok()?.as_bytes()), + } + }; + let (at, value) = header_value(&text, b"$ACADVER")?; + let code = kept.to_string(); + let mut out = Vec::with_capacity(text.len().saturating_add(code.len())); + out.extend_from_slice(text.get(..at)?); + out.extend_from_slice(code.as_bytes()); + out.extend_from_slice(text.get(at.checked_add(value.len())?..)?); + Some(out) + } + + /// The byte offset and the trimmed value of header variable `name` in an ASCII DXF: the value + /// of the group that follows the `9` group naming it. The file is read as (group code, + /// value) line pairs, in one pass with no buffering, up to the first `0`/`ENDSEC`, the end + /// of the HEADER section: a large input without one costs time, not memory (a line index of + /// a 32 MiB file used 0.8 GB). Lines may end in `\r\n`. + pub(super) fn header_value<'a>(dxf: &'a [u8], name: &[u8]) -> Option<(usize, &'a [u8])> { + let mut offset = 0usize; + let mut lines = dxf.split(|b| *b == b'\n').map(|line| { + let at = offset.saturating_add(line.len() - line.trim_ascii_start().len()); + offset = offset.saturating_add(line.len()).saturating_add(1); + (at, line.trim_ascii()) + }); + while let (Some((_, code)), Some((_, value))) = (lines.next(), lines.next()) { + if code == b"0" && value == b"ENDSEC" { + return None; + } + if code == b"9" && value == name { + let (_, code) = lines.next()?; + let (at, value) = lines.next()?; + return (code != b"0" && code != b"9").then_some((at, value)); + } + } + None + } + + /// The current dimension and text styles' names from their handles: a DWG stores the + /// handles, and the reader leaves the names at "Standard", so a drawing reopened from DWG + /// lost its current dimension style (#1051). + fn current_style_names(doc: &mut acadrust::CadDocument) { + let h = doc.header.current_dimstyle_handle; + if let Some(n) = doc.dim_styles.iter().find(|ds| ds.handle == h && !h.is_null()).map(|ds| ds.name.clone()) { + doc.header.current_dimstyle_name = n; + } + let h = doc.header.current_text_style_handle; + if let Some(n) = doc.text_styles.iter().find(|ts| ts.handle == h && !h.is_null()).map(|ts| ts.name.clone()) { + doc.header.current_text_style_name = n; + } + } + + /// The current dimension style (`$DIMSTYLE`) by its name: the DXF gives the name, and the + /// handle read with it needn't be the style's in the document, in which case the DWG writer + /// fell back to Standard and AutoCAD opened the drawing with Standard current (#1051). + fn current_dimstyle(doc: &mut acadrust::CadDocument) { + let name = doc.header.current_dimstyle_name.clone(); + if let Some(h) = doc.dim_styles.iter().find(|ds| ds.name.eq_ignore_ascii_case(&name)).map(|ds| ds.handle) { + doc.header.current_dimstyle_handle = h; + } + } + + /// The current text style (`$TEXTSTYLE`) by its name, the same way as [`current_dimstyle`]: + /// the handle read with the DXF needn't be the style's in the document, in which case the DWG + /// writer fell back to Standard and AutoCAD opened the drawing with Standard current (#1650). + fn current_text_style(doc: &mut acadrust::CadDocument) { + let name = doc.header.current_text_style_name.clone(); + if let Some(h) = doc.text_styles.iter().find(|ts| ts.name.eq_ignore_ascii_case(&name)).map(|ts| ts.handle) { + doc.header.current_text_style_handle = h; + } + } + + /// The DXF names of an ASCII DXF's CLASS records, in CLASSES order: a proxy's class number + /// (group 91) is 500 plus its class's place here (DXF Reference, ACAD_PROXY_OBJECT). Empty for + /// one without a CLASSES section. `None` for a binary DXF, whose classes this doesn't read: + /// CADCraft's own bridge DXF is always ASCII, and only a binary DXF given to the public + /// conversion functions comes here. + pub(super) fn dxf_class_names(dxf: &[u8]) -> Option> { + let pairs = super::proxy_transport::text_pairs(dxf)?; + let mut names = Vec::new(); + let (mut section, mut in_classes, mut in_class) = (false, false, false); + for pair in pairs { + let (code, value) = pair?; + match (code, value.as_str()) { + (0, "ENDSEC") if in_classes => break, + (0, "SECTION") => section = true, + (2, name) if section => { + in_classes = name == "CLASSES"; + section = false; + } + (0, kind) if in_classes => { + in_class = kind == "CLASS"; + // Even an unnamed record keeps its place in the source class table. + if in_class { + names.push(String::new()); + } + } + (1, value) if in_class => { + if let Some(last) = names.last_mut() { + *last = value.to_string(); + } + in_class = false; + } + _ => section = false, + } + } + Some(names) + } + + /// Proxy objects' and entities' class numbers as the DWG numbers its classes. A DXF proxy + /// names its class by its place in the DXF's CLASSES (`classes`, from 500), but acadrust's + /// reader puts its own default classes first and numbers the DXF's after them, so the DXF + /// number named another class in the DWG: a 2018 drawing's piping proxies became + /// LARGE_RADIAL_DIMENSION and SECTIONOBJECT, and the ODA File Converter refused the file. A + /// proxy whose number names no class of the DXF is left out: kept as it is, its number would + /// name some other class of the DWG, for the same reason. + /// + /// Before 2013 (AC1027) acadrust writes only the classes it knows a pre-2013 DWG needs, and a + /// proxy's class is not one of them: the proxy would name a missing class (the ODA refuses + /// the file: "No ClassId") or, by its old number, some other class. Such a DWG leaves the + /// proxies out instead, as it does other programs' data it can't write (`not_saved` reports + /// the entities). So does a DXF whose classes are unknown (`classes` is `None`, a binary + /// DXF): its proxies' numbers can't be mapped, and kept as they are they would name the + /// wrong classes and the ODA would refuse the file. Returns the proxies left out, by DXF type, for + /// what the DWG writer left out ([`super::Unwritten`]). + fn proxy_classes(doc: &mut acadrust::CadDocument, classes: Option<&[String]>) -> super::Unwritten { + let classes = match classes { + Some(c) if doc.version >= acadrust::DxfVersion::AC1027 => c, + _ => { + let entities: Vec = doc + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Extended(x) if matches!(x.data, acadrust::entities::ExtendedEntityData::Proxy(_)) => { + Some(x.common.handle) + } + _ => None, + }) + .collect(); + let objects: Vec = + doc.objects.iter().filter_map(|(h, o)| matches!(o, acadrust::objects::ObjectType::ProxyObject(_)).then_some(*h)).collect(); + for h in &entities { + doc.remove_entity(*h); + } + for h in &objects { + doc.objects.remove(h); + } + return left_out(objects.len(), entities.len()); + } + }; + // Name matching cannot choose between different source classes with the same name. + // Count those proxies as unwritten rather than silently changing their class identity. + let mut unique = std::collections::HashMap::new(); + for name in classes { + unique.entry(name.to_uppercase()).and_modify(|value| *value = false).or_insert(true); + } + let number = |id: i32| -> Option { + let name = classes.get(usize::try_from(id.checked_sub(500)?).ok()?)?; + if unique.get(&name.to_uppercase()) != Some(&true) { + return None; + } + doc.classes.get_by_name(name).map(|c| i32::from(c.class_number)) + }; + let objects: Vec<(acadrust::Handle, Option)> = doc + .objects + .iter() + .filter_map(|(h, o)| match o { + acadrust::objects::ObjectType::ProxyObject(p) => Some((*h, number(p.class_id))), + _ => None, + }) + .collect(); + let entities: Vec<(acadrust::Handle, Option)> = doc + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Extended(x) => match &x.data { + acadrust::entities::ExtendedEntityData::Proxy(p) => Some((x.common.handle, number(p.class_id))), + _ => None, + }, + _ => None, + }) + .collect(); + let unmapped = |list: &[(acadrust::Handle, Option)]| list.iter().filter(|(_, n)| n.is_none()).map(|(h, _)| *h).collect::>(); + let (gone_objects, gone_entities) = (unmapped(&objects), unmapped(&entities)); + for h in &gone_objects { + doc.objects.remove(h); + } + for h in &gone_entities { + doc.remove_entity(*h); + } + let objects = objects.into_iter().filter_map(|(h, n)| Some((h, n?))); + let entities = entities.into_iter().filter_map(|(h, n)| Some((h, n?))); + for (h, n) in objects { + if let Some(acadrust::objects::ObjectType::ProxyObject(p)) = doc.objects.get_mut(&h) { + p.class_id = n; + } + } + let entities: std::collections::HashMap = entities.into_iter().collect(); + for e in doc.entities_mut() { + if let acadrust::entities::EntityType::Extended(x) = e { + let Some(n) = entities.get(&x.common.handle).copied() else { continue }; + if let acadrust::entities::ExtendedEntityData::Proxy(p) = &mut x.data { + p.class_id = n; + } + } + } + left_out(gone_objects.len(), gone_entities.len()) + } + + /// Proxy objects and entities left out of the DWG, by their DXF types. + fn left_out(objects: usize, entities: usize) -> super::Unwritten { + [("ACAD_PROXY_OBJECT", objects), ("ACAD_PROXY_ENTITY", entities)] + .into_iter() + .filter(|(_, n)| *n > 0) + .map(|(t, n)| (t.to_string(), n)) + .collect() + } + + /// The current layer (`$CLAYER`) by its name, the same way as [`current_dimstyle`]: a DWG + /// stores the handle of the layer, and the one read with the DXF needn't be the layer's in + /// the document, so the drawing reopened with layer "0" current (#2252). + fn current_layer(doc: &mut acadrust::CadDocument) { + let name = doc.header.current_layer_name.clone(); + // The table's own lookup compares Unicode case-insensitively ("Survey_Ä" = "Survey_ä"). + if let Some(layer) = doc.layers.get(&name) { + doc.header.current_layer_handle = layer.handle; + } + } + + /// `kept`: the version the DXF's carried-over groups were read from ([`dxf_to_dwg_kept_as`]). + fn convert(dxf: &[u8], version: Option, kept: Option) -> Result<(Vec, super::Unwritten), String> { + // Reject a pathologically large DXF before handing it to the third-party decoder, which + // allocates tables and section buffers from the input's declared sizes and cannot be + // interrupted once it starts (CWE-789). This bounds the large-input variant; the decoder + // runs inside `catch_unwind` so a decode failure is reported rather than crashing. + if dxf.len() > Limits::DEFAULT.max_dxf_bytes { + return Err(format!( + "DXF: the input is {}, larger than the {} accepted for DWG conversion", + mb(dxf.len() as u64), + mb(Limits::DEFAULT.max_dxf_bytes as u64) + )); + } + // Decoding a code page to UTF-8 can grow the text, so the limit applies again. + let data = match kept.and_then(|k| declare_version(dxf, k)) { + Some(d) if d.len() > Limits::DEFAULT.max_dxf_bytes => { + return Err(format!( + "DXF: the input is {} as UTF-8, larger than the {} accepted for DWG conversion", + mb(d.len() as u64), + mb(Limits::DEFAULT.max_dxf_bytes as u64) + )); + } + Some(d) => d, + None => dxf.to_vec(), + }; + let (classes, source) = guarded(AssertUnwindSafe(|| (dxf_class_names(&data), super::proxy_transport::source_classes(&data)))) + .map_err(|_| "the DXF proxy class conversion failed".to_string())?; + let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) + .map_err(|_| "the DXF→DWG conversion failed".to_string())? + .map_err(|e| format!("DXF: {e}"))?; + match version { + Some(v) => doc.version = v, + // Without a version asked for, write at least AutoCAD 2004 (AC1018) DWG: R2000 DWG + // has no true colours, transparency, table styles or gradients. The DXF stays R2000; + // only the DWG is newer. + None if doc.version < MIN_DWG_VERSION => doc.version = MIN_DWG_VERSION, + None => {} + } + // The fix-ups run on the third-party reader's document, so a panic in one is an error, not a crash. + let unwritten = guarded(AssertUnwindSafe(|| { + super::fail_in_test("convert"); + // From 2013 the DWG takes the source classes as they are, duplicates and metadata + // included; otherwise (before 2013, a binary DXF, classes that can't be written back) + // proxies are matched to classes by name or left out. + let restored = match source { + Some(source) if doc.version >= acadrust::DxfVersion::AC1027 => super::proxy_transport::restore_classes(&mut doc, source), + _ => None, + }; + let proxies = match restored { + Some((objects, entities)) => left_out(objects, entities), + None => proxy_classes(&mut doc, classes.as_deref()), + }; + other_layout_owners(&mut doc); + table_style_rows(&mut doc, true); + dimension_flags(&mut doc); + let mut unwritten = drop_unwritable(&mut doc); + for (kind, n) in proxies { + let total = unwritten.entry(kind).or_insert(0); + *total = total.saturating_add(n); + } + current_dimstyle(&mut doc); + add_variable_dictionary(&mut doc); + current_text_style(&mut doc); + current_layer(&mut doc); + unwritten + })) + .map_err(|_| "the DXF to DWG conversion failed on this file".to_string())?; + let dwg = std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc))) + .map_err(|_| "the DWG writer failed on this drawing".to_string())? + .map_err(|e| format!("DWG write: {e}"))?; + Ok((dwg, unwritten)) + } + + /// AutoCAD's entry name for the drawing variables dictionary (the DXF Reference calls it the + /// ACDBVARIABLEDICTIONARY; dictionary keys are case-insensitive). + const VARIABLE_DICTIONARY: &str = "AcDbVariableDictionary"; + + /// A style or scale name, or `default` when the drawing has none. + fn name_or_default(name: &str, default: &str) -> String { + let name = name.trim(); + if name.is_empty() { default.to_string() } else { name.to_string() } + } + + /// A drawing variable's value as text, or `default` when the header holds a value the + /// variable doesn't accept (a hostile file can put any integer in it). + fn variable_value(value: i16, valid: &[i16], default: i16) -> String { + if valid.contains(&value) { value.to_string() } else { default.to_string() } + } + + /// Add the drawing variables dictionary AutoCAD always writes into the named object + /// dictionary, with the variables it keeps there, when the drawing has none (#1813). + /// Vectric Aspire 10.5 reads a 2004 (AC1018) DWG without it as empty ("No data was imported + /// from the DXF / DWG file"), though it reads the same drawing as DXF — which has no such + /// dictionary either, as CADCraft's and ezdxf's writers don't make one. AutoCAD's AC1032 DWGs + /// read there without it, so newer output is left as it was, and a dictionary the drawing + /// does have keeps its own entries and values. + fn add_variable_dictionary(doc: &mut acadrust::CadDocument) { + use acadrust::objects::{Dictionary, DictionaryVariable, ObjectType}; + if doc.version >= acadrust::DxfVersion::AC1032 { + return; + } + let root_handle = doc.header.named_objects_dict_handle; + match doc.objects.get(&root_handle) { + Some(ObjectType::Dictionary(root)) => { + if root.get(VARIABLE_DICTIONARY).is_some() { + return; + } + } + _ => return, + } + // The variables AutoCAD writes for a drawing with default styles and a 1:1 annotation + // scale. DIMASSOC and HIDETEXT keep the drawing's own header values; LAYEREVAL and + // LAYERNOTIFY have no DXF header variable. + let variables = [ + ("CMLEADERSTYLE", name_or_default(&doc.header.current_mleader_style_name, "Standard")), + ("CTABLESTYLE", name_or_default(&doc.header.current_table_style_name, "Standard")), + ("CANNOSCALE", name_or_default(&doc.header.current_annotation_scale, "1:1")), + ("DIMASSOC", variable_value(doc.header.dimension_associativity, &[0, 1, 2], 2)), + ("HIDETEXT", variable_value(doc.header.hide_text, &[0, 1], 1)), + ("LAYEREVAL", "0".to_string()), + ("LAYERNOTIFY", "0".to_string()), + ]; + let dictionary_handle = doc.allocate_handle(); + let mut dictionary = Dictionary::new(); + dictionary.handle = dictionary_handle; + dictionary.owner = root_handle; + for (name, value) in variables { + let handle = doc.allocate_handle(); + let mut variable = DictionaryVariable::new(name, &value); + variable.handle = handle; + variable.owner_handle = dictionary_handle; + dictionary.add_entry(name, handle); + doc.objects.insert(handle, ObjectType::DictionaryVariable(variable)); + } + doc.objects.insert(dictionary_handle, ObjectType::Dictionary(dictionary)); + if let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&root_handle) { + root.add_entry(VARIABLE_DICTIONARY, dictionary_handle); + } + } + + /// Entities of a layout other than the one in `*Paper_Space` are written owned by their block + /// (entity mode 0, with its handle). acadrust writes every paper-space entity with mode 1, + /// "paper space", which AutoCAD reads as the `*Paper_Space` block's: everything drawn on a + /// second layout landed on the first one, and the second stayed empty (#1057). + fn other_layout_owners(doc: &mut acadrust::CadDocument) { + let others: std::collections::HashSet = doc + .block_records + .iter() + .filter(|br| { + let n = br.name.to_ascii_uppercase(); + n.len() > 12 && n.starts_with("*PAPER_SPACE") && n[12..].bytes().all(|b| b.is_ascii_digit()) + }) + .map(|br| br.handle) + .collect(); + if others.is_empty() { + return; + } + for e in doc.entities_mut() { + let c = e.common_mut(); + if others.contains(&c.owner_handle) { + c.entity_mode = Some(0); + } + } + } + + #[cfg(test)] + mod post_tests { + use super::*; + use acadrust::entities::{CellRange, EntityType, Table}; + + fn doc_with_table(rows: usize, cols: usize, ranges: usize) -> acadrust::CadDocument { + let mut t = Table::new(acadrust::types::Vector3::new(0.0, 0.0, 0.0), rows, cols); + t.merged_ranges = (0..ranges).map(|_| CellRange::new(0, 0, rows - 1, cols - 1)).collect(); + let mut doc = acadrust::CadDocument::new(); + assert!(doc.add_entity(EntityType::Table(Box::new(t))).is_ok()); + doc + } + + /// Overlapping whole-table ranges can't make the merge pass visit more than its budget (#1934). + #[test] + fn merge_work_is_bounded_by_the_cell_budget() { + let mut doc = doc_with_table(10, 10, 50); + assert_eq!(table_merges_within(&mut doc, 250), 200, "two whole-table ranges fit, the rest are skipped"); + let mut doc = doc_with_table(10, 10, 1); + assert_eq!(table_merges_within(&mut doc, usize::MAX), 100); + } + + /// A height marked only in the style's override flags (as newer files store it) is kept, + /// and the same height with no flag at all is cleared (review on #2588). Tested on the + /// read document because acadrust's DWG writer doesn't write the override flags. + #[test] + fn a_style_override_flag_keeps_the_cell_height() { + use acadrust::entities::table::{CellStyle, CellStylePropertyFlags}; + let height = |override_flags: i32| { + let mut doc = doc_with_table(1, 1, 0); + for e in doc.entities_mut() { + if let EntityType::Table(t) = e { + for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) { + let mut s = CellStyle::new(); + s.text_height = 0.5; + s.override_flags = override_flags; + cell.style = Some(s); + } + } + } + table_cell_heights(&mut doc); + doc.entities().find_map(|e| match e { + EntityType::Table(t) => t.rows.first()?.cells.first()?.style.as_ref().map(|s| s.text_height), + _ => None, + }) + }; + assert_eq!(height(CellStylePropertyFlags::TEXT_HEIGHT.bits() as i32), Some(0.5)); + assert_eq!(height(0), Some(0.0)); + } + + /// A panic in the post-read fix-ups is an error, not a crash (#1934). + #[test] + fn a_panic_in_post_processing_is_an_error() { + #[allow(clippy::panic)] + let r = guarded(AssertUnwindSafe(|| -> usize { panic!("boom") })); + assert!(r.is_err()); + assert_eq!(guarded(|| 3), Ok(3)); + } + } + + #[cfg(test)] + mod application_object_tests { + use super::*; + use acadrust::CadDocument; + use acadrust::classes::DxfClass; + use acadrust::objects::{ObjectType, ProxyObjectReference, ProxyPayload, ProxyReferenceKind, RegisteredClassObject}; + use acadrust::types::{DxfVersion, Handle}; + + /// An object of another application's class that acadrust keeps only as its record (a + /// vertical product's dimension data, say) is carried as that class's proxy object, with its + /// data bits, references, owner and extension dictionary, through DXF and back to DWG, twice. + #[test] + fn undecoded_application_object_is_kept_as_its_proxy() { + for version in [DxfVersion::AC1027, DxfVersion::AC1032] { + let mut source = CadDocument::new(); + source.version = version; + source.classes.add_or_update(DxfClass::new("TESTCONTAINER", "xyzDbTestContainer")); + let handle = Handle::from(0x2Bu64); + let target = Handle::from(0x2Cu64); + let payload = ProxyPayload::from_bits(&[0x5A, 0x3C, 0xC0], 18); + // A null pointer between two references: it keeps its place, the one after it is not lost. + let references = vec![ + ProxyObjectReference { handle: target, kind: ProxyReferenceKind::HardPointer }, + ProxyObjectReference { handle: Handle::from(0u64), kind: ProxyReferenceKind::SoftPointer }, + ProxyObjectReference { handle: Handle::from(0x0Cu64), kind: ProxyReferenceKind::HardPointer }, + ]; + source.objects.insert( + handle, + ObjectType::RegisteredClass(RegisteredClassObject { + handle, + owner: Handle::from(0x0Cu64), + dxf_name: "TESTCONTAINER".into(), + cpp_class_name: "xyzDbTestContainer".into(), + payload: payload.clone(), + object_ids: references.clone(), + ..Default::default() + }), + ); + let mut dwg = acadrust::DwgWriter::write_to_vec(&source).unwrap(); + // acadrust has no model of it: read back, it is only its record. + let decoded = acadrust::DwgReader::from_stream(Cursor::new(dwg.clone())).read().unwrap(); + assert!(matches!(decoded.objects.get(&handle), Some(ObjectType::Unknown { .. })), "{:?}", decoded.objects.get(&handle)); + for generation in 0..2 { + let (dxf, notes) = dwg_to_dxf_noted(&dwg, Limits::DEFAULT).unwrap(); + assert!(notes.is_empty(), "{version:?} {generation}: {notes:?}"); + // The DXF has the object, by its handle, as a proxy record. + let text = String::from_utf8_lossy(&dxf); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let record = lines.windows(4).any(|w| w == ["0", "ACAD_PROXY_OBJECT", "5", "2B"]); + assert!(record, "{version:?} {generation}: no proxy record for the object"); + dwg = dxf_to_dwg_as(&dxf, "AC1032").unwrap(); + let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.clone())).read().unwrap(); + let Some(ObjectType::ProxyObject(proxy)) = doc.objects.get(&handle) else { panic!("{version:?} {generation}: proxy object") }; + assert_eq!(proxy.payload.bit_count, payload.bit_count); + assert_eq!(proxy.payload.data(), payload.data()); + assert_eq!(proxy.object_ids, references); + let class = doc.classes.iter().find(|c| i32::from(c.class_number) == proxy.class_id).unwrap(); + assert_eq!(class.dxf_name, "TESTCONTAINER"); + assert!(!class.is_an_entity); + } + } + } + + /// The database's own classes are not turned into another application's proxies; what is + /// left without a DXF form is said, not dropped silently. + #[test] + fn database_objects_without_a_form_are_reported() { + let mut doc = CadDocument::new(); + doc.classes.add_or_update(DxfClass::new("BLOCKPROPERTIESTABLE", "AcDbBlockPropertiesTable")); + let handle = Handle::from(0x40u64); + doc.objects.insert( + handle, + ObjectType::Unknown { + type_name: "BLOCKPROPERTIESTABLE".into(), + handle, + owner: Handle::from(0x0Cu64), + raw_dxf_codes: None, + raw_dwg_data: Some(vec![0; 8]), + raw_dwg_handle_bits: 0, + raw_dwg_version: Some(DxfVersion::AC1032), + }, + ); + let notes = application_objects(&mut doc); + assert!(matches!(doc.objects.get(&handle), Some(ObjectType::Unknown { .. }))); + assert_eq!( + notes, + [ + "DWG: 1 objects of types this bridge can't preserve were left out (BLOCKPROPERTIESTABLE × 1); saving over the original file would lose them" + ] + ); + } + + /// A record that doesn't split stays as it was and is named, never guessed at. + #[test] + fn invalid_object_records_are_rejected() { + for handle_bits in [-1, 1000] { + let raw = acadrust::entities::RawRecord { data: vec![0; 8], handle_bits, version: DxfVersion::AC1032 }; + assert!(object_record(&raw, 42).is_err()); + } + let mut doc = CadDocument::new(); + doc.classes.add_or_update(DxfClass::new("TESTCONTAINER", "xyzDbTestContainer")); + let handle = Handle::from(0x41u64); + doc.objects.insert( + handle, + ObjectType::Unknown { + type_name: "TESTCONTAINER".into(), + handle, + owner: Handle::from(0x0Cu64), + raw_dxf_codes: None, + raw_dwg_data: Some(vec![0xFF; 4]), + raw_dwg_handle_bits: 1000, + raw_dwg_version: Some(DxfVersion::AC1032), + }, + ); + let notes = application_objects(&mut doc); + assert!(matches!(doc.objects.get(&handle), Some(ObjectType::Unknown { .. }))); + assert!(notes.iter().any(|n| n.contains("(TESTCONTAINER × 1)")), "{notes:?}"); + } + } +} + +#[cfg(not(no_dwg_bridge))] +pub use native::{ + dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as, dxf_to_dwg_kept_as, dxf_to_dwg_kept_noted, dxf_to_dwg_noted, +}; + +/// What saving as DWG left out: how many records of each DXF type (upper case) the DWG writer +/// can't write. +pub type Unwritten = std::collections::BTreeMap; + +// Test-only: the stage ("post_process" or "convert") whose guard the current test checks. The +// stage then panics on entry, so a test through the public API shows whether it is guarded. +#[cfg(all(test, not(no_dwg_bridge)))] +thread_local! { + static PANIC_IN: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Panics when a test asked for `stage` to fail (see [`PANIC_IN`]); does nothing otherwise. +#[cfg(not(no_dwg_bridge))] +#[allow(clippy::panic)] +fn fail_in_test(_stage: &str) { + #[cfg(test)] + if PANIC_IN.with(|p| p.get()) == Some(_stage) { + panic!("test-forced panic in {_stage}"); + } +} + +/// The error for a DWG version this writer can't create. +#[cfg_attr(no_dwg_bridge, allow(dead_code))] +fn unsupported(version: &str) -> String { + let list: Vec<&str> = VERSIONS.iter().map(|(_, year)| *year).collect(); + format!("DWG version `{version}` can't be written (this bridge writes {})", list.join(", ")) +} + +/// Which build has no DWG bridge, for the stubs' errors. +#[cfg(no_dwg_bridge)] +const NO_BRIDGE_BUILD: &str = if cfg!(target_arch = "wasm32") { "web" } else { "FreeBSD aarch64" }; + +/// There's no worker without a bridge. +#[cfg(no_dwg_bridge)] +pub const WORKER_ARG: &str = "--dwg-worker"; +#[cfg(no_dwg_bridge)] +pub fn serve_if_asked() -> Option { + None +} +#[cfg(no_dwg_bridge)] +pub fn use_own_worker() {} +#[cfg(no_dwg_bridge)] +pub fn allow_in_process() {} +#[cfg(no_dwg_bridge)] +pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { + dwg_to_dxf_noted(bytes, limits) +} +#[cfg(no_dwg_bridge)] +pub fn encode_as(dxf: &[u8], version: &str) -> Result, String> { + dxf_to_dwg_as(dxf, version) +} +#[cfg(no_dwg_bridge)] +pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec, Unwritten), String> { + dxf_to_dwg_noted(dxf, version) +} +#[cfg(no_dwg_bridge)] +pub fn encode_kept_noted(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec, Unwritten), String> { + match kept { + Some(kept) => dxf_to_dwg_kept_noted(dxf, version, kept), + None => dxf_to_dwg_noted(dxf, version), + } +} + +#[cfg(no_dwg_bridge)] +pub fn dwg_to_dxf(_bytes: &[u8]) -> Result, String> { + Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_dwg_bridge)] +pub fn dwg_to_dxf_noted(_bytes: &[u8], _limits: Limits) -> Result<(Vec, Vec), String> { + Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_dwg_bridge)] +pub fn dwg_to_dxf_with(_bytes: &[u8], _limits: Limits) -> Result, String> { + Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_dwg_bridge)] +pub fn dxf_to_dwg(_dxf: &[u8]) -> Result, String> { + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_dwg_bridge)] +pub fn dxf_to_dwg_as(_dxf: &[u8], _version: &str) -> Result, String> { + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_dwg_bridge)] +pub fn dxf_to_dwg_noted(_dxf: &[u8], _version: &str) -> Result<(Vec, Unwritten), String> { + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_dwg_bridge)] +pub fn dxf_to_dwg_kept_as(_dxf: &[u8], _version: &str, _kept: &str) -> Result, String> { + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_dwg_bridge)] +pub fn dxf_to_dwg_kept_noted(_dxf: &[u8], _version: &str, _kept: &str) -> Result<(Vec, Unwritten), String> { + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The DXF of an empty drawing, enough for the bridge to make a small DWG. + #[cfg(not(no_dwg_bridge))] + const MINIMAL_DXF: &str = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nEOF\n"; + + /// Makes `stage` panic on the current thread until dropped. + #[cfg(not(no_dwg_bridge))] + struct PanicIn; + + #[cfg(not(no_dwg_bridge))] + impl PanicIn { + fn at(stage: &'static str) -> Self { + PANIC_IN.with(|p| p.set(Some(stage))); + Self + } + } + + #[cfg(not(no_dwg_bridge))] + impl Drop for PanicIn { + fn drop(&mut self) { + PANIC_IN.with(|p| p.set(None)); + } + } + + /// The public read reports a panic in the post-read fix-ups as an error: this fails if the + /// `guarded` call around `post_process` is taken out (#2402). + #[cfg(not(no_dwg_bridge))] + #[test] + fn reading_a_dwg_survives_a_panic_in_post_processing() { + let dwg = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap(); + assert!(dwg_to_dxf(&dwg).is_ok(), "the DWG reads without the forced panic"); + let _panic = PanicIn::at("post_process"); + let err = dwg_to_dxf(&dwg).unwrap_err(); + assert!(err.contains("the DWG post-processing failed on this file"), "{err}"); + } + + /// The DXF to DWG conversion reports a panic in its fix-ups as an error, not a crash (#2402). + #[cfg(not(no_dwg_bridge))] + #[test] + fn converting_to_dwg_survives_a_panic_in_the_fix_ups() { + let _panic = PanicIn::at("convert"); + let err = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap_err(); + assert!(err.contains("the DXF to DWG conversion failed on this file"), "{err}"); + } + + #[test] + fn detects_magic() { + assert!(is_dwg(b"AC1032\0\0\0\0")); + assert!(!is_dwg(b" 0\r\nSECTION")); + assert_eq!(version(b"AC1018xxxx").as_deref(), Some("AC1018")); + } + + /// A DXF with ROMANS as `$TEXTSTYLE` gives a DWG whose current text style is ROMANS, not + /// Standard: the DXF names the style, and the handle read with it was Standard's (#1650). + #[cfg(not(no_dwg_bridge))] + #[test] + fn current_text_style_reaches_the_dwg() { + let header = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 9\n$TEXTSTYLE\n 7\nROMANS\n 0\nENDSEC\n"; + let style = " 0\nSTYLE\n 5\n1F0\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nROMANS\n 70\n0\n"; + let style = format!("{style} 40\n0\n 41\n1\n 50\n0\n 71\n0\n 42\n2.5\n 3\nromans.shx\n 4\n\n"); + let dxf = format!("{header} 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nSTYLE\n 70\n1\n{style} 0\nENDTAB\n 0\nENDSEC\n 0\nEOF\n"); + let dwg = dxf_to_dwg(dxf.as_bytes()).unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); + let romans = doc.text_styles.iter().find(|ts| ts.name == "ROMANS").map(|ts| ts.handle); + assert!(romans.is_some(), "ROMANS is missing from the DWG"); + assert_eq!(Some(doc.header.current_text_style_handle), romans); + } + + #[test] + fn garbage_is_an_error_not_a_crash() { + assert!(dwg_to_dxf(b"AC1032 this is not a dwg file at all").is_err()); + assert!(dwg_to_dxf(b"").is_err()); + } + + #[cfg(not(no_dwg_bridge))] + #[test] + fn dxf_to_dwg_rejects_garbage_without_crashing() { + // The DXF→DWG path runs the third-party reader inside catch_unwind and reports failures + // rather than crashing (and rejects oversized input before decoding). + assert!(dxf_to_dwg(b"not a dxf file").is_err()); + assert!(dxf_to_dwg(b"").is_err()); + } + + /// A DXF with one DIMENSION per (text, group 70, subclass, points) row. + #[cfg(not(no_dwg_bridge))] + type DimensionSpec<'a> = (&'a str, i64, &'a str, &'a [(i32, [f64; 2])]); + + #[cfg(not(no_dwg_bridge))] + fn dims_dxf(dims: &[DimensionSpec<'_>]) -> String { + let mut s = String::from(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n"); + for (text, flags, sub, pts) in dims { + s += " 0\nDIMENSION\n 8\n0\n100\nAcDbEntity\n100\nAcDbDimension\n 10\n0\n 20\n0\n 30\n0\n"; + s += &format!(" 11\n50\n 21\n-20\n 31\n0\n 70\n{flags}\n 1\n{text}\n 3\nStandard\n100\n{sub}\n"); + for (code, [x, y]) in pts.iter() { + s += &format!("{code:>3}\n{x}\n{:>3}\n{y}\n{:>3}\n0\n", code + 10, code + 20); + } + } + s + " 0\nENDSEC\n 0\nEOF\n" + } + + /// DWG stores DXF group 70's bit 128 inverted, in bit 0 of the dimension flags byte (set: + /// the text is at its default position), and bit 32 in bit 1 (ODA DWG specification, common + /// dimension data). The bytes are read back raw, so a reader that inverts bit 0 the same way + /// as the writer can't hide a wrong byte. + #[cfg(not(no_dwg_bridge))] + #[test] + fn dimension_text_position_flags_reach_the_dwg_as_autocad_reads_them() { + let linear: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [100.0, 0.0])]; + let radius: &[(i32, [f64; 2])] = &[(15, [10.0, 0.0])]; + let angular: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [10.0, 0.0]), (15, [0.0, 0.0]), (16, [0.0, 10.0])]; + let kinds = [ + (0, "AcDbAlignedDimension", linear), + (1, "AcDbAlignedDimension", linear), + (4, "AcDbRadialDimension", radius), + (2, "AcDb2LineAngularDimension", angular), + ]; + let mut dims = Vec::new(); + for (ty, sub, pts) in kinds { + dims.push(("HOME", ty | 32, sub, pts)); + dims.push(("MOVED", ty | 32 | 128, sub, pts)); + } + let dwg = dxf_to_dwg(dims_dxf(&dims).as_bytes()).unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); + let mut seen = Vec::new(); + for e in doc.entities() { + let acadrust::entities::EntityType::Dimension(d) = e else { continue }; + let (text, byte) = (d.base().text_override().unwrap_or_default(), d.base().dwg_flags_byte); + seen.push((text.to_string(), byte & 0x03)); + assert_eq!(byte & 0x02, 0x02, "{text} {:?}: bit 32 of group 70 is lost (flags byte {byte:#04x})", d.base().dimension_type); + let default_pos = text == "HOME"; + assert_eq!(byte & 0x01 != 0, default_pos, "{text} {:?}: flags byte {byte:#04x}", d.base().dimension_type); + } + for text in ["HOME", "MOVED"] { + assert_eq!(seen.iter().filter(|(t, _)| t == text).count(), 4, "{seen:?}"); + } + + // And CADCraft reads its own DWG back as it wrote it: 128 only on the moved texts. + let dxf = String::from_utf8(dwg_to_dxf(&dwg).unwrap()).unwrap(); + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let mut flags = Vec::new(); + for rec in lines.chunks(2).collect::>().split(|p| p.first() == Some(&"0")) { + let value = |code: &str| rec.iter().find(|p| p.first() == Some(&code)).and_then(|p| p.get(1).copied()); + if let (Some(text @ ("HOME" | "MOVED")), Some(v)) = (value("1"), value("70")) { + flags.push((text, v.parse::().unwrap_or(-1) & 128)); + } + } + assert_eq!(flags.len(), 8, "{flags:?}"); + assert!(flags.iter().all(|(l, f)| (*f == 128) == (*l == "MOVED")), "{flags:?}"); + } + + /// The handles a DXF text refers to or gives its records (groups 5, 105 and 330–369). + #[cfg(not(no_dwg_bridge))] + fn dxf_handles(dxf: &str) -> std::collections::HashSet { + let lines: Vec<&str> = dxf.lines().collect(); + lines + .chunks(2) + .filter_map(|p| match p { + [c, v] if matches!(c.trim().parse::(), Ok(5 | 105 | 330..=369)) => u64::from_str_radix(v.trim(), 16).ok(), + _ => None, + }) + .collect() + } + + /// Issue #1482: a DWG that once came from MicroStation can carry hundreds of thousands of DGN + /// line style components no definition uses (a real 83 MB site plan: 888,483 of 889,053, a + /// 1.2 GB DXF rendition over the limit, so it didn't open). They're left out with a note, and + /// their dictionary entries with them; the definition and every component it reaches — + /// through compound and point components, around a cycle — are kept. + #[cfg(not(no_dwg_bridge))] + #[test] + fn orphaned_dgn_line_style_components_are_left_out() { + use acadrust::objects::*; + let mut doc = acadrust::CadDocument::new(); + let container = doc.allocate_handle(); + let nod = doc.header.named_objects_dict_handle; + let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&nod) else { panic!("no named object dictionary") }; + root.entries.push(("ACAD_DGNLINESTYLECOMP".into(), container)); + let pattern = || DgnLsStrokePattern { + has_iteration_limit: false, + is_single_segment: false, + iteration_limit: 0, + auto_phase: 0.0, + phase: 0.0, + phase_mode: DgnLsPhaseMode::Distance, + strokes: vec![DgnLsStroke { + is_dash: true, + bypass_corner: false, + can_be_scaled: true, + invert_at_origin: false, + invert_at_end: false, + length: 2.5, + start_width: 0.0, + end_width: 0.0, + width_mode: 0, + cap_mode: 0, + }], + }; + let kind = |c: &DgnLsComponentData| match c { + DgnLsComponentData::Symbol(_) => DgnLsComponentType::Symbol, + DgnLsComponentData::Compound(_) => DgnLsComponentType::Compound, + DgnLsComponentData::Stroke(_) => DgnLsComponentType::Stroke, + DgnLsComponentData::Point(_) => DgnLsComponentType::Point, + DgnLsComponentData::Internal(_) => DgnLsComponentType::Internal, + }; + let compound = |of: &[acadrust::Handle]| { + DgnLsComponentData::Compound(DgnLsCompoundComponent { + entries: of.iter().map(|&component| DgnLsCompoundEntry { component, offset: 0.0 }).collect(), + }) + }; + let mut entries = Vec::new(); + let mut put = |doc: &mut acadrust::CadDocument, h: acadrust::Handle, data: DgnLineStyleData| { + entries.push((format!("{:X}", h.value()), h)); + let reactors = vec![container]; + doc.objects + .insert(h, ObjectType::DgnLineStyle(DgnLineStyleObject { handle: h, owner: container, reactors, xdictionary_handle: None, data })); + }; + let component = |c: DgnLsComponentData| DgnLineStyleData::Component { + kind: kind(&c), + description: "dash".into(), + version: 1, + component_uid: [7; 16], + scale: 1.0, + property_flags: 0, + component: c, + properties: vec![], + }; + let h: Vec = (0..9).map(|_| doc.allocate_handle()).collect(); + let [def, root, stroke, point, back, orphan, orphan_cycle, internal, shared] = h[..] else { panic!("nine handles") }; + put( + &mut doc, + def, + DgnLineStyleData::Definition { + description: "{ dash }".into(), + version: 1, + style_number: 1, + component_uid: [1; 16], + is_continuous: false, + unit_definition: 1.0, + unit_scale: 1.0, + units_type: 0, + is_element: false, + is_physical: false, + is_scale_independent: false, + is_snappable: false, + root_component: root, + properties: vec![], + }, + ); + // Used: def → root → {stroke, point → shared, back → root (a cycle)}. + put(&mut doc, root, component(compound(&[stroke, point, back]))); + put(&mut doc, stroke, component(DgnLsComponentData::Stroke(pattern()))); + put(&mut doc, point, component(DgnLsComponentData::Point(DgnLsPointComponent { stroke_component: shared, symbols: vec![] }))); + put(&mut doc, back, component(compound(&[root]))); + put(&mut doc, shared, component(DgnLsComponentData::Stroke(pattern()))); + // Orphans: an internal component, and two compounds that refer to each other and to a + // used component (which stays). + let pattern_internal = + DgnLsInternalComponent { pattern: pattern(), internal_version: 0, hardware_style: 0, is_hardware_style: false, line_code: 0 }; + put(&mut doc, internal, component(DgnLsComponentData::Internal(pattern_internal))); + put(&mut doc, orphan, component(compound(&[orphan_cycle, shared]))); + put(&mut doc, orphan_cycle, component(compound(&[orphan]))); + let mut dict = Dictionary::new(); + dict.handle = container; + dict.owner = nod; + dict.entries = entries; + doc.objects.insert(container, ObjectType::Dictionary(dict)); + let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); + + let (dxf, notes) = dwg_to_dxf_noted(&dwg, Limits::DEFAULT).unwrap(); + let dxf = String::from_utf8(dxf).unwrap(); + let handles = dxf_handles(&dxf); + for kept in [def, root, stroke, point, back, shared] { + assert!(handles.contains(&kept.value()), "{:X} was left out", kept.value()); + } + for gone in [internal, orphan, orphan_cycle] { + assert!(!handles.contains(&gone.value()), "{:X} was kept or is still referred to", gone.value()); + } + let lines: Vec<&str> = dxf.lines().collect(); + let ls: Vec<&str> = lines.chunks(2).filter_map(|p| p.get(1).filter(|_| p[0].trim() == "0" && p[1].starts_with("LS")).copied()).collect(); + assert_eq!(ls.iter().filter(|t| t.ends_with("COMPONENT")).count(), 5, "{ls:?}"); + assert!(ls.contains(&"LSDEFINITION") && !ls.contains(&"LSINTERNALCOMPONENT"), "{ls:?}"); + assert_eq!(notes, ["DWG: 3 DGN line style components that no line style definition uses were left out"]); + } + + /// An R2000 DXF header (`\r\n` lines, as CADCraft writes them) with `extra` after `$ACADVER`. + #[cfg(not(no_dwg_bridge))] + fn r2000(extra: &[u8]) -> Vec { + let mut dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n 9\r\n$DWGCODEPAGE\r\n 3\r\nANSI_1252\r\n".to_vec(); + dxf.extend_from_slice(b" 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\n"); + dxf.extend_from_slice(extra); + dxf.extend_from_slice(b"\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"); + dxf + } + + /// The kept version replaces only the `$ACADVER` value; everything else stays byte for byte. + #[cfg(not(no_dwg_bridge))] + #[test] + fn declare_version_changes_only_acadver() { + let dxf = r2000(b"A\\U+00E7\\U+00E3o"); + let out = native::declare_version(&dxf, acadrust::DxfVersion::AC1032).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), String::from_utf8(dxf).unwrap().replacen("AC1015", "AC1032", 1)); + } + + /// A kept version not newer than the declared one, a binary DXF and a DXF without `$ACADVER` + /// are read as they are. + #[cfg(not(no_dwg_bridge))] + #[test] + fn declare_version_leaves_what_it_need_not_change() { + let dxf = r2000(b"x"); + assert_eq!(native::declare_version(&dxf, acadrust::DxfVersion::AC1015), None); + assert_eq!(native::declare_version(&dxf, acadrust::DxfVersion::AC1009), None); + assert_eq!(native::declare_version(b"AutoCAD Binary DXF\r\n\x1a\0", acadrust::DxfVersion::AC1032), None); + let no_version = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + assert_eq!(native::declare_version(no_version, acadrust::DxfVersion::AC1032), None); + // A `$ACADVER` outside the HEADER section is not the file's version. + let late = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n"; + assert_eq!(native::declare_version(late, acadrust::DxfVersion::AC1032), None); + } + + /// The header is read as group code and value pairs up to the first `0`/`ENDSEC`: a `$ACADVER` + /// name whose value would come after it, or a file that never ends its HEADER, is no version + /// to replace, and `\r\n` lines keep the value's offset right. + #[cfg(not(no_dwg_bridge))] + #[test] + fn declare_version_reads_the_header_in_pairs_up_to_endsec() { + let cut = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 0\r\nENDSEC\r\n 1\r\nAC1015\r\n"; + assert_eq!(native::declare_version(cut, acadrust::DxfVersion::AC1032), None); + let endless = vec![b'\n'; 1 << 20]; + assert_eq!(native::declare_version(&endless, acadrust::DxfVersion::AC1032), None); + let crlf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1015\r\n 0\r\nENDSEC\r\n"; + let out = native::declare_version(crlf, acadrust::DxfVersion::AC1032).unwrap(); + assert_eq!(out, b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1032\r\n 0\r\nENDSEC\r\n"); + } + + /// Declared as 2007 or later, a DXF is UTF-8: code page text is decoded first. Declared as an + /// older version, the code page bytes stay as they are. + #[cfg(not(no_dwg_bridge))] + #[test] + fn declare_version_decodes_a_code_page_for_utf8_versions() { + let dxf = r2000(b"A\xe7\xe3o"); + let utf8 = native::declare_version(&dxf, acadrust::DxfVersion::AC1032).unwrap(); + let text = String::from_utf8(utf8).unwrap(); + assert!(text.contains("\r\nAção\r\n") && text.contains("$ACADVER\r\n 1\r\nAC1032\r\n"), "{text}"); + let legacy = native::declare_version(&dxf, acadrust::DxfVersion::AC1018).unwrap(); + assert!(legacy.windows(4).any(|w| w == b"A\xe7\xe3o"), "the code page bytes stay"); + assert!(legacy.windows(6).any(|w| w == b"AC1018")); + // A code page it doesn't know is read as Windows-1252, as acadrust reads an older DXF. + let at = dxf.windows(9).position(|w| w == b"ANSI_1252").unwrap(); + let unknown = [&dxf[..at], b"NO_SUCH_CP".as_slice(), &dxf[at + 9..]].concat(); + let text = String::from_utf8(native::declare_version(&unknown, acadrust::DxfVersion::AC1032).unwrap()).unwrap(); + assert!(text.contains("\r\nAção\r\n"), "{text}"); + // Without a `$DWGCODEPAGE` there is nothing to decode it by: it is read as it is. + let none = [&dxf[..at - 21], &dxf[at + 11..]].concat(); + assert!(!none.windows(12).any(|w| w == b"$DWGCODEPAGE"), "{}", String::from_utf8_lossy(&none)); + assert_eq!(native::declare_version(&none, acadrust::DxfVersion::AC1032), None); + } + + /// An unknown kept version converts as [`dxf_to_dwg_as`] does. + #[cfg(not(no_dwg_bridge))] + #[test] + fn unknown_kept_version_converts_as_before() { + let dxf = r2000(b"x"); + assert_eq!(dxf_to_dwg_kept_as(&dxf, "AC1032", "AC9999"), dxf_to_dwg_as(&dxf, "AC1032")); + assert!(dxf_to_dwg_kept_as(&dxf, "AC0000", "AC1032").is_err(), "an unwritable version is still an error"); + } + + /// The CLASS names in CLASSES order; nothing for a binary DXF or one without CLASSES. + #[cfg(not(no_dwg_bridge))] + #[test] + fn dxf_class_names_in_classes_order() { + let dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 1\r\nWIDGETA\r\n 2\r\nAcDbWidgetA\r\n 3\r\nApp\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 2\r\nAcDbWidgetB\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\nNOT_A_CLASS\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + assert_eq!(native::dxf_class_names(dxf).unwrap(), ["WIDGETA", "WIDGETB"]); + // A CLASS record without a name keeps its place, so the classes after it keep theirs + // (#2837 review). + let unnamed = b" 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 2\r\nAcDbNoName\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + assert_eq!(native::dxf_class_names(unnamed).unwrap(), ["", "WIDGETB"]); + assert_eq!(native::dxf_class_names(b" 0\nSECTION\n 2\nHEADER\n 0\nENDSEC\n 0\nEOF\n"), Some(Vec::new())); + assert_eq!(native::dxf_class_names(b"AutoCAD Binary DXF\r\n\x1a\0"), None); + } + + /// AutoCAD's DWG scale action (BLOCKSCALEACTION) ends with a byte after its three + /// connections that DXF doesn't carry. acadrust 0.6.4 neither read nor wrote it, so AutoCAD + /// read past the object and refused every DWG CADCraft wrote with a dynamic block that scales + /// ("Error Decrypting Data"); 0.6.5 added it and 0.6.6, which this uses, still keeps it (0.6.6 also + /// fixes multi-layout DWGs, #1463). The byte reaches the DWG, and a scale action + /// from DXF is written whole, with the byte AutoCAD writes (0). + #[cfg(not(no_dwg_bridge))] + #[test] + fn scale_actions_keep_the_byte_autocad_reads_after_their_connections() { + use acadrust::objects::*; + let scale_action = |doc: &acadrust::CadDocument| { + doc.objects.values().find_map(|o| match o { + ObjectType::DynamicBlock(DynamicBlockObject { data: DynamicBlockData::ScaleAction(s), .. }) => Some(s.clone()), + _ => None, + }) + }; + let mut doc = acadrust::CadDocument::new(); + let h = doc.allocate_handle(); + let conn = |code, name: &str| BlockConnection { code, name: name.into() }; + let mut action = DynamicBlockObject::new("BLOCKSCALEACTION", "AcDbBlockScaleAction"); + action.handle = h; + action.owner = doc.header.named_objects_dict_handle; + let mut a = BlockBasePointAction::default(); + a.action.action.element.name = "Scale".into(); + a.action.connections = vec![conn(2, "UpdatedBaseX"), conn(2, "UpdatedBaseY")]; + a.action.dependent = true; + a.connections = vec![conn(2, "Scale"), conn(2, "XScale"), conn(2, "YScale")]; + a.dwg_tail_byte = 7; + action.data = DynamicBlockData::ScaleAction(a.clone()); + doc.objects.insert(h, ObjectType::DynamicBlock(action)); + + let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + assert_eq!(scale_action(&back).map(|s| s.dwg_tail_byte), Some(7), "the byte isn't written"); + + let mut dxf = Vec::new(); + acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); + for version in ["AC1018", "AC1032"] { + let dwg = dxf_to_dwg_as(&dxf, version).unwrap(); + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let read = scale_action(&back).unwrap_or_else(|| panic!("{version}: the scale action wasn't written")); + assert_eq!(read.connections, a.connections, "{version}"); + assert_eq!(read.action.connections, a.action.connections, "{version}"); + assert_eq!(read.dwg_tail_byte, 0, "{version}"); + } + } + + /// Saving says what the DWG writer left out, per type: entities of types acadrust's DXF + /// reader doesn't model (another program's custom entity) can't be written; a drawing the DWG + /// keeps whole reports nothing. + #[cfg(not(no_dwg_bridge))] + #[test] + fn saving_lists_the_types_the_dwg_writer_leaves_out() { + let line = " 0\nLINE\n 8\n0\n100\nAcDbEntity\n100\nAcDbLine\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 11\n10.0\n 21\n0.0\n 31\n0.0\n"; + let widget = " 0\nACME_WIDGET\n 8\n0\n100\nAcDbEntity\n100\nAcmeWidget\n 10\n1.0\n 20\n2.0\n 30\n0.0\n"; + let dxf = |body: &str| { + format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n{body} 0\nENDSEC\n 0\nEOF\n") + }; + for version in ["AC1015", "AC1018", "AC1032"] { + let (dwg, unwritten) = dxf_to_dwg_noted(dxf(&format!("{line}{widget}{widget}")).as_bytes(), version).unwrap(); + assert!(is_dwg(&dwg), "{version}"); + assert_eq!(unwritten, [("ACME_WIDGET".to_string(), 2)].into_iter().collect::(), "{version}"); + } + let (_, unwritten) = dxf_to_dwg_noted(dxf(line).as_bytes(), "AC1032").unwrap(); + assert!(unwritten.is_empty(), "{unwritten:?}"); + } + + /// An OLE2FRAME, which CADCraft keeps as its DXF groups without modelling it, is written to + /// the DWG with its data: it isn't in the list of what the writer left out. + #[cfg(not(no_dwg_bridge))] + #[test] + fn ole_frames_are_written_with_their_data() { + let ole = " 0\nOLE2FRAME\n 8\n0\n100\nAcDbEntity\n100\nAcDbOle2Frame\n 70\n2\n 10\n1.0\n 20\n9.0\n 30\n0.0\n 11\n8.0\n 21\n2.0\n 31\n0.0\n 71\n2\n 72\n0\n 73\n1\n 90\n4\n310\nDEADBEEF\n 1\nOLE\n"; + let dxf = + format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n{ole} 0\nENDSEC\n 0\nEOF\n"); + for version in ["AC1015", "AC1018", "AC1032"] { + let (dwg, unwritten) = dxf_to_dwg_noted(dxf.as_bytes(), version).unwrap(); + assert!(unwritten.is_empty(), "{version} {unwritten:?}"); + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let frames: Vec> = back + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Ole2Frame(o) => Some(o.encoded_payload()), + _ => None, + }) + .collect(); + assert_eq!(frames, [vec![0xDE, 0xAD, 0xBE, 0xEF]], "{version}"); + } + } +} diff --git a/crates/dwg/src/proxy_transport.rs b/crates/dwg/src/proxy_transport.rs new file mode 100644 index 000000000..db0b984ec --- /dev/null +++ b/crates/dwg/src/proxy_transport.rs @@ -0,0 +1,632 @@ +//! Another application's entities and their classes through the DWG bridge: on reading a DWG, +//! registered entities acadrust has no model for become proxy entities of their class; on writing +//! one, the DWG gets the source DXF's classes in their places, so every proxy names its own class. + +use std::collections::{HashMap, HashSet}; + +use acadrust::CadDocument; +use acadrust::classes::{DxfClass, ProxyFlags}; +use acadrust::entities::{EntityType, ExtendedEntityData, ProxyEntityData}; +use acadrust::objects::{ObjectType, ProxyPayload}; + +fn class_number(index: usize) -> Result { + index.checked_add(500).and_then(|n| i16::try_from(n).ok()).ok_or_else(|| "DXF: too many application classes".into()) +} + +/// After a DWG read: each registered entity of another application's class that acadrust keeps +/// only as its record and opaque data (no decoded properties) becomes a proxy entity of that class +/// (DXF Reference, ACAD_PROXY_ENTITY), with its graphics, data bits, R2007+ strings and object +/// references, so the DXF keeps it; and every proxy's class number becomes 500 plus its class's +/// place in the classes, as a DXF numbers it. A record that can't be converted (its class is +/// missing or not unique) is left out and named in the notes; one with decoded properties stays as +/// read, also named, as its opaque data has no DXF form beside them. +pub(super) fn prepare(doc: &mut CadDocument) -> Vec { + let classes: Vec<_> = doc.classes.iter().cloned().collect(); + let mut numbers = HashMap::new(); + let mut identities = HashMap::new(); + for (index, class) in classes.iter().enumerate() { + let number = class_number(index).ok(); + numbers.entry(i32::from(class.class_number)).and_modify(|v| *v = None).or_insert(number.map(i32::from)); + let identity = (class.dxf_name.as_str(), class.cpp_class_name.as_str(), class.is_an_entity); + identities.entry(identity).and_modify(|v| *v = None).or_insert(number); + } + let identity = |dxf: &str, cpp: &str, entity: bool| { + identities + .get(&(dxf, cpp, entity)) + .copied() + .flatten() + .map(i32::from) + .ok_or_else(|| format!("missing or ambiguous application CLASS for {dxf:.80} ({cpp:.80})")) + }; + let Some(dwg_version) = super::native::proxy_dwg_version(doc.dwg_source_version.unwrap_or(doc.version)) else { return Vec::new() }; + let maintenance = i32::from(doc.maintenance_version); + let remap = |id: i32| numbers.get(&id).copied().flatten().ok_or_else(|| format!("proxy names missing or ambiguous application class {id}")); + // Only mutate proxies: entities_mut invalidates the decoder's verbatim records for every entity. + let handles: Vec<_> = doc + .entities() + .filter_map(|e| match e { + EntityType::Extended(e) => match &e.data { + ExtendedEntityData::Proxy(_) => Some(e.common.handle), + ExtendedEntityData::RegisteredClass(data) if data.properties.is_empty() || data.payload.bit_count > 0 => Some(e.common.handle), + _ => None, + }, + _ => None, + }) + .collect(); + let mut notes = Vec::new(); + let mut entity_count = 0usize; + let mut object_count = 0usize; + let mut semantic = 0usize; + for handle in handles { + // Ok(None): not an application record; Ok(Some(None)): kept as read, with its properties. + let converted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result>, String> { + let Some(EntityType::Extended(entity)) = doc.get_entity(handle) else { return Ok(None) }; + let data = match &entity.data { + ExtendedEntityData::Proxy(data) => { + let mut proxy = data.clone(); + proxy.class_id = remap(proxy.class_id)?; + ExtendedEntityData::Proxy(proxy) + } + ExtendedEntityData::RegisteredClass(data) => { + if !data.properties.is_empty() { + return Ok(Some(None)); + } + let class_id = identity(&data.dxf_name, &data.cpp_class_name, true)?; + let text_payload = entity.common.raw_record.as_deref().map(registered_text).transpose()?.unwrap_or_default(); + ExtendedEntityData::Proxy(ProxyEntityData { + proxy_id: 498, + class_id, + dxf_subclass: String::new(), + version: (maintenance << 16) | dwg_version, + dwg_version, + maintenance_version: maintenance, + from_dxf: false, + graphics: ProxyPayload::from_bytes(entity.common.graphic_data.as_deref().unwrap_or_default()), + payload: data.payload.clone(), + text_payload, + object_ids: data.object_ids.clone(), + }) + } + _ => return Ok(None), + }; + Ok(Some(Some(data))) + })) + .unwrap_or_else(|_| Err("application record conversion failed".into())); + match converted { + Ok(Some(Some(data))) => { + if let Some(EntityType::Extended(entity)) = doc.get_entity_mut(handle) { + entity.data = data; + } + } + Ok(Some(None)) => semantic = semantic.saturating_add(1), + Ok(None) => {} + Err(why) => { + doc.remove_entity(handle); + entity_count = entity_count.saturating_add(1); + skipped_note(&mut notes, "entity", handle, &why); + } + } + } + doc.objects.retain(|handle, object| { + if let ObjectType::ProxyObject(proxy) = object { + match remap(proxy.class_id) { + Ok(id) => proxy.class_id = id, + Err(why) => { + object_count = object_count.saturating_add(1); + skipped_note(&mut notes, "object", *handle, &why); + return false; + } + } + } + true + }); + if entity_count > 0 || object_count > 0 { + notes.insert(0, format!("DWG: partial read; application proxy records left out (entities: {entity_count}, objects: {object_count})")); + } + if semantic > 0 { + notes.push(format!( + "DWG: {semantic} registered entities with decoded properties keep them, without their other data; saving over the original file would lose it" + )); + } + notes +} + +fn skipped_note(notes: &mut Vec, kind: &str, handle: acadrust::types::Handle, why: &str) { + if notes.len() < 6 { + let why: String = why.chars().take(256).collect(); + notes.push(format!("DWG: proxy {kind} {handle} left out: {why}")); + } +} + +/// The decoder's registered-class representation omits the separate R2007+ string stream. +fn registered_text(raw: &acadrust::entities::RawRecord) -> Result { + use acadrust::io::dwg::DwgVersion; + use acadrust::io::dwg::dwg_stream_readers::object_reader::DwgObjectReader; + use acadrust::io::dwg::dwg_stream_writers::bit_writer::DwgBitWriter; + use acadrust::types::DxfVersion; + + if raw.version < DxfVersion::AC1021 { + return Ok(ProxyPayload::default()); + } + let version = DwgVersion::from_dxf_version(raw.version).map_err(|e| format!("DWG proxy text: {e}"))?; + let handle_bits = usize::try_from(raw.handle_bits).map_err(|_| "DWG proxy text: negative handle stream size")?; + let total_bits = raw.data.len().checked_mul(8).ok_or("DWG proxy text: record too large")?; + if handle_bits > total_bits { + return Err("DWG proxy text: handle stream exceeds record".into()); + } + // Frame the verbatim record for the dependency's checked object reader. + let mut frame = DwgBitWriter::new(version, raw.version); + frame.write_modular_short(raw.data.len()); + if raw.version >= DxfVersion::AC1024 { + frame.write_modular_char(handle_bits); + } + frame.write_bytes(&raw.data); + let reader = DwgObjectReader::new(frame.into_bytes(), raw.version, HashMap::new()).map_err(|e| format!("DWG proxy text: {e}"))?; + let (kind, mut streams) = reader.read_record_at(0).map_err(|e| format!("DWG proxy text: {e}"))?; + reader.read_common_entity_data(&mut streams, kind); + if kind == 498 { + // An existing registered-class envelope is a proxy and carries its class name first. + streams.read_variable_text(); + } else if kind < 500 { + return Err("DWG proxy text: registered entity has no application class".into()); + } + streams.check_error().map_err(|e| format!("DWG proxy text: {e}"))?; + let bits = usize::try_from(streams.text_remaining_bits()).map_err(|_| "DWG proxy text: negative string stream size")?; + if bits > total_bits { + return Err("DWG proxy text: string stream exceeds record".into()); + } + let count = u32::try_from(bits).map_err(|_| "DWG proxy text: string stream too large")?; + let mut bytes = vec![0; bits.div_ceil(8)]; + for (index, byte) in bytes.iter_mut().enumerate() { + for bit in 0..8.min(bits.saturating_sub(index * 8)) { + if streams.read_text_bit() { + *byte |= 0x80 >> bit; + } + } + } + streams.check_error().map_err(|e| format!("DWG proxy text: {e}"))?; + Ok(ProxyPayload::from_bits(&bytes, count)) +} + +/// ASCII DXF pairs decoded with the bridge's public code-page and escape codecs. A malformed +/// pair yields `None`, so both class scans fall back rather than guessing its identity. +pub(super) fn text_pairs(dxf: &[u8]) -> Option> + '_> { + use acadrust::io::dxf::code_page::{decode_legacy_escapes, encoding_from_code_page}; + + if dxf.starts_with(b"AutoCAD Binary DXF") { + return None; + } + let version = + super::native::header_value(dxf, b"$ACADVER").and_then(|(_, v)| std::str::from_utf8(v).ok()).map(acadrust::DxfVersion::from_version_string); + let unicode = version.is_some_and(|v| v >= acadrust::DxfVersion::AC1021); + let encoding = if version.is_some_and(|v| v < acadrust::DxfVersion::AC1021) { + super::native::header_value(dxf, b"$DWGCODEPAGE").and_then(|(_, page)| std::str::from_utf8(page).ok()).and_then(encoding_from_code_page) + } else { + None + }; + let mut lines = dxf.split(|b| *b == b'\n').map(|line| line.strip_suffix(b"\r").unwrap_or(line)); + Some(std::iter::from_fn(move || { + let code = lines.next()?; + let Some(value) = lines.next() else { return (!code.trim_ascii().is_empty()).then_some(None) }; + let pair = || { + let code = std::str::from_utf8(code).ok()?.trim().parse().ok()?; + let text = if let Some(encoding) = encoding { + encoding.decode(value).0.into_owned() + } else if unicode { + String::from_utf8_lossy(value).into_owned() + } else { + // The decoder uses UTF-8 with Latin-1 fallback when no encoding was declared. + std::str::from_utf8(value).map_or_else(|_| value.iter().map(|&b| char::from(b)).collect(), str::to_string) + }; + let text = decode_legacy_escapes(&text); + // DXF's escaped control characters are decoded after CIF/MIF, as in the bridge. + let text = text.replace("^J", "\n").replace("^M", "\r").replace("^I", "\t").replace("^ ", "^"); + Some((code, text)) + }; + Some(pair()) + })) +} + +/// The CLASS records of an ASCII DXF, in CLASSES order and numbered by place from 500 (DXF +/// Reference, CLASSES; a proxy's group 91 is that number). `None` for a binary DXF (the bridge's +/// generated DXF is ASCII), and for one with a record that can't be written back as it is: no names, +/// flags or instance count out of range, more classes than the numbers allow. Then +/// `proxy_classes` matches the classes by name instead. +pub(super) fn source_classes(dxf: &[u8]) -> Option> { + let pairs = text_pairs(dxf)?; + let mut records: Vec> = Vec::new(); + let (mut section, mut in_classes) = (false, false); + for pair in pairs { + let (code, value) = pair?; + match (code, value.as_str()) { + (0, "ENDSEC") if in_classes => break, + (0, "SECTION") => section = true, + (2, name) if section => { + in_classes = name == "CLASSES"; + section = false; + } + (0, kind) if in_classes => { + if kind != "CLASS" { + return None; + } + records.push(Vec::new()); + } + (code, value) if in_classes => records.last_mut()?.push((code, value.to_string())), + _ => section = false, + } + } + records.iter().enumerate().map(|(index, groups)| source_class(groups, class_number(index).ok()?)).collect() +} + +/// One CLASS record's groups as the class `number`, or `None` when it can't be written back. +fn source_class(groups: &[(i32, String)], number: i16) -> Option { + let text = |code| groups.iter().find(|(c, _)| *c == code).map(|(_, v)| v.clone()).unwrap_or_default(); + let integer = |code| groups.iter().find(|(c, _)| *c == code).map_or(Some(0), |(_, v)| v.trim().parse::().ok()); + let mut class = DxfClass::new(text(1), text(2)); + if class.dxf_name.is_empty() || class.cpp_class_name.is_empty() { + return None; + } + class.application_name = text(3); + class.proxy_flags = ProxyFlags(u16::try_from(integer(90)?).ok()?); + class.instance_count = i32::try_from(integer(91)?).ok()?; + class.was_zombie = integer(280)? != 0; + class.is_an_entity = integer(281)? != 0; + class.item_class_id = if class.is_an_entity { 498 } else { 499 }; + class.class_number = number; + Some(class) +} + +/// Give a DWG of 2013 or later the source DXF's classes (`classes`, from [`source_classes`]) in +/// their places, with their metadata and duplicate names, so each proxy's DXF class number names +/// its own class; the decoder's default classes the source lacks follow them. A proxy whose number +/// names no source class is left out, as `proxy_classes` leaves it out. Returns how many proxy objects and +/// entities were left out; nothing changes when the drawing has no proxies. `None`, with nothing +/// changed, when the classes would be more than the class numbers allow. +pub(super) fn restore_classes(doc: &mut CadDocument, classes: Vec) -> Option<(usize, usize)> { + let fits = |number: i32| number.checked_sub(500).and_then(|n| usize::try_from(n).ok()).is_some_and(|i| i < classes.len()); + let mut any = false; + let mut entities = Vec::new(); + for entity in doc.entities() { + if let EntityType::Extended(e) = entity + && let ExtendedEntityData::Proxy(p) = &e.data + { + any = true; + if !fits(p.class_id) { + entities.push(e.common.handle); + } + } + } + let mut objects = Vec::new(); + for (handle, object) in &doc.objects { + if let ObjectType::ProxyObject(p) = object { + any = true; + if !fits(p.class_id) { + objects.push(*handle); + } + } + } + if !any { + return Some((0, 0)); + } + let mut names: HashSet<_> = classes.iter().map(|c| c.dxf_name.to_uppercase()).collect(); + let defaults: Vec<_> = doc.classes.iter().filter(|c| names.insert(c.dxf_name.to_uppercase())).cloned().collect(); + if let Some(last) = classes.len().checked_add(defaults.len())?.checked_sub(1) { + class_number(last).ok()?; + } + for handle in &entities { + doc.remove_entity(*handle); + } + for handle in &objects { + doc.objects.remove(handle); + } + doc.classes.clear(); + for (index, mut class) in classes.into_iter().chain(defaults).enumerate() { + class.class_number = class_number(index).ok()?; + doc.classes.push_preserving(class); + } + Some((objects.len(), entities.len())) +} + +#[cfg(test)] +mod tests { + use super::*; + use acadrust::entities::{EntityCommon, ExtendedEntity, RegisteredClassEntityData}; + use acadrust::types::DxfVersion; + + fn proxy_doc() -> CadDocument { + let mut doc = CadDocument::new(); + doc.version = DxfVersion::AC1032; + doc.add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::Proxy(ProxyEntityData { + proxy_id: 498, + class_id: 501, + dxf_subclass: String::new(), + version: 33, + dwg_version: 33, + maintenance_version: 0, + from_dxf: false, + graphics: ProxyPayload::default(), + payload: ProxyPayload::from_bits(&[0x80], 1), + text_payload: ProxyPayload::default(), + object_ids: vec![], + }), + }))) + .unwrap(); + doc + } + + /// An ASCII DXF of `groups`, `(code, value)` per pair of lines. + fn dxf(groups: &[(i32, &str)]) -> Vec { + groups.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::().into_bytes() + } + + #[test] + fn source_classes_keep_duplicates_and_metadata_before_defaults() { + let bytes = dxf(&[ + (0, "SECTION"), + (2, "HEADER"), + (9, "$DIMSTYLE"), + (2, "CLASSES"), + (0, "ENDSEC"), + (0, "SECTION"), + (2, "CLASSES"), + (0, "CLASS"), + (1, "Объект"), + (2, "First"), + (3, "Первый"), + (90, "1025"), + (91, "7"), + (280, "1"), + (281, "1"), + (0, "CLASS"), + (1, "Объект"), + (2, "Second"), + (3, "Второй"), + (90, "128"), + (281, "1"), + (0, "ENDSEC"), + (0, "EOF"), + ]); + let classes = source_classes(&bytes).unwrap(); + assert_eq!(classes.len(), 2); + assert_eq!(classes[0].application_name, "Первый"); + assert_eq!(classes[0].proxy_flags.0, 1025); + assert_eq!(classes[0].instance_count, 7); + assert!(classes[0].was_zombie); + assert_eq!((classes[0].class_number, classes[1].class_number), (500, 501)); + assert_eq!(classes[1].cpp_class_name, "Second"); + let mut doc = proxy_doc(); + assert_eq!(restore_classes(&mut doc, classes.clone()), Some((0, 0))); + assert_eq!(doc.classes.iter().take(2).cloned().collect::>(), classes); + // A binary DXF, and a CLASS record that can't be written back as it is, give no classes. + assert!(source_classes(b"AutoCAD Binary DXF\r\n\x1a\0").is_none()); + for (code, value) in [(1, ""), (2, ""), (90, "65536"), (91, "9223372036854775807"), (281, "x")] { + let mut class = vec![(1, "A"), (2, "A")]; + class.retain(|(c, _)| *c != code); + class.push((code, value)); + let mut groups = vec![(0, "SECTION"), (2, "CLASSES"), (0, "CLASS")]; + groups.extend(class); + groups.extend([(0, "ENDSEC"), (0, "EOF")]); + assert!(source_classes(&dxf(&groups)).is_none(), "{code} {value}"); + } + } + + #[test] + fn source_classes_decode_escapes_once_and_respect_legacy_code_pages() { + let body = "0\nCLASS\n1\n\\U+041E\\U+0431\\U+044A\\U+0435\\U+043A\\U+0442\n2\nClass\n3\nCaf\\U+00E9\\U+D83D\\U+DE42\\U+005CU+0041\n281\n1\n0\nENDSEC\n0\nEOF\n"; + let text = format!("0\nSECTION\n2\nCLASSES\n{body}"); + let classes = source_classes(text.as_bytes()).unwrap(); + assert_eq!(classes[0].dxf_name, "Объект"); + assert_eq!(classes[0].application_name, "Café🙂\\U+0041"); + + let prefix = + b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DWGCODEPAGE\n3\nANSI_1251\n0\nENDSEC\n0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\n"; + let encoded = [prefix.as_slice(), b"\xCF\xF0\xE8\xEC\xE5\xF0", b"\n2\nClass\n3\nApp\n281\n1\n0\nENDSEC\n0\nEOF\n"].concat(); + assert_eq!(source_classes(&encoded).unwrap()[0].dxf_name, "Пример"); + // R2007+ text is UTF-8 even with a legacy code-page declaration. + let modern = String::from_utf8_lossy(prefix).replace("AC1015", "AC1032") + "Пример\n2\nClass\n3\nApp\n281\n1\n0\nENDSEC\n0\nEOF\n"; + assert_eq!(source_classes(modern.as_bytes()).unwrap()[0].dxf_name, "Пример"); + } + + #[test] + fn proxies_of_missing_classes_are_left_out() { + for id in [-1, 499, 501, i32::MAX] { + let mut doc = proxy_doc(); + if let Some(EntityType::Extended(e)) = doc.entities_mut().next() + && let ExtendedEntityData::Proxy(p) = &mut e.data + { + p.class_id = id; + } + let mut class = DxfClass::new_entity("ENTITY", "Entity"); + class.class_number = 500; + assert_eq!(restore_classes(&mut doc, vec![class]), Some((0, 1)), "{id}"); + assert_eq!(doc.entities().count(), 0); + } + // Class 501 is there: the proxy keeps it, in its place. + let mut doc = proxy_doc(); + assert_eq!(restore_classes(&mut doc, vec![DxfClass::new("A", "A"), DxfClass::new_entity("B", "B")]), Some((0, 0))); + assert_eq!(doc.entities().count(), 1); + assert_eq!(doc.classes.iter().nth(1).map(|c| (c.dxf_name.clone(), c.class_number)), Some(("B".to_string(), 501))); + // Without proxies the classes stay the decoder's. + let mut doc = CadDocument::new(); + let before: Vec<_> = doc.classes.iter().cloned().collect(); + assert_eq!(restore_classes(&mut doc, vec![DxfClass::new("A", "A")]), Some((0, 0))); + assert_eq!(doc.classes.iter().cloned().collect::>(), before); + } + + #[test] + fn unrepresentable_proxies_keep_other_geometry_and_bounded_diagnostics() { + use acadrust::entities::{Line, RawRecord}; + use acadrust::objects::ProxyObject; + use acadrust::types::{Handle, Vector3}; + for count in [1, 10] { + let mut doc = proxy_doc(); + if let Some(EntityType::Extended(e)) = doc.entities_mut().next() + && let ExtendedEntityData::Proxy(p) = &mut e.data + { + p.class_id = i32::MAX; + } + let template = doc.entities().next().unwrap().clone(); + for _ in 1..count { + let mut entity = template.clone(); + entity.common_mut().handle = Handle::NULL; + doc.add_entity(entity).unwrap(); + } + let object = Handle::new(u64::MAX - 1); + assert!(!doc.objects.contains_key(&object)); + doc.objects.insert(object, ObjectType::ProxyObject(ProxyObject { handle: object, class_id: i32::MAX, ..Default::default() })); + let line = doc.add_entity(EntityType::Line(Line::from_points(Vector3::new(2.0, 3.0, 0.0), Vector3::new(12.0, 13.0, 0.0)))).unwrap(); + let raw = RawRecord { data: vec![0xAA, 0x55], handle_bits: 0, version: DxfVersion::AC1032 }; + doc.get_entity_mut(line).unwrap().common_mut().raw_record = Some(std::sync::Arc::new(raw.clone())); + let notes = prepare(&mut doc); + assert_eq!(notes.len(), (count + 1).min(6) + 1); + assert!(notes.iter().all(|n| n.starts_with("DWG:"))); + assert!(notes[0].contains(&format!("entities: {count}, objects: 1"))); + assert_eq!(doc.entities().count(), 1); + assert!(!doc.objects.contains_key(&object)); + let Some(EntityType::Line(actual)) = doc.get_entity(line) else { panic!("readable line") }; + assert_eq!(actual.start, Vector3::new(2.0, 3.0, 0.0)); + assert_eq!(actual.end, Vector3::new(12.0, 13.0, 0.0)); + assert_eq!(doc.get_entity(line).unwrap().common().raw_record.as_deref(), Some(&raw)); + } + } + #[test] + fn opaque_registered_class_ambiguity_is_not_guessed() { + let mut doc = CadDocument::new(); + doc.classes.push_preserving(DxfClass::new_entity("CUSTOM", "Custom")); + doc.classes.push_preserving(DxfClass::new_entity("CUSTOM", "Custom")); + doc.add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "CUSTOM".into(), + cpp_class_name: "Custom".into(), + properties: vec![], + payload: ProxyPayload::from_bits(&[0x80], 1), + object_ids: vec![], + }), + }))) + .unwrap(); + assert!(prepare(&mut doc).iter().any(|n| n.contains("ambiguous"))); + assert_eq!(doc.entities().count(), 0); + assert!(class_number(usize::MAX).is_err()); + } + #[test] + fn semantic_records_keep_verbatim_data_and_mixed_payloads_are_reported() { + use acadrust::entities::RawRecord; + use acadrust::objects::{SemanticProperty, SemanticPropertyValue}; + for payload in [ProxyPayload::default(), ProxyPayload::from_bits(&[0x80], 1)] { + let mut doc = CadDocument::new(); + let raw = RawRecord { data: vec![0xAA], handle_bits: 0, version: DxfVersion::AC1032 }; + let handle = doc + .add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "SEMANTIC".into(), + cpp_class_name: "Semantic".into(), + properties: vec![SemanticProperty { + subclass: "Semantic".into(), + code: 1, + value: SemanticPropertyValue::Text("value".into()), + }], + payload: payload.clone(), + object_ids: vec![], + }), + }))) + .unwrap(); + doc.get_entity_mut(handle).unwrap().common_mut().raw_record = Some(std::sync::Arc::new(raw.clone())); + assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw)); + if payload.bit_count == 0 { + assert!(prepare(&mut doc).is_empty()); + assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw)); + } else { + // Kept as read, and named: its opaque data has no DXF form beside the properties. + assert!(prepare(&mut doc).iter().any(|n| n.contains("decoded properties"))); + assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw)); + } + } + } +} + +#[cfg(test)] +mod string_stream_tests { + use super::*; + use acadrust::entities::{EntityCommon, ExtendedEntity, RawRecord, RegisteredClassEntityData}; + use acadrust::types::DxfVersion; + use std::io::Cursor; + + #[test] + fn registered_transport_recovers_separate_non_byte_aligned_strings() { + for version in [DxfVersion::AC1027, DxfVersion::AC1032] { + let mut source = CadDocument::new(); + source.version = version; + source.classes.add_or_update(DxfClass::new_entity("CUSTOM_TEXT", "CustomText")); + let class_id = i32::from(source.classes.get_by_name("CUSTOM_TEXT").unwrap().class_number); + let text = ProxyPayload::from_bits(&[0xA5, 0xC7, 0xE0], 19); + let payload = ProxyPayload::from_bits(&[0x80], 1); + source + .add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::Proxy(ProxyEntityData { + proxy_id: 498, + class_id, + dxf_subclass: "CustomText".into(), + version: 33, + dwg_version: 33, + maintenance_version: 0, + from_dxf: false, + graphics: ProxyPayload::default(), + payload: payload.clone(), + text_payload: text.clone(), + object_ids: vec![], + }), + }))) + .unwrap(); + let bytes = acadrust::DwgWriter::write_to_vec(&source).unwrap(); + let mut decoded = acadrust::DwgReader::from_stream(Cursor::new(bytes)).read().unwrap(); + let entity = decoded.entities().next().unwrap(); + let handle = entity.common().handle; + let raw = entity.common().raw_record.clone().unwrap(); + assert_eq!(registered_text(&raw).unwrap().data(), text.data()); + assert_eq!(registered_text(&raw).unwrap().bit_count, 19); + let EntityType::Extended(entity) = decoded.get_entity_mut(handle).unwrap() else { panic!() }; + entity.data = ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "CUSTOM_TEXT".into(), + cpp_class_name: "CustomText".into(), + properties: vec![], + payload: payload.clone(), + object_ids: vec![], + }); + entity.common.raw_record = Some(raw); + assert!(prepare(&mut decoded).is_empty()); + for _ in 0..2 { + let mut dxf = Vec::new(); + acadrust::DxfWriter::new(&decoded).write_to_writer(&mut dxf).unwrap(); + let bytes = crate::dxf_to_dwg_as(&dxf, "AC1032").unwrap(); + decoded = acadrust::DwgReader::from_stream(Cursor::new(bytes)).read().unwrap(); + let p = decoded + .entities() + .find_map(|e| match e { + EntityType::Extended(e) => match &e.data { + ExtendedEntityData::Proxy(p) => Some(p), + _ => None, + }, + _ => None, + }) + .unwrap(); + assert_eq!(p.payload.bit_count, 1); + assert_eq!(p.payload.data(), payload.data()); + assert_eq!(p.text_payload.bit_count, 19); + assert_eq!(p.text_payload.data(), text.data()); + } + } + } + + #[test] + fn invalid_string_stream_boundaries_return_errors() { + for handle_bits in [-1, 1000] { + let raw = RawRecord { data: vec![0; 8], handle_bits, version: DxfVersion::AC1032 }; + assert!(registered_text(&raw).is_err()); + } + } +} diff --git a/crates/dwg/src/worker.rs b/crates/dwg/src/worker.rs new file mode 100644 index 000000000..1d16f5701 --- /dev/null +++ b/crates/dwg/src/worker.rs @@ -0,0 +1,425 @@ +//! The DWG reader and writer in a child process. +//! +//! An allocation failure or stack overflow in the third-party code ends the process it runs in, and +//! `catch_unwind` can't stop that. So the app runs them in a copy of itself: [`use_own_worker`] says +//! how to start one, and [`serve_if_asked`], first thing in `main`, turns the copy into a worker +//! that reads one request from standard input and writes one reply to standard output. A file that +//! kills the worker then costs that one open or save, and every other open drawing stays safe. +//! +//! Without a worker [`decode`] and [`encode_as`] refuse rather than run the conversion in the +//! calling process, because the third-party code is the part that can end a process. +//! [`allow_in_process`] is the explicit exception, for input the caller knows is trusted (tests, or +//! bytes this process produced itself). There's no memory limit on the worker yet: that takes +//! per-platform system calls, which `unsafe_code = "forbid"` keeps out of this crate. +//! +//! A reply comes from a process that just handled a possibly hostile file, so it is parsed as +//! untrusted input. + +use std::ffi::OsString; +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{RecvTimeoutError, channel}; +use std::time::Duration; + +use super::Limits; + +/// The argument that makes the app a worker. +pub const WORKER_ARG: &str = "--dwg-worker"; +/// Bumped when the messages change: an app updated while running may start a newer copy. +const PROTOCOL: u8 = 2; +const DECODE: u8 = 1; +const ENCODE: u8 = 2; +const CRASH: u8 = 0xff; +/// How long one file may take before the worker is stopped. It can't be interrupted otherwise. +const TIMEOUT: Duration = Duration::from_secs(30 * 60); +/// Most bytes accepted for what a reply carries besides the drawing. +const MAX_NOTES_BYTES: u64 = 64 << 20; +/// Most bytes accepted as a written DWG. +const MAX_DWG_REPLY: u64 = 2 << 30; +/// Most bytes one request holds: the largest input, whichever the direction, and its header. +const MAX_REQUEST: u64 = (2 << 30) + 256; +/// What a conversion says when it has no worker and is not allowed to run here. +const NO_WORKER: &str = "DWG: no worker is configured, so this file was not converted; \ + call use_worker or use_own_worker at startup, or allow_in_process for input that is trusted"; + +struct Worker { + program: PathBuf, + args: Vec, +} + +static WORKER: Mutex> = Mutex::new(None); +/// Whether this process may run the conversion itself, set only by [`allow_in_process`]. +static IN_PROCESS: AtomicBool = AtomicBool::new(false); + +/// Start `program args` as the worker from now on. `program` must call [`serve_if_asked`]. +pub fn use_worker(program: PathBuf, args: Vec) { + if let Ok(mut w) = WORKER.lock() { + *w = Some(Worker { program, args }); + } +} + +/// Use a copy of this program as the worker, started with [`WORKER_ARG`]. If its path can't be +/// found, the reader and writer stay in this process. +pub fn use_own_worker() { + match std::env::current_exe() { + Ok(program) => use_worker(program, vec![WORKER_ARG.into()]), + Err(e) => log::warn!("DWG worker: can't find this program: {e}"), + } +} + +/// Let [`decode`] and [`encode_as`] run the conversion in this process when no worker is set. +/// +/// This opts out of the isolation the crate exists for: the third-party code allocates from sizes +/// a hostile file declares, and a failed allocation ends the process. Call it for input the caller +/// knows is trusted (tests, or bytes this process produced), never for a file that arrived from +/// outside. +pub fn allow_in_process() { + IN_PROCESS.store(true, Ordering::Relaxed); +} + +fn in_process_allowed() -> bool { + IN_PROCESS.load(Ordering::Relaxed) +} + +/// Serve one request and return the exit code if this process was started as a worker. +pub fn serve_if_asked() -> Option { + (std::env::args_os().nth(1)? == WORKER_ARG).then(|| serve(std::io::stdin().lock(), std::io::stdout().lock())) +} + +/// [`super::dwg_to_dxf_noted`] in the worker. With no worker configured this is refused unless +/// [`allow_in_process`] was called; a configured worker that cannot start is an error. +pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { + // Before starting a process, and so the same limit holds with or without one. + if bytes.len() > limits.max_dwg_bytes { + return super::dwg_to_dxf_noted(bytes, limits); + } + let reply_limit = (limits.max_dxf_bytes as u64).saturating_add(MAX_NOTES_BYTES); + match call(&request(DECODE, limits, ""), bytes, reply_limit, "reading this file") { + Some(reply) => reply?, + None if in_process_allowed() => super::dwg_to_dxf_noted(bytes, limits), + None => Err(NO_WORKER.to_string()), + } +} + +/// [`super::dxf_to_dwg_as`] in the worker. Refused without a worker unless [`allow_in_process`] +/// was called. +pub fn encode_as(dxf: &[u8], version: &str) -> Result, String> { + encode_noted(dxf, version).map(|(dwg, _)| dwg) +} + +/// [`super::dxf_to_dwg_noted`] in the worker. What the writer left out comes back as notes of +/// `TYPEcount`. +pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec, super::Unwritten), String> { + encode_kept_noted(dxf, version, None) +} + +/// [`encode_noted`] for a DXF whose carried-over groups were read from a file of version `kept` +/// ([`super::dxf_to_dwg_kept_noted`]); `None` is [`encode_noted`]. +pub fn encode_kept_noted(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec, super::Unwritten), String> { + if u8::try_from(version.len()).is_err() { + return Err(super::unsupported(version)); + } + // A kept version too long to send is unsupported by this bridge and changes nothing. + let kept = kept.filter(|k| u8::try_from(k.len()).is_ok()); + let mut header = request(ENCODE, Limits::DEFAULT, version); + push_str(&mut header, kept.unwrap_or("")); + match call(&header, dxf, MAX_DWG_REPLY, "writing this file") { + Some(reply) => reply?.map(|(dwg, notes)| (dwg, unwritten_from(¬es))), + None if in_process_allowed() => encode_here(dxf, version, kept), + None => Err(NO_WORKER.to_string()), + } +} + +/// The conversion in this process. +fn encode_here(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec, super::Unwritten), String> { + match kept { + Some(kept) => super::dxf_to_dwg_kept_noted(dxf, version, kept), + None => super::dxf_to_dwg_noted(dxf, version), + } +} + +fn unwritten_from(notes: &[String]) -> super::Unwritten { + notes.iter().filter_map(|n| n.split_once('\t')).filter_map(|(kind, n)| Some((kind.to_string(), n.parse::().ok()?))).fold( + super::Unwritten::new(), + |mut m, (kind, n)| { + *m.entry(kind).or_insert(0) = n; + m + }, + ) +} + +/// Make the worker abort, as the third-party code can: what the tests prove isolation with. +#[doc(hidden)] +pub fn crash_worker_for_test() -> Result<(), String> { + call(&request(CRASH, Limits::DEFAULT, ""), &[], 1024, "testing").ok_or("no worker")??.map(|_| ()) +} + +fn request(op: u8, limits: Limits, version: &str) -> Vec { + let mut r = vec![PROTOCOL, op]; + r.extend((limits.max_dwg_bytes as u64).to_le_bytes()); + r.extend((limits.max_dxf_bytes as u64).to_le_bytes()); + push_str(&mut r, version); + r +} + +/// `text` with a one-byte length before it; callers keep it under 256 bytes. +fn push_str(r: &mut Vec, text: &str) { + r.push(u8::try_from(text.len()).unwrap_or(0)); + r.extend(text.as_bytes()); +} + +type Reply = Result<(Vec, Vec), String>; + +/// Run one request in a worker. `None`: no worker is configured, so the caller decides what to do +/// (convert here only with [`allow_in_process`], or refuse). `Err`: a configured worker could not +/// start or went wrong, and `doing` says at what, for the user. +fn call(header: &[u8], payload: &[u8], reply_limit: u64, doing: &str) -> Option> { + let mut command = { + let worker = WORKER.lock().ok()?; + let worker = worker.as_ref()?; + let mut c = Command::new(&worker.program); + c.args(&worker.args); + c + }; + command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); + } + let mut child = match command.spawn() { + Ok(c) => c, + Err(e) => { + // A worker is configured but cannot run: never fall back to decoding here. + log::warn!("DWG worker: can't start it: {e}"); + return Some(Err(format!("the DWG worker could not start ({e}); nothing else is affected"))); + } + }; + let (Some(mut to_child), Some(from_child)) = (child.stdin.take(), child.stdout.take()) else { + let _ = child.kill(); + let _ = child.wait(); + return Some(Err("the DWG worker could not start (no pipes); nothing else is affected".to_string())); + }; + let received = std::thread::scope(|scope| { + // Written beside the read: a worker that replies before it has read everything, or dies, + // must block neither side. A failed write shows up as the reply going wrong. + scope.spawn(move || { + let _ = to_child.write_all(header).and_then(|()| to_child.write_all(payload)); + }); + let (tx, rx) = channel(); + scope.spawn(move || { + let mut reply = Vec::new(); + let read = from_child.take(reply_limit).read_to_end(&mut reply); + let _ = tx.send(read.map(|_| reply)); + }); + let received = rx.recv_timeout(TIMEOUT); + if matches!(received, Err(RecvTimeoutError::Timeout)) { + let _ = child.kill(); + } + received + }); + let status = child.wait(); + let stopped = || format!("the DWG worker stopped while {doing}; nothing else is affected"); + Some(match (received, status) { + (Err(RecvTimeoutError::Timeout), _) => Err(format!("{doing} took too long, so the DWG worker was stopped; nothing else is affected")), + (Ok(Ok(reply)), Ok(status)) if status.success() => parse_reply(reply).ok_or_else(stopped), + _ => Err(stopped()), + }) +} + +/// Take `n` bytes off the front of `b`. +fn take<'a>(b: &mut &'a [u8], n: usize) -> Option<&'a [u8]> { + let (head, tail) = b.split_at_checked(n)?; + *b = tail; + Some(head) +} + +fn take_u32(b: &mut &[u8]) -> Option { + let bytes: [u8; 4] = take(b, 4)?.try_into().ok()?; + usize::try_from(u32::from_le_bytes(bytes)).ok() +} + +fn take_u64(b: &mut &[u8]) -> Option { + Some(u64::from_le_bytes(take(b, 8)?.try_into().ok()?)) +} + +/// A reply: 0, the note count, each note with its length, then the bytes with their length; or 1 +/// and a message. `None` when it isn't one, whole. Takes the reply, because the bytes can be most +/// of the memory the app may use: they are kept, not copied. +fn parse_reply(mut reply: Vec) -> Option { + let total = reply.len(); + let mut b = &reply[..]; + match *take(&mut b, 1)?.first()? { + 0 => { + let count = take_u32(&mut b)?; + let mut notes = Vec::new(); + for _ in 0..count { + let n = take_u32(&mut b)?; + notes.push(String::from_utf8_lossy(take(&mut b, n)?).into_owned()); + } + let n = usize::try_from(take_u64(&mut b)?).ok()?; + if b.len() != n { + return None; + } + reply.drain(..total - n); + Some(Ok((reply, notes))) + } + 1 => Some(Err(String::from_utf8_lossy(b).into_owned())), + _ => None, + } +} + +fn write_reply(out: &mut impl Write, reply: Reply) -> std::io::Result<()> { + match reply { + Ok((bytes, notes)) => { + out.write_all(&[0])?; + out.write_all(&u32::try_from(notes.len()).unwrap_or(0).to_le_bytes())?; + for note in ¬es { + out.write_all(&u32::try_from(note.len()).unwrap_or(0).to_le_bytes())?; + if u32::try_from(note.len()).is_ok() { + out.write_all(note.as_bytes())?; + } + } + out.write_all(&(bytes.len() as u64).to_le_bytes())?; + out.write_all(&bytes)?; + } + Err(e) => { + out.write_all(&[1])?; + out.write_all(e.as_bytes())?; + } + } + out.flush() +} + +/// What a request asks for, or why it can't be served. +fn handle(mut b: &[u8]) -> Reply { + let bad = || "the DWG worker got a request it can't read (a different bridge version?)".to_string(); + if take(&mut b, 1).and_then(<[u8]>::first) != Some(&PROTOCOL) { + return Err(bad()); + } + let op = take(&mut b, 1).and_then(<[u8]>::first).copied().ok_or_else(bad)?; + let max_dwg_bytes = take_u64(&mut b).and_then(|n| usize::try_from(n).ok()).ok_or_else(bad)?; + let max_dxf_bytes = take_u64(&mut b).and_then(|n| usize::try_from(n).ok()).ok_or_else(bad)?; + let version_len = take(&mut b, 1).and_then(<[u8]>::first).copied().ok_or_else(bad)?; + let version = take(&mut b, usize::from(version_len)).and_then(|v| std::str::from_utf8(v).ok()).ok_or_else(bad)?; + match op { + DECODE => super::dwg_to_dxf_noted(b, Limits { max_dwg_bytes, max_dxf_bytes }), + ENCODE => { + // The version the DXF's carried-over groups were read from; empty for none. + let kept_len = take(&mut b, 1).and_then(<[u8]>::first).copied().ok_or_else(bad)?; + let kept = take(&mut b, usize::from(kept_len)).and_then(|v| std::str::from_utf8(v).ok()).ok_or_else(bad)?; + encode_here(b, version, (!kept.is_empty()).then_some(kept)) + .map(|(dwg, left_out)| (dwg, left_out.iter().map(|(kind, n)| format!("{kind}\t{n}")).collect())) + } + CRASH => std::process::abort(), + _ => Err(bad()), + } +} + +/// Serve the one request on `input`. The exit code is 0 unless the reply couldn't be sent. +fn serve(input: impl Read, mut output: impl Write) -> i32 { + let mut request = Vec::new(); + let reply = match input.take(MAX_REQUEST).read_to_end(&mut request) { + Ok(_) => handle(&request), + Err(e) => Err(format!("the DWG worker could not read its request: {e}")), + }; + i32::from(write_reply(&mut output, reply).is_err()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn wire(reply: Reply) -> Vec { + let mut out = Vec::new(); + write_reply(&mut out, reply).unwrap(); + out + } + + #[test] + fn what_the_writer_left_out_survives_the_reply() { + let notes = vec!["ACME_WIDGET\t2".to_string(), "not a count".to_string(), "X\tmany".to_string()]; + assert_eq!(unwritten_from(¬es), [("ACME_WIDGET".to_string(), 2)].into_iter().collect()); + } + + #[test] + fn replies_round_trip() { + let ok: Reply = Ok((b"bytes".to_vec(), vec!["one".into(), "two é".into()])); + assert_eq!(parse_reply(wire(ok.clone())), Some(ok)); + let failed: Reply = Err("DWG: no".into()); + assert_eq!(parse_reply(wire(failed.clone())), Some(failed)); + } + + #[test] + fn a_reply_cut_short_or_made_up_is_refused() { + let whole = wire(Ok((b"bytes".to_vec(), vec!["note".into()]))); + for n in 0..whole.len() { + assert_eq!(parse_reply(whole[..n].to_vec()), None, "cut at {n}"); + } + assert_eq!(parse_reply(vec![7, 0, 0]), None); + // A note count far beyond what follows ends at the first missing note. + assert_eq!(parse_reply(vec![0, 0xff, 0xff, 0xff, 0xff]), None); + assert_eq!(parse_reply(vec![0, 1, 0, 0, 0, 0xff, 0xff, 0xff, 0xff]), None); + } + + #[test] + fn a_request_it_cannot_read_is_an_error_not_a_crash() { + for request in [ + &[][..], + &[PROTOCOL + 1, DECODE], + &[PROTOCOL], + &[PROTOCOL, DECODE, 1, 2, 3], + &[PROTOCOL, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] { + assert!(handle(request).is_err(), "{request:?}"); + } + } + + /// An encode request carries the kept version after the target one; a request without it is + /// one it can't read, and one with it reaches the converter. + #[test] + fn an_encode_request_carries_the_kept_version() { + let bad = "the DWG worker got a request it can't read (a different bridge version?)"; + let short = self::request(ENCODE, Limits::DEFAULT, "AC1032"); + assert_eq!(handle(&short).unwrap_err(), bad); + for kept in ["", "AC1032"] { + let mut request = self::request(ENCODE, Limits::DEFAULT, "AC1032"); + push_str(&mut request, kept); + request.extend(b"not a drawing"); + let err = handle(&request).unwrap_err(); + assert_ne!(err, bad, "kept {kept:?}"); + } + } + + /// A conversion is refused rather than run here, and a worker that cannot start is an error: + /// neither case may turn into decoding a (possibly hostile) file in this process. + #[test] + fn a_conversion_is_refused_without_a_worker_and_never_falls_back_to_this_process() { + // No worker is configured and nothing opted in. + assert_eq!(decode(b"AC1032", Limits::DEFAULT).unwrap_err(), NO_WORKER); + assert_eq!(encode_as(b"not a dxf", "AC1032").unwrap_err(), NO_WORKER); + // Trusted input may run here, and the reader still reports a file it cannot read. + allow_in_process(); + assert!(in_process_allowed()); + assert!(decode(b"AC1032", Limits::DEFAULT).is_err()); + assert!(encode_as(b"not a dxf", "AC1032").is_err()); + // A configured worker that cannot start is an error even after the opt-in: the conversion + // never runs here instead. + use_worker(PathBuf::from("/nonexistent/craft-dwg-worker"), Vec::new()); + assert!(decode(b"AC1032", Limits::DEFAULT).unwrap_err().contains("could not start")); + assert!(encode_as(b"not a dxf", "AC1032").unwrap_err().contains("could not start")); + } + + #[test] + fn serving_reports_a_decode_failure_as_a_reply() { + let mut request = self::request(DECODE, Limits::DEFAULT, ""); + request.extend(b"AC1032 not really a drawing"); + let mut out = Vec::new(); + assert_eq!(serve(&request[..], &mut out), 0); + assert!(matches!(parse_reply(out.clone()), Some(Err(_))), "{out:?}"); + } +} diff --git a/crates/dxf/src/paths.rs b/crates/dxf/src/paths.rs index d60d91456..7e4f18f0f 100644 --- a/crates/dxf/src/paths.rs +++ b/crates/dxf/src/paths.rs @@ -55,7 +55,11 @@ pub fn import(bytes: &[u8]) -> Result { if estimated_elements(&entity.kind) > remaining { return Err(Error::TooManySegments); } - let converted = entity_paths(&entity.kind, entity.common.extrusion); + let converted = if let crate::model::EntityKind::Spline(spline) = &entity.kind { + spline_path(spline)?.into_iter().collect() + } else { + entity_paths(&entity.kind, entity.common.extrusion) + }; if converted.iter().flat_map(|path| path.elements()).any(|element| { let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); match *element { @@ -128,6 +132,9 @@ fn estimated_elements(kind: &crate::model::EntityKind) -> usize { polyline_count(&vertices, poly.closed()) } E::Ellipse { start, end, .. } => 1usize.saturating_add(arc_count(end - start)), + // `spline_path` already caps subdivision at MAX_SPLINE_ELEMENTS. Its actual output is + // checked against the drawing-wide budget after conversion. + E::Spline(_) => 0, _ => 0, } } @@ -191,6 +198,278 @@ fn entity_paths(kind: &crate::model::EntityKind, normal: crate::model::Point) -> } } +const MAX_SPLINE_ELEMENTS: usize = 200_000; +const SPLINE_TOLERANCE: f64 = 1e-6; +const MAX_SPLINE_DEPTH: u32 = 12; +const MAX_SPLINE_DEGREE: usize = 11; +const MIN_RELATIVE_WEIGHT: f64 = 1e-100; + +#[derive(Clone, Copy)] +struct Homogeneous { + x: f64, + y: f64, + w: f64, +} + +impl Homogeneous { + fn lerp(self, other: Self, t: f64) -> Self { + let s = 1.0 - t; + Self { x: self.x * s + other.x * t, y: self.y * s + other.y * t, w: self.w * s + other.w * t } + } + fn point(self) -> Option { + (self.w.abs() > 1e-300).then(|| Point::new(self.x / self.w, self.y / self.w)).filter(|point| point.x.is_finite() && point.y.is_finite()) + } +} + +// Keep the NURBS conversion semantics of the previous importer: exact polynomial Bezier +// spans through cubic degree, tolerance-bounded rational/high-degree spans, invalid-weight +// fallback, and fit-point fallback when control data is malformed. +fn spline_path(spline: &crate::model::Spline) -> Result, Error> { + let weights = (spline.flags & 4 != 0 && spline.weights.len() == spline.control.len()).then_some(spline.weights.as_slice()); + let mut limit_hit = false; + let converted = usize::try_from(spline.degree).ok().and_then(|degree| nurbs(degree, &spline.knots, &spline.control, weights, &mut limit_hit)); + let path = converted + .map(|mut path| { + if spline.flags & 1 != 0 { + path.close_path(); + } + path + }) + .or_else(|| { + let closed = spline.flags & 1 != 0; + // `through` emits one move, n-1 (open) or n (closed) cubics, and + // an additional close element for closed paths. Check before allocating + // its converted point vector. + let max_points = MAX_SPLINE_ELEMENTS.saturating_sub(if closed { 2 } else { 0 }); + if spline.fit.len() > max_points { + limit_hit = true; + return None; + } + through(&spline.fit.iter().map(|p| Point::new(p[0], p[1])).collect::>(), closed) + }); + if limit_hit { + return Err(Error::TooManySegments); + } + Ok(path) +} + +fn nurbs(degree: usize, knots: &[f64], control: &[[f64; 3]], weights: Option<&[f64]>, limit_hit: &mut bool) -> Option { + let n = control.len(); + if !(1..=MAX_SPLINE_DEGREE).contains(°ree) + || n <= degree + || knots.len() != n + degree + 1 + || knots.windows(2).any(|w| w[1] < w[0]) + || control.iter().any(|p| !p[0].is_finite() || !p[1].is_finite()) + || knots.iter().any(|k| !k.is_finite()) + { + return None; + } + let raw = |i: usize| weights.and_then(|w| w.get(i)).copied().filter(|w| *w > 0.0 && w.is_finite()).unwrap_or(1.0); + let max_w = (0..n).map(raw).fold(0.0, f64::max); + if max_w == 0.0 { + return None; + } + let weight = |i: usize| (raw(i) / max_w).max(MIN_RELATIVE_WEIGHT); + let rational = (0..n).any(|i| (weight(i) - weight(0)).abs() > 1e-12); + let (lo, hi) = control.iter().fold((Point::new(f64::MAX, f64::MAX), Point::new(f64::MIN, f64::MIN)), |(lo, hi), p| { + (Point::new(lo.x.min(p[0]), lo.y.min(p[1])), Point::new(hi.x.max(p[0]), hi.y.max(p[1]))) + }); + let tolerance = ((hi - lo).hypot() * SPLINE_TOLERANCE).max(1e-12); + let mut path = BezPath::new(); + for span in degree..n { + let (Some(&t0), Some(&t1)) = (knots.get(span), knots.get(span + 1)) else { continue }; + if t1 <= t0 { + continue; + } + let bezier: Vec = (0..=degree) + .map(|j| { + let args: Vec<_> = (0..degree).map(|k| if k < degree - j { t0 } else { t1 }).collect(); + blossom(degree, knots, control, span, &args, &weight) + }) + .collect::>()?; + let start = bezier.first()?.point()?; + let needs_new_subpath = path_endpoint(&path).is_none_or(|end| end.distance(start) > 1e-12 * (1.0 + start.to_vec2().hypot())); + if needs_new_subpath { + path.move_to(start); + } + // A rational degree-one span changes its parameterization with its weights, but its locus + // is still the straight segment between its endpoints. Preserve that exact geometry. + let polynomial: Option> = if rational && degree > 1 { None } else { bezier.iter().map(|p| p.point()).collect() }; + match polynomial.as_deref() { + Some([_, p]) => path.line_to(*p), + Some([_, q, p]) => path.quad_to(*q, *p), + Some([_, a, b, p]) => path.curve_to(*a, *b, *p), + _ => fit_spline(&mut path, &bezier, tolerance, 0, limit_hit)?, + } + if path.elements().len() > MAX_SPLINE_ELEMENTS { + *limit_hit = true; + return None; + } + } + (path.elements().len() > 1).then_some(path) +} + +fn path_endpoint(path: &BezPath) -> Option { + match path.elements().last()? { + kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => Some(*p), + kurbo::PathEl::QuadTo(_, p) => Some(*p), + kurbo::PathEl::CurveTo(_, _, p) => Some(*p), + kurbo::PathEl::ClosePath => None, + } +} + +fn blossom(degree: usize, knots: &[f64], control: &[[f64; 3]], span: usize, args: &[f64], weight: &impl Fn(usize) -> f64) -> Option { + // Only the active degree+1 control points are needed for one span. Convert this small window + // here instead of making a second vector proportional to an untrusted entity's full controls. + let first = span.checked_sub(degree)?; + let mut points: Vec<_> = control + .get(first..=span)? + .iter() + .enumerate() + .map(|(offset, p)| { + let w = weight(first + offset); + Homogeneous { x: p[0] * w, y: p[1] * w, w } + }) + .collect(); + for r in 1..=degree { + let u = *args.get(r - 1)?; + for j in (r..=degree).rev() { + let i = span - degree + j; + let (a, b) = (*knots.get(i)?, *knots.get(i + degree + 1 - r)?); + let alpha = if b - a > 1e-300 { (u - a) / (b - a) } else { 0.0 }; + let previous = *points.get(j - 1)?; + let current = points.get_mut(j)?; + *current = previous.lerp(*current, alpha); + } + } + points.get(degree).copied() +} + +fn eval_spline_bezier(bezier: &[Homogeneous], t: f64) -> Option<(Point, kurbo::Vec2)> { + let mut points = bezier.to_vec(); + let n = points.len().checked_sub(1)?; + for level in (1..=n).rev() { + if level == 1 { + let (a, b) = (*points.first()?, *points.get(1)?); + let p = a.lerp(b, t); + let point = p.point()?; + let k = n as f64; + let (dx, dy, dw) = (k * (b.x - a.x), k * (b.y - a.y), k * (b.w - a.w)); + let w2 = p.w * p.w; + return Some((point, kurbo::Vec2::new((dx * p.w - p.x * dw) / w2, (dy * p.w - p.y * dw) / w2))); + } + for i in 0..level { + let next = *points.get(i + 1)?; + let current = points.get_mut(i)?; + *current = current.lerp(next, t); + } + } + Some((points.first()?.point()?, kurbo::Vec2::ZERO)) +} + +fn fit_spline(path: &mut BezPath, bezier: &[Homogeneous], tolerance: f64, depth: u32, limit_hit: &mut bool) -> Option<()> { + let (p0, d0) = eval_spline_bezier(bezier, 0.0)?; + let (p3, d3) = eval_spline_bezier(bezier, 1.0)?; + let (c1, c2) = (p0 + d0 / 3.0, p3 - d3 / 3.0); + if ![c1, c2].iter().all(|p| p.x.is_finite() && p.y.is_finite()) { + path.line_to(p3); + return Some(()); + } + let candidate = [p0, c1, c2, p3]; + if cubic_error_bound(bezier, &candidate).is_some_and(|error| error <= tolerance) { + if path.elements().len() >= MAX_SPLINE_ELEMENTS { + *limit_hit = true; + return None; + } + path.curve_to(c1, c2, p3); + return Some(()); + } + if depth >= MAX_SPLINE_DEPTH || path.elements().len() >= MAX_SPLINE_ELEMENTS { + *limit_hit = true; + return None; + } + let (left, right) = split_homogeneous_bezier(bezier)?; + fit_spline(path, &left, tolerance, depth + 1, limit_hit)?; + fit_spline(path, &right, tolerance, depth + 1, limit_hit) +} + +fn split_homogeneous_bezier(bezier: &[Homogeneous]) -> Option<(Vec, Vec)> { + let count = bezier.len(); + if count < 2 { + return None; + } + let mut row = bezier.to_vec(); + let mut left = vec![*bezier.first()?; count]; + let mut right = vec![*bezier.last()?; count]; + left[0] = row[0]; + right[count - 1] = row[count - 1]; + for level in 1..count { + for index in 0..count - level { + row[index] = row[index].lerp(row[index + 1], 0.5); + } + left[level] = row[0]; + right[count - 1 - level] = row[count - 1 - level]; + } + Some((left, right)) +} + +// Bound the rational curve/cubic difference over the whole parameter interval. In Bernstein +// form, X(t)-W(t)C(t) has degree p+3, so its norm is bounded by the largest coefficient norm; +// W(t) is a convex combination of positive weights and is at least their minimum. +fn cubic_error_bound(bezier: &[Homogeneous], cubic: &[Point; 4]) -> Option { + let degree = bezier.len().checked_sub(1)?; + let total = degree.checked_add(3)?; + let min_weight = bezier.iter().map(|point| point.w).fold(f64::INFINITY, f64::min); + if !(min_weight > 0.0 && min_weight.is_finite()) { + return None; + } + let mut max_error_numerator: f64 = 0.0; + for k in 0..=total { + let mut x = 0.0; + let mut y = 0.0; + for (i, point) in bezier.iter().enumerate() { + let Some(j) = k.checked_sub(i).filter(|j| *j < 4) else { continue }; + let factor = binomial(degree, i) * binomial(3, j) / binomial(total, k); + x += (point.x - point.w * cubic[j].x) * factor; + y += (point.y - point.w * cubic[j].y) * factor; + } + max_error_numerator = max_error_numerator.max(x.hypot(y)); + } + Some(max_error_numerator / min_weight) +} + +fn binomial(n: usize, k: usize) -> f64 { + if k > n { + return 0.0; + } + let k = k.min(n - k); + (1..=k).fold(1.0, |value, i| value * (n + 1 - i) as f64 / i as f64) +} + +fn through(points: &[Point], closed: bool) -> Option { + let n = points.len(); + let first = *points.first()?; + if n < 2 { + return None; + } + let at = |i: isize| { + let len = n as isize; + let j = if closed { i.rem_euclid(len) } else { i.clamp(0, len - 1) }; + points.get(j as usize).copied().unwrap_or(first) + }; + let mut path = BezPath::new(); + path.move_to(first); + let segments = if closed { n } else { n - 1 }; + for i in 0..segments as isize { + let (p0, p1, p2, p3) = (at(i - 1), at(i), at(i + 1), at(i + 2)); + path.curve_to(p1 + (p2 - p0) / 6.0, p2 - (p3 - p1) / 6.0, p2); + } + if closed { + path.close_path(); + } + Some(path) +} + fn map_ocs_path(path: BezPath, normal: crate::model::Point, z: f64) -> BezPath { let [x, y, n] = crate::model::ocs_axes(normal); let transform = kurbo::Affine::new([x[0], x[1], y[0], y[1], n[0] * z, n[1] * z]); @@ -319,3 +598,262 @@ fn ellipse(center: crate::model::Point, major: crate::model::Point, normal: crat fn cross(a: crate::model::Point, b: crate::model::Point) -> crate::model::Point { [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] } + +#[cfg(test)] +mod spline_tests { + use super::*; + use crate::model::Spline; + use kurbo::ParamCurveNearest; + + // The previous importer accepted cubic fits based on seven fixed probes, then bisected the + // parameter interval. Keep this test-only reference to compare real legacy output with the + // conservative fit used by craft-dxf. + fn prior_fit(path: &mut BezPath, bezier: &[Homogeneous], t0: f64, t1: f64, tolerance: f64, depth: u32) -> Option<()> { + let (p0, d0) = eval_spline_bezier(bezier, t0)?; + let (p3, d3) = eval_spline_bezier(bezier, t1)?; + let h = (t1 - t0) / 3.0; + let (c1, c2) = (p0 + d0 * h, p3 - d3 * h); + if ![c1, c2].iter().all(|point| point.x.is_finite() && point.y.is_finite()) { + path.line_to(p3); + return Some(()); + } + let cubic = kurbo::CubicBez::new(p0, c1, c2, p3); + let close = (1..8).all(|i| { + let t = f64::from(i) / 8.0; + eval_spline_bezier(bezier, t0 + (t1 - t0) * t).is_some_and(|(point, _)| kurbo::ParamCurve::eval(&cubic, t).distance(point) <= tolerance) + }); + if close || depth >= MAX_SPLINE_DEPTH || path.elements().len() >= MAX_SPLINE_ELEMENTS { + path.curve_to(c1, c2, p3); + return Some(()); + } + let midpoint = (t0 + t1) / 2.0; + prior_fit(path, bezier, t0, midpoint, tolerance, depth + 1)?; + prior_fit(path, bezier, midpoint, t1, tolerance, depth + 1) + } + + fn legacy_path(bezier: &[Homogeneous], tolerance: f64) -> BezPath { + let mut path = BezPath::new(); + let start = eval_spline_bezier(bezier, 0.0).expect("legacy start point").0; + path.move_to(start); + prior_fit(&mut path, bezier, 0.0, 1.0, tolerance, 0).expect("legacy fit succeeds"); + path + } + + fn sampled_path_distance(from: &BezPath, to: &BezPath, tolerance: f64) -> f64 { + let target: Vec<_> = to.segments().collect(); + from.segments() + .flat_map(|segment| (0..=32).map(move |i| kurbo::ParamCurve::eval(&segment, f64::from(i) / 32.0))) + .map(|point| target.iter().map(|segment| segment.nearest(point, tolerance / 100.0).distance_sq.sqrt()).fold(f64::INFINITY, f64::min)) + .fold(0.0_f64, f64::max) + } + + fn cubic() -> Spline { + Spline { + degree: 3, + flags: 8, + knots: vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + control: vec![[0.0, 0.0, 0.0], [1.0, 2.0, 0.0], [2.0, 2.0, 0.0], [3.0, 0.0, 0.0]], + weights: Vec::new(), + fit: Vec::new(), + start_tangent: None, + end_tangent: None, + fit_tolerance: 0.0, + } + } + + fn xyz(points: &[Point]) -> Vec<[f64; 3]> { + points.iter().map(|point| [point.x, point.y, 0.0]).collect() + } + + #[test] + fn spline_path_follows_clamped_control_curve_and_bounds_work() { + let path = spline_path(&cubic()).unwrap().expect("valid cubic spline"); + assert_eq!(path.elements().len(), 2); + assert!(matches!(path.elements()[0], kurbo::PathEl::MoveTo(p) if p == Point::new(0.0, 0.0))); + assert!(matches!(path.elements()[1], kurbo::PathEl::CurveTo(a, b, p) + if a == Point::new(1.0, 2.0) && b == Point::new(2.0, 2.0) && p == Point::new(3.0, 0.0))); + assert_eq!(estimated_elements(&crate::model::EntityKind::Spline(cubic())), 0); + } + + #[test] + fn rational_closed_periodic_and_fit_point_splines_keep_compatibility() { + let mut rational_line = Spline { + degree: 1, + flags: 4, + knots: vec![0.0, 0.0, 1.0, 1.0], + control: vec![[2.0, 3.0, 0.0], [5.0, 7.0, 0.0]], + weights: vec![1.0, 100.0], + fit: Vec::new(), + start_tangent: None, + end_tangent: None, + fit_tolerance: 0.0, + }; + rational_line.flags |= 8; + let line = spline_path(&rational_line).unwrap().expect("rational degree-one spline"); + assert!(matches!(line.elements(), [kurbo::PathEl::MoveTo(a), kurbo::PathEl::LineTo(b)] + if *a == Point::new(2.0, 3.0) && *b == Point::new(5.0, 7.0))); + + let mut rational = cubic(); + rational.flags |= 4; + rational.weights = vec![1.0, 0.5, 0.5, 1.0]; + let rational_path = spline_path(&rational).unwrap().expect("rational spline"); + assert!(rational_path.elements().iter().any(|el| matches!(el, kurbo::PathEl::CurveTo(..)))); + + let mut closed = cubic(); + closed.flags |= 1; + assert!(matches!(spline_path(&closed).unwrap().unwrap().elements().last(), Some(kurbo::PathEl::ClosePath))); + let mut periodic = cubic(); + periodic.flags |= 2; + assert!(!matches!(spline_path(&periodic).unwrap().unwrap().elements().last(), Some(kurbo::PathEl::ClosePath))); + + let mut fit = cubic(); + fit.knots.clear(); + fit.fit = vec![[0.0, 0.0, 0.0], [1.0, 2.0, 0.0], [3.0, 0.0, 0.0]]; + let path = spline_path(&fit).unwrap().expect("fit-point fallback"); + assert!(matches!(path.elements()[0], kurbo::PathEl::MoveTo(p) if p == Point::new(0.0,0.0))); + assert!(matches!(path.elements().last(), Some(kurbo::PathEl::CurveTo(_, _, p)) if *p == Point::new(3.0,0.0))); + + let mut negative = cubic(); + negative.degree = -1; + negative.fit = fit.fit; + assert!(spline_path(&negative).unwrap().is_some(), "invalid degree reaches the prior fit-point fallback"); + } + + #[test] + fn spline_path_rejects_malformed_knots_and_defaults_invalid_weights() { + let mut spline = cubic(); + spline.knots[4] = f64::NAN; + assert!(spline_path(&spline).unwrap().is_none()); + let mut spline = cubic(); + spline.flags |= 4; + spline.weights = vec![1.0, 0.0, 1.0, 1.0]; + assert!(spline_path(&spline).unwrap().is_some(), "invalid weights historically fall back to unit weights"); + } + + #[test] + fn ascii_document_import_keeps_spline_as_supported_geometry() { + let bytes = b"0\nSECTION\n2\nENTITIES\n0\nSPLINE\n8\n0\n70\n8\n71\n3\n72\n8\n73\n4\n40\n0\n40\n0\n40\n0\n40\n0\n40\n1\n40\n1\n40\n1\n40\n1\n10\n0\n20\n0\n10\n1\n20\n2\n10\n2\n20\n2\n10\n3\n20\n0\n0\nENDSEC\n0\nEOF\n"; + let imported = import(bytes).expect("valid spline drawing"); + assert_eq!(imported.paths.len(), 1); + assert!(imported.warnings.is_empty()); + let bounds = imported.bounds.expect("spline bounds"); + assert!((bounds.x0 - 0.0).abs() < 1e-12 && (bounds.x1 - 3.0).abs() < 1e-12); + assert!((bounds.y0 - 0.0).abs() < 1e-12 && (bounds.y1 - 1.5).abs() < 1e-12); + } + + #[test] + fn discontinuous_nurbs_spans_remain_separate_subpaths() { + let mut limit_hit = false; + let path = nurbs( + 1, + &[0.0, 0.0, 0.5, 0.5, 1.0, 1.0], + &xyz(&[Point::new(0.0, 0.0), Point::new(1.0, 0.0), Point::new(5.0, 5.0), Point::new(6.0, 5.0)]), + None, + &mut limit_hit, + ) + .expect("piecewise linear spline"); + assert!(!limit_hit); + assert!(matches!(path.elements(), [kurbo::PathEl::MoveTo(a), kurbo::PathEl::LineTo(b), kurbo::PathEl::MoveTo(c), kurbo::PathEl::LineTo(d)] + if *a == Point::new(0.0,0.0) && *b == Point::new(1.0,0.0) && *c == Point::new(5.0,5.0) && *d == Point::new(6.0,5.0))); + } + + #[test] + fn positive_knot_spans_at_large_offsets_are_kept() { + let start = 1.0e12; + let delta = 1.0e-3; + let mut limit_hit = false; + let path = nurbs(1, &[start, start, start + delta, start + delta], &xyz(&[Point::new(2.0, 3.0), Point::new(5.0, 7.0)]), None, &mut limit_hit) + .expect("positive-width span"); + assert!(!limit_hit); + assert!(matches!(path.elements(), [kurbo::PathEl::MoveTo(a), kurbo::PathEl::LineTo(b)] + if *a == Point::new(2.0, 3.0) && *b == Point::new(5.0, 7.0))); + } + + #[test] + fn fit_point_fallback_checks_element_budget_before_collecting() { + let mut spline = cubic(); + spline.degree = -1; + spline.fit = vec![[0.0, 0.0, 0.0]; MAX_SPLINE_ELEMENTS + 1]; + assert!(matches!(spline_path(&spline), Err(Error::TooManySegments))); + } + + #[test] + fn bernstein_error_bound_covers_rational_and_high_degree_deviations() { + for control in [ + vec![Homogeneous { x: 0.0, y: 0.0, w: 1.0 }, Homogeneous { x: 0.2, y: 2.0, w: 0.5 }, Homogeneous { x: 1.0, y: 0.0, w: 1.0 }], + vec![ + Homogeneous { x: 0.0, y: 0.0, w: 1.0 }, + Homogeneous { x: 0.2, y: 2.0, w: 0.7 }, + Homogeneous { x: 0.5, y: -2.0, w: 0.9 }, + Homogeneous { x: 0.8, y: 2.0, w: 1.2 }, + Homogeneous { x: 1.0, y: 0.0, w: 1.0 }, + ], + ] { + let degree = control.len() - 1; + let bezier = [Point::new(0.0, 0.0), Point::new(0.25, 1.0), Point::new(0.75, 1.0), Point::new(1.0, 0.0)]; + let bound = cubic_error_bound(&control, &bezier).unwrap(); + let cubic = kurbo::CubicBez::new(bezier[0], bezier[1], bezier[2], bezier[3]); + for sample in 0..=1024 { + let t = sample as f64 / 1024.0; + let mut points = control.clone(); + for level in (1..=degree).rev() { + for i in 0..level { + points[i] = points[i].lerp(points[i + 1], t); + } + } + let source = points[0].point().unwrap(); + let approximation = kurbo::ParamCurve::eval(&cubic, t); + assert!(source.distance(approximation) <= bound * (1.0 + 1e-12), "sample {t}: bound {bound}"); + } + } + } + + #[test] + fn rational_quadratic_circle_matches_the_prior_importer_tolerance() { + let weight = std::f64::consts::FRAC_1_SQRT_2; + let control = xyz(&[(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0), (-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (1.0, 0.0)] + .map(|(x, y)| Point::new(200.0 + x * 100.0, 200.0 + y * 100.0))); + let knots = [0.0, 0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 4.0]; + let weights = [1.0, weight, 1.0, weight, 1.0, weight, 1.0, weight, 1.0]; + let mut limit_hit = false; + let path = nurbs(2, &knots, &control, Some(&weights), &mut limit_hit).expect("circle NURBS"); + assert!(!limit_hit); + let center = Point::new(200.0, 200.0); + let max_radial_error = path + .segments() + .flat_map(|segment| (0..=32).map(move |i| kurbo::ParamCurve::eval(&segment, i as f64 / 32.0))) + .map(|point| (point.distance(center) - 100.0).abs()) + .fold(0.0_f64, f64::max); + assert!(max_radial_error < 0.01, "prior importer tolerance was 0.01; got {max_radial_error}"); + } + + #[test] + fn bounded_spline_fit_matches_prior_rational_and_high_degree_geometry() { + let weight = std::f64::consts::FRAC_1_SQRT_2; + let curves = [ + vec![Homogeneous { x: 1.0, y: 0.0, w: 1.0 }, Homogeneous { x: weight, y: weight, w: weight }, Homogeneous { x: 0.0, y: 1.0, w: 1.0 }], + vec![ + Homogeneous { x: 0.0, y: 0.0, w: 1.0 }, + Homogeneous { x: 0.2, y: 2.0, w: 0.7 }, + Homogeneous { x: 0.5, y: -2.0, w: 0.9 }, + Homogeneous { x: 0.8, y: 2.0, w: 1.2 }, + Homogeneous { x: 1.0, y: 0.0, w: 1.0 }, + ], + ]; + for bezier in curves { + let points: Vec<_> = bezier.iter().map(|point| point.point().expect("finite source point")).collect(); + let (lo, hi) = points.iter().fold((points[0], points[0]), |(lo, hi), point| { + (Point::new(lo.x.min(point.x), lo.y.min(point.y)), Point::new(hi.x.max(point.x), hi.y.max(point.y))) + }); + let tolerance = ((hi - lo).hypot() * SPLINE_TOLERANCE).max(1e-12); + let mut current = BezPath::new(); + current.move_to(points[0]); + let mut limit_hit = false; + fit_spline(&mut current, &bezier, tolerance, 0, &mut limit_hit).expect("bounded fit succeeds"); + assert!(!limit_hit); + let prior = legacy_path(&bezier, tolerance); + let difference = sampled_path_distance(&prior, ¤t, tolerance).max(sampled_path_distance(¤t, &prior, tolerance)); + assert!(difference <= 2.1 * tolerance, "legacy/new Hausdorff sample distance {difference} exceeds 2.1 × tolerance {tolerance}"); + } + } +} diff --git a/crates/eps/README.md b/crates/eps/README.md index f2abd0b2c..25c8a7eda 100644 --- a/crates/eps/README.md +++ b/crates/eps/README.md @@ -8,8 +8,10 @@ nothing. |---|---| | `sniff`, `is_eps` | EPS (binary header, or `%!PS-Adobe-… EPSF-…`), plain PostScript or PDF, and whether it is an Illustrator file: PostScript-based (`%AI…` comments, or Illustrator as `%%Creator`) or PDF-based (the `AIPrivateData` / `AIPDFPrivateData` keys near the start or end of the PDF, a hint only) | | `sections` | The parts behind the binary header ("DOS EPS"): the PostScript, the TIFF preview, the Windows metafile preview. A header that points outside the file is an error | +| `postscript_section` | The PostScript program alone; a damaged preview does not prevent a reader from using a valid program section | | `wrap` | PostScript and its previews behind a binary header, as `sections` reads them back | | `Comments::read` | `%%BoundingBox` and `%%HiResBoundingBox` (the first in the header; `(atend)` taken from the trailer, outside embedded documents), `%%Pages`, `%%LanguageLevel`, `%%Creator`, `%%Title` | +| `Comments::read_with_header_limit` | The same comments with a caller-selected header scan limit capped at 256 KiB; `read` defaults to 64 KiB | | `epsi` | The device-independent preview (`%%BeginPreview`, 1, 2, 4 or 8 bits) as an 8-bit grey bitmap | | `ascii85::encode`, `ascii85::decode` | The ASCII85 data encoding; lines never start with `%`, decoding is bounded | diff --git a/crates/eps/src/container.rs b/crates/eps/src/container.rs index ba721f5c2..245252b83 100644 --- a/crates/eps/src/container.rs +++ b/crates/eps/src/container.rs @@ -27,6 +27,27 @@ pub struct Sections<'a> { pub metafile: Option<&'a [u8]>, } +fn word(bytes: &[u8], at: usize) -> Result { + let end = at.checked_add(4).ok_or(Error::OutsideFile)?; + let b = bytes.get(at..end).and_then(|b| <[u8; 4]>::try_from(b).ok()).ok_or(Error::OutsideFile)?; + usize::try_from(u32::from_le_bytes(b)).map_err(|_| Error::OutsideFile) +} + +fn part(bytes: &[u8], at: usize) -> Result<&[u8], Error> { + let len_at = at.checked_add(4).ok_or(Error::OutsideFile)?; + let (start, len) = (word(bytes, at)?, word(bytes, len_at)?); + start.checked_add(len).and_then(|end| bytes.get(start..end)).ok_or(Error::OutsideFile) +} + +/// The PostScript program in an EPS, ignoring preview ranges in its binary header. +/// +/// This is useful to readers that execute only PostScript and historically accepted a valid +/// program section even when a separate preview range was damaged. Use [`sections`] when every +/// declared section must be validated. +pub fn postscript_section(bytes: &[u8]) -> Result<&[u8], Error> { + if bytes.starts_with(&DOS_MAGIC) { part(bytes, 4) } else { Ok(bytes) } +} + /// The sections of an EPS file: its PostScript and previews behind a binary header, or the whole /// file as PostScript. A header that points outside the file is an error, whichever section it /// is: such a file is cut short or not an EPS. @@ -34,17 +55,12 @@ pub fn sections(bytes: &[u8]) -> Result, Error> { if !bytes.starts_with(&DOS_MAGIC) { return Ok(Sections { postscript: bytes, tiff: None, metafile: None }); } - let word = |at: usize| -> Result { - let b = bytes.get(at..at.saturating_add(4)).and_then(|b| <[u8; 4]>::try_from(b).ok()).ok_or(Error::OutsideFile)?; - usize::try_from(u32::from_le_bytes(b)).map_err(|_| Error::OutsideFile) - }; - let part = |at: usize| -> Result<&[u8], Error> { - let (start, len) = (word(at)?, word(at + 4)?); - start.checked_add(len).and_then(|end| bytes.get(start..end)).ok_or(Error::OutsideFile) - }; // A preview with no offset or no length is absent. - let preview = |at: usize| -> Result, Error> { if word(at)? == 0 || word(at + 4)? == 0 { Ok(None) } else { part(at).map(Some) } }; - Ok(Sections { postscript: part(4)?, metafile: preview(12)?, tiff: preview(20)? }) + let preview = |at: usize| -> Result, Error> { + let len_at = at.checked_add(4).ok_or(Error::OutsideFile)?; + if word(bytes, at)? == 0 || word(bytes, len_at)? == 0 { Ok(None) } else { part(bytes, at).map(Some) } + }; + Ok(Sections { postscript: postscript_section(bytes)?, metafile: preview(12)?, tiff: preview(20)? }) } /// `postscript` behind a binary header, followed by its previews. With neither preview the diff --git a/crates/eps/src/dsc.rs b/crates/eps/src/dsc.rs index 835f9b23f..2334e1d90 100644 --- a/crates/eps/src/dsc.rs +++ b/crates/eps/src/dsc.rs @@ -2,6 +2,8 @@ /// Bytes of a file's start read for its header comments. pub const MAX_HEADER: usize = 64 << 10; +/// Largest header scan available for readers preserving a wider historical bound. +pub const MAX_EXTENDED_HEADER: usize = 256 << 10; /// Bytes of a file's end read for comments its header defers there with `(atend)`. pub const MAX_TRAILER: usize = 64 << 10; @@ -34,7 +36,17 @@ impl Comments { /// A bounding box the header defers with `(atend)` is the last one of the trailer, outside /// any document the file embeds. pub fn read(ps: &[u8]) -> Self { - let head = String::from_utf8_lossy(ps.get(..MAX_HEADER).unwrap_or(ps)); + Self::read_with_header_limit(ps, MAX_HEADER) + } + + /// Read comments with a caller-selected scan limit for the header. + /// + /// The limit is capped at [`MAX_EXTENDED_HEADER`], and the trailer remains capped at + /// [`MAX_TRAILER`]. This lets readers preserve a previously supported wider scan without + /// making header or trailer work unbounded. + pub fn read_with_header_limit(ps: &[u8], header_limit: usize) -> Self { + let header_limit = header_limit.min(MAX_EXTENDED_HEADER).min(ps.len()); + let head = String::from_utf8_lossy(&ps[..header_limit]); let mut c = Comments::default(); let (mut box_atend, mut hires_atend) = (false, false); // Lines may end in `\r` alone (classic Mac files). diff --git a/crates/eps/src/embedded.rs b/crates/eps/src/embedded.rs new file mode 100644 index 000000000..8e2225993 --- /dev/null +++ b/crates/eps/src/embedded.rs @@ -0,0 +1,269 @@ +//! Embedded Type 1 and CFF font programs in PostScript / EPS source. + +/// A font program embedded in the PostScript source of an EPS file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EmbeddedFontProgram { + /// The PostScript `/FontName` when one is present in the source. CFF `StartData` blocks store + /// their name inside the CFF Name INDEX, which the font parser reads from `program`. + pub name: Option, + /// The bytes of the Type 1 program or CFF font set. + pub program: Vec, + /// Whether `program` is a CFF font set rather than a Type 1 program. + pub cff: bool, +} + +/// Embedded font programs in a PostScript section, in source order within each format. +/// +/// Type 1 programs are recognized from their `eexec` and `cleartomark` delimiters and are named +/// by `/FontName`. CFF `StartData` blocks are returned without a name because the name is inside +/// the binary CFF data. Malformed or truncated blocks are skipped, as in the original EPS reader. +pub fn embedded_font_programs(ps: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut heads = positions(ps, b"%!PS-AdobeFont"); + heads.extend(positions(ps, b"%!FontType1")); + heads.sort_unstable(); + let names = positions(ps, b"/FontName"); + let mut from = 0; + let mut used = 0; + while let Some(ee) = find_eexec(ps, from) { + from = ee + 5; + let last_before = |v: &[usize]| v[..v.partition_point(|&p| p < ee)].last().copied().filter(|&p| p >= used); + // The fallback look-back stops at the previous font's end, so it cannot pick up its header. + let start = last_before(&heads).or_else(|| last_before(&names).map(|p| p.saturating_sub(512).max(used))); + let Some(start) = start else { continue }; + let end = find_from(ps, b"cleartomark", ee).map_or(ps.len(), |p| p + 11); + if let Some(name) = name_after(&ps[start..ee], b"/FontName") { + out.push(EmbeddedFontProgram { name: Some(name), program: ps[start..end].to_vec(), cff: false }); + } + from = end; + used = end; + } + + let mut from = 0; + while let Some(sd) = find_from(ps, b"StartData", from) { + from = sd + 9; + let head = String::from_utf8_lossy(&ps[sd.saturating_sub(64)..sd]).into_owned(); + let Some(len) = head.split_whitespace().last().and_then(|t| t.parse::().ok()) else { continue }; + let s = sd + 10; + let Some(data) = ps.get(s..s.saturating_add(len)) else { continue }; + out.push(EmbeddedFontProgram { name: None, program: data.to_vec(), cff: true }); + from = s + len; + } + out +} + +fn find_from(hay: &[u8], needle: &[u8], from: usize) -> Option { + hay.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|p| p + from) +} + +/// Find an executable `eexec` operator, ignoring comments, literal strings and names. +fn find_eexec(ps: &[u8], from: usize) -> Option { + let mut pos = from.min(ps.len()); + while pos < ps.len() { + let c = ps[pos]; + if is_white(c) { + pos += 1; + continue; + } + if c == b'%' { + let start = pos; + while pos < ps.len() && !matches!(ps[pos], b'\n' | b'\r') { + pos += 1; + } + let line = &ps[start..pos]; + let marker: Option<&[u8]> = if line.starts_with(b"%%BeginData:") { + Some(b"%%EndData") + } else if line.starts_with(b"%%BeginBinary:") { + Some(b"%%EndBinary") + } else if line.starts_with(b"%%BeginPreview") { + Some(b"%%EndPreview") + } else { + None + }; + if let Some(marker) = marker { + let rest = ps.get(pos..)?; + pos = rest.windows(marker.len()).position(|window| window == marker).map_or(ps.len(), |offset| pos + offset); + } + continue; + } + if c == b'(' { + pos += 1; + let mut depth = 1usize; + while pos < ps.len() && depth > 0 { + match ps[pos] { + b'\\' => pos = pos.saturating_add(2).min(ps.len()), + b'(' => { + depth = depth.saturating_add(1); + pos += 1; + } + b')' => { + depth -= 1; + pos += 1; + } + _ => pos += 1, + } + } + continue; + } + if c == b'<' { + match ps.get(pos + 1) { + Some(b'<') => pos += 2, + Some(b'~') => { + pos += 2; + pos = ps + .get(pos..) + .and_then(|rest| { + rest.windows(2).position(|window| window == b"~>").map(|offset| pos.saturating_add(offset).saturating_add(2)) + }) + .unwrap_or(ps.len()); + } + _ => { + pos += 1; + while pos < ps.len() && ps[pos] != b'>' { + pos += 1; + } + pos = pos.saturating_add(1).min(ps.len()); + } + } + continue; + } + if c == b'/' { + pos += 1; + if ps.get(pos) == Some(&b'/') { + pos += 1; + } + while pos < ps.len() && !is_white(ps[pos]) && !is_delimiter(ps[pos]) { + pos += 1; + } + continue; + } + if is_delimiter(c) { + pos += 1; + continue; + } + let start = pos; + while pos < ps.len() && !is_white(ps[pos]) && !is_delimiter(ps[pos]) { + pos += 1; + } + if &ps[start..pos] == b"eexec" { + return Some(start); + } + } + None +} + +fn is_white(c: u8) -> bool { + matches!(c, 0 | 9 | 10 | 12 | 13 | 32) +} + +fn is_delimiter(c: u8) -> bool { + matches!(c, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') +} + +fn positions(hay: &[u8], needle: &[u8]) -> Vec { + let mut out = vec![]; + let mut from = 0; + while let Some(p) = find_from(hay, needle, from) { + out.push(p); + from = p + needle.len(); + } + out +} + +fn name_after(b: &[u8], key: &[u8]) -> Option { + let p = find_from(b, key, 0)? + key.len(); + let rest = &b[p..]; + let s = rest.iter().position(|c| *c == b'/')? + 1; + let e = rest[s..].iter().position(|c| is_white(*c) || is_delimiter(*c)).map_or(rest.len(), |q| s + q); + (e > s).then(|| String::from_utf8_lossy(&rest[s..e]).into_owned()) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::embedded_font_programs; + + #[test] + fn finds_type1_font_programs_by_name() { + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%!PS-AdobeFont-1.0: Test\n/FontName /Test def\ncurrentfile eexec\n0000\ncleartomark\n"; + let fonts = embedded_font_programs(ps); + assert_eq!(fonts.len(), 1); + assert_eq!(fonts[0].name.as_deref(), Some("Test")); + assert!(!fonts[0].cff); + assert!(String::from_utf8_lossy(&fonts[0].program).contains("cleartomark")); + } + + #[test] + fn finds_cff_startdata_without_interpreting_its_name_index() { + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n10 StartData\n0123456789\n"; + let fonts = embedded_font_programs(ps); + assert_eq!(fonts.len(), 1); + assert_eq!(fonts[0].name, None); + assert!(fonts[0].cff); + assert_eq!(fonts[0].program, b"0123456789"); + } + + #[test] + fn ignores_truncated_startdata() { + let fonts = embedded_font_programs(b"%!PS-Adobe-3.0 EPSF-3.0\n100 StartData\nshort"); + assert!(fonts.is_empty()); + } + + #[test] + fn many_headerless_eexec_words_do_not_hide_later_font() { + let mut ps = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); + ps.extend_from_slice(b"eexec ".repeat(20_000).as_slice()); + ps.extend_from_slice(b"\n%!PS-AdobeFont-1.0: Real\n/FontName /Real def\ncurrentfile eexec\n0000\ncleartomark\n"); + let fonts = embedded_font_programs(&ps); + assert_eq!(fonts.len(), 1); + assert_eq!(fonts[0].name.as_deref(), Some("Real")); + } + + #[test] + fn headerless_font_does_not_reuse_previous_font_header() { + let first = b"%!PS-AdobeFont-1.0: A\n/FontName /A def\ncurrentfile eexec\n0000\ncleartomark\n"; + let second = b"/FontName /B def\ncurrentfile eexec\n0000\ncleartomark\n"; + let mut ps = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); + ps.extend_from_slice(first); + ps.extend_from_slice(second); + let fonts = embedded_font_programs(&ps); + assert_eq!(fonts.len(), 2); + let b = fonts.iter().find(|font| font.name.as_deref() == Some("B")).unwrap(); + assert!(!String::from_utf8_lossy(&b.program).contains("AdobeFont")); + } + + #[test] + fn eexec_in_comments_strings_names_and_font_names_is_not_an_operator() { + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%!PS-AdobeFont-1.0: Test\n%% eexec in a comment\n%%BeginBinary: 10\neexec junk\n%%EndBinary\n/FontName /eexecTest def\n(nested (ignored eexec)) pop\n<6565786563> pop\n<~eexec~> pop\n/eexec def\ncurrentfile eexec\n0000\ncleartomark\n"; + let fonts = embedded_font_programs(ps); + assert_eq!(fonts.len(), 1); + assert_eq!(fonts[0].name.as_deref(), Some("eexecTest")); + } + + #[test] + fn font_name_stops_at_postscript_delimiters_and_comments() { + let ps = b"%!PS-AdobeFont-1.0: Test\n/FontName /Test%comment\n def\ncurrentfile eexec\n0000\ncleartomark\n"; + let fonts = embedded_font_programs(ps); + assert_eq!(fonts.len(), 1); + assert_eq!(fonts[0].name.as_deref(), Some("Test")); + } + + #[test] + fn font_names_stop_at_every_postscript_delimiter() { + for delimiter in b"()<>[]{}/%" { + let mut source = b"/FontName /Test".to_vec(); + source.push(*delimiter); + source.extend_from_slice(b"ignored"); + assert_eq!(super::name_after(&source, b"/FontName").as_deref(), Some("Test")); + } + } + + #[test] + fn literal_name_backslash_does_not_escape_a_comment_delimiter() { + let ps = b"%!PS-AdobeFont-1.0: Test\n/FontName /Test def\n/unused\\%(\npop\ncurrentfile eexec\n0000\ncleartomark\n"; + let fonts = embedded_font_programs(ps); + assert_eq!(fonts.len(), 1); + assert_eq!(fonts[0].name.as_deref(), Some("Test")); + } +} diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index e7a8cee01..c9a2574f5 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -18,13 +18,16 @@ pub mod ascii85; mod container; mod dsc; +mod embedded; #[cfg(feature = "paths")] pub mod paths; +pub mod postscript; mod preview; mod rectangles; -pub use container::{DOS_HEADER, DOS_MAGIC, Sections, sections, wrap}; -pub use dsc::{Comments, MAX_HEADER, MAX_TRAILER}; +pub use container::{DOS_HEADER, DOS_MAGIC, Sections, postscript_section, sections, wrap}; +pub use dsc::{Comments, MAX_EXTENDED_HEADER, MAX_HEADER, MAX_TRAILER}; +pub use embedded::{EmbeddedFontProgram, embedded_font_programs}; pub use preview::{Bitmap, MAX_EPSI, epsi}; pub use rectangles::{MAX_SIMPLE_RECTANGLE_SAVE_DEPTH, MAX_SIMPLE_RECTANGLE_TOKENS, MAX_SIMPLE_RECTANGLES, Rectangle, simple_rectangles}; diff --git a/crates/eps/src/paths.rs b/crates/eps/src/paths.rs index e77b90b60..271f905bd 100644 --- a/crates/eps/src/paths.rs +++ b/crates/eps/src/paths.rs @@ -47,12 +47,16 @@ pub fn import(bytes: &[u8], limits: Limits) -> Result { } let source = vectorcraft_eps::import(bytes).map_err(Error::Parse)?; let page_bounds = vectorcraft_eps::page(bytes).map_err(Error::Parse)?; + // Illustrator's editable copy is expressed in its art-box document coordinates. The page + // reader, in contrast, returns a page at the origin. Normalize extracted paths to match it. + let origin = source.document.artboards.first().map(|board| board.rect.origin()).unwrap_or_default(); + let to_page = kurbo::Affine::translate((-origin.x, -origin.y)); let mut paths = Vec::new(); let mut total_elements = 0usize; let mut clipped = false; let mut omitted = false; for layer in &source.document.layers { - collect(layer, &mut paths, &mut total_elements, limits, &mut clipped, &mut omitted)?; + collect(layer, &mut paths, &mut total_elements, limits, to_page, &mut clipped, &mut omitted)?; } let mut warnings = source.warnings; if clipped { @@ -69,6 +73,7 @@ fn collect( paths: &mut Vec, elements: &mut usize, limits: Limits, + to_page: kurbo::Affine, clipped: &mut bool, omitted: &mut bool, ) -> Result<(), Error> { @@ -85,7 +90,7 @@ fn collect( if paths.len() >= limits.max_paths || *elements > limits.max_path_elements { return Err(Error::OutputLimit); } - paths.push(path); + paths.push(to_page * path); } } else if let Some(children) = node.children() { let is_clip = matches!(node.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. } | vectorcraft_doc::NodeKind::Layer { clip: true, .. }); @@ -94,7 +99,7 @@ fn collect( if is_clip && index == 0 { continue; } - collect(child, paths, elements, limits, clipped, omitted)?; + collect(child, paths, elements, limits, to_page, clipped, omitted)?; } } else { *omitted = true; diff --git a/crates/eps/src/postscript.rs b/crates/eps/src/postscript.rs new file mode 100644 index 000000000..3261b3193 --- /dev/null +++ b/crates/eps/src/postscript.rs @@ -0,0 +1,873 @@ +//! Shared PostScript format primitives for EPS programs. +//! +//! [`Scanner`] handles bounded lexical parsing. [`OperandStack`], [`ExecutionBudget`], and +//! [`NumericOperator`] provide reusable language-level VM behavior while leaving values, +//! dictionaries, graphics state, rendering, and font policy to the host interpreter. + +/// Maximum nesting depth for executable procedures in a source token. +pub const MAX_PROCEDURE_DEPTH: usize = 100; + +/// Maximum number of operand values an interpreter should retain by default. +pub const MAX_OPERAND_STACK: usize = 100_000; + +/// Maximum nested executable procedure calls supported by the bounded VM. +pub const MAX_CALL_DEPTH: usize = 256; + +/// PostScript operand-stack operators whose semantics do not depend on the value model. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StackOperator { + Pop, + Exchange, + Duplicate, + CopyTop(usize), + Index(usize), + Roll { count: usize, shift: i64 }, + Clear, + Count, +} + +/// Result of applying an operand-stack operator. +#[derive(Debug, PartialEq, Eq)] +pub enum StackOutcome { + None, + Popped(Option), + Count(usize), + Copied(bool), +} + +/// A bounded PostScript operand stack. +/// +/// The stack is deliberately generic: an interpreter owns the concrete PostScript values and +/// graphics state, while this module provides the shared language-level stack operators. A push +/// past `limit` is ignored, matching the bounded EPS interpreter's defensive behavior. +#[derive(Clone, Debug)] +pub struct OperandStack { + values: Vec, + limit: usize, +} + +impl OperandStack { + /// Create an empty stack with a maximum number of values. + pub fn new(limit: usize) -> Self { + Self { values: Vec::new(), limit } + } + + /// Number of values currently on the stack. + pub fn len(&self) -> usize { + self.values.len() + } + + /// Whether the stack is empty. + pub fn is_empty(&self) -> bool { + self.values.is_empty() + } + + /// Borrow all stack values mutably from bottom to top. + pub fn values_mut(&mut self) -> &mut [T] { + &mut self.values + } + + /// Remove and return the top value, if present. + pub fn pop(&mut self) -> Option { + self.values.pop() + } + + /// Remove every value. + pub fn clear(&mut self) { + self.values.clear(); + } + + /// Remove values at and above `at`, returning them in bottom-to-top order. An index beyond + /// the stack length removes nothing. + pub fn split_off(&mut self, at: usize) -> Vec { + let at = at.min(self.values.len()); + self.values.split_off(at) + } + + /// Push a value if the configured limit allows it; report whether it was pushed. + pub fn push(&mut self, value: T) -> bool { + if self.values.len() >= self.limit { + return false; + } + self.values.push(value); + true + } + + /// Pop a value, or return the caller's language-specific underflow value. + pub fn pop_or(&mut self, underflow: T) -> T { + self.values.pop().unwrap_or(underflow) + } + + /// Borrow the top value. + pub fn top(&self) -> Option<&T> { + self.values.last() + } + + /// PostScript `dup`: duplicate the top value if one exists. + pub fn duplicate(&mut self) { + if let Some(value) = self.values.last().cloned() { + let _ = self.push(value); + } + } + + /// PostScript `dup` with a caller-supplied underflow value. + pub fn duplicate_or(&mut self, underflow: T) { + let value = self.values.last().cloned().unwrap_or(underflow); + let _ = self.push(value); + } + + /// PostScript `exch`: exchange the top two values when both exist. + pub fn exchange(&mut self) { + let len = self.values.len(); + if len >= 2 { + self.values.swap(len - 1, len - 2); + } + } + + /// PostScript `exch` with caller-supplied underflow values. Both operands are popped and + /// restored even if either pop underflows, matching interpreters that use a null sentinel. + pub fn exchange_or(&mut self, underflow: T) { + let b = self.pop_or(underflow.clone()); + let a = self.pop_or(underflow); + let _ = self.push(b); + let _ = self.push(a); + } + + /// PostScript `index`: copy the value `depth` below the top onto the stack. + /// + /// Invalid or negative depths are left to the caller to validate; an out-of-range depth is a + /// no-op. This keeps the helper bounded even for hostile numeric operands. + pub fn index(&mut self, depth: usize) { + let len = self.values.len(); + if depth < len && len < self.limit { + let value = self.values[len - depth - 1].clone(); + self.values.push(value); + } + } + + /// PostScript `index` with a caller-supplied underflow value, pushed even when `depth` is out + /// of range. The configured stack limit still applies. + pub fn index_or(&mut self, depth: usize, underflow: T) { + let len = self.values.len(); + let value = if depth < len { self.values[len - depth - 1].clone() } else { underflow }; + let _ = self.push(value); + } + + /// PostScript `n j roll`: rotate the top `count` values by signed `shift` places. + /// + /// Positive shifts move values toward the top; negative shifts move them toward the bottom. + /// Counts larger than the stack and empty rolls are ignored. + pub fn roll(&mut self, count: usize, shift: i64) { + let len = self.values.len(); + if count == 0 || count > len { + return; + } + let places = (i128::from(shift).rem_euclid(count as i128)) as usize; + self.values[len - count..].rotate_right(places); + } + + /// PostScript `copy` for an integer operand: append a copy of the top `count` values if it + /// fits. Returns false when the range is invalid or the configured limit would be exceeded. + pub fn copy_top(&mut self, count: usize) -> bool { + let len = self.values.len(); + if count > len || len.saturating_add(count) > self.limit { + return false; + } + let copied = self.values[len - count..].to_vec(); + self.values.extend(copied); + true + } + + /// Borrow all stack values from bottom to top. + pub fn values(&self) -> &[T] { + &self.values + } + + /// Apply a PostScript operand-stack operator. `underflow` is the interpreter's fallback value + /// for `exch`, `dup`, and `index`; the stack's configured limit remains in force. + pub fn execute(&mut self, operator: StackOperator, underflow: T) -> StackOutcome { + match operator { + StackOperator::Pop => StackOutcome::Popped(self.pop()), + StackOperator::Exchange => { + self.exchange_or(underflow); + StackOutcome::None + } + StackOperator::Duplicate => { + self.duplicate_or(underflow); + StackOutcome::None + } + StackOperator::CopyTop(count) => StackOutcome::Copied(self.copy_top(count)), + StackOperator::Index(depth) => { + self.index_or(depth, underflow); + StackOutcome::None + } + StackOperator::Roll { count, shift } => { + self.roll(count, shift); + StackOutcome::None + } + StackOperator::Clear => { + self.clear(); + StackOutcome::None + } + StackOperator::Count => StackOutcome::Count(self.len()), + } + } +} + +/// Bounded execution accounting shared by PostScript interpreters. +/// +/// EPS programs can recurse or repeatedly execute procedures. A host can use this counter to +/// stop work before it consumes unbounded CPU, independently of its operator and graphics policy. +#[derive(Clone, Debug)] +pub struct ExecutionBudget { + remaining: usize, + call_depth: usize, + max_call_depth: usize, +} + +impl ExecutionBudget { + /// Create a budget with an operation allowance and maximum nested procedure calls. + pub fn new(operations: usize, max_call_depth: usize) -> Self { + Self { remaining: operations, call_depth: 0, max_call_depth } + } + + /// Units of work still available. + pub fn remaining(&self) -> usize { + self.remaining + } + + /// Current nested procedure depth. + pub fn call_depth(&self) -> usize { + self.call_depth + } + + /// Charge work atomically. On failure the remaining budget stays unchanged. + pub fn spend(&mut self, units: usize) -> bool { + let Some(remaining) = self.remaining.checked_sub(units) else { + return false; + }; + self.remaining = remaining; + true + } + + /// Charge work that is accounted lazily: saturate at zero so the caller's next strict + /// [`Self::spend`] stops execution. This supports work whose current operator preserves the + /// app's historical behavior after exhausting its budget. + pub fn charge(&mut self, units: usize) { + self.remaining = self.remaining.saturating_sub(units); + } + + /// Enter a procedure call if it remains within the configured depth. + pub fn enter_call(&mut self) -> bool { + if self.call_depth >= self.max_call_depth { + return false; + } + self.call_depth += 1; + true + } + + /// Leave a procedure call. Extra leaves are ignored to keep cleanup paths safe. + pub fn leave_call(&mut self) { + self.call_depth = self.call_depth.saturating_sub(1); + } +} + +/// Numeric operators used by PostScript's value-independent arithmetic core. +/// +/// The host interpreter remains responsible for popping operands and selecting a result value, +/// but these operations define the shared arithmetic semantics. Non-finite results become zero, +/// matching the defensive finite-value policy used by the host interpreter. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NumericOperator { + Add, + Subtract, + Multiply, + Divide, + IntegerDivide, + Modulo, + Atan, + Exponentiate, + Maximum, + Minimum, + Negate, + Absolute, + SquareRoot, + Sine, + Cosine, + NaturalLog, + CommonLog, + ToInteger, + ToReal, + Round, + Floor, + Ceiling, + Truncate, +} + +impl NumericOperator { + /// Resolve a standard PostScript operator name to its numeric operation. + pub fn from_name(name: &str) -> Option { + Some(match name { + "add" => Self::Add, + "sub" => Self::Subtract, + "mul" => Self::Multiply, + "div" => Self::Divide, + "idiv" => Self::IntegerDivide, + "mod" => Self::Modulo, + "atan" => Self::Atan, + "exp" => Self::Exponentiate, + "max" => Self::Maximum, + "min" => Self::Minimum, + "neg" => Self::Negate, + "abs" => Self::Absolute, + "sqrt" => Self::SquareRoot, + "sin" => Self::Sine, + "cos" => Self::Cosine, + "ln" => Self::NaturalLog, + "log" => Self::CommonLog, + "cvi" => Self::ToInteger, + "cvr" => Self::ToReal, + "round" => Self::Round, + "floor" => Self::Floor, + "ceiling" => Self::Ceiling, + "truncate" => Self::Truncate, + _ => return None, + }) + } + + /// Number of operands the operation consumes. + pub const fn arity(self) -> usize { + match self { + Self::Add + | Self::Subtract + | Self::Multiply + | Self::Divide + | Self::IntegerDivide + | Self::Modulo + | Self::Atan + | Self::Exponentiate + | Self::Maximum + | Self::Minimum => 2, + _ => 1, + } + } + + /// Apply a binary operator. Returns `None` for an operator that takes one operand. + pub fn apply_binary(self, a: f64, b: f64) -> Option { + let value = match self { + Self::Add => a + b, + Self::Subtract => a - b, + Self::Multiply => a * b, + Self::Divide => { + if b == 0.0 { + 0.0 + } else { + a / b + } + } + // Rust's float-to-int cast saturates, as the app's previous VM did. checked_div/rem + // also make both zero-divisor and i64::MIN / -1 cases deterministic. + Self::IntegerDivide => (a as i64).checked_div(b as i64).unwrap_or(0) as f64, + Self::Modulo => (a as i64).checked_rem(b as i64).unwrap_or(0) as f64, + Self::Atan => a.atan2(b).to_degrees().rem_euclid(360.0), + Self::Exponentiate => a.powf(b), + Self::Maximum => a.max(b), + Self::Minimum => a.min(b), + _ => return None, + }; + Some(finite_or_zero(value)) + } + + /// Apply a unary operator. Returns `None` for an operator that takes two operands. + pub fn apply_unary(self, a: f64) -> Option { + let value = match self { + Self::Negate => -a, + Self::Absolute => a.abs(), + Self::SquareRoot => a.max(0.0).sqrt(), + Self::Sine => a.to_radians().sin(), + Self::Cosine => a.to_radians().cos(), + Self::NaturalLog => a.ln(), + Self::CommonLog => a.log10(), + Self::ToInteger | Self::Truncate => a.trunc(), + Self::ToReal => a, + Self::Round => (a + 0.5).floor(), + Self::Floor => a.floor(), + Self::Ceiling => a.ceil(), + _ => return None, + }; + Some(finite_or_zero(value)) + } +} + +fn finite_or_zero(value: f64) -> f64 { + if value.is_finite() { value } else { 0.0 } +} + +/// A lexical PostScript value. Names are left unevaluated for the caller's interpreter. +#[derive(Clone, Debug, PartialEq)] +pub enum Token { + /// A number accepted by the PostScript source reader. + Number(f64), + /// An executable name, including immediately evaluated `//name`. + Name(String), + /// A literal name such as `/name`. + LiteralName(String), + /// A parenthesized or hexadecimal byte string. + String(Vec), + /// The encoded bytes between `<~` and `~>` (including delimiters), not decoded data. + Ascii85(Vec), + /// A procedure whose nested values have already been tokenized. + Procedure(Vec), + /// A closing brace not consumed as part of a procedure, or another malformed delimiter. + Null, +} + +/// PostScript source bytes and the current byte offset. +pub struct Scanner<'a> { + /// Source bytes. Public so an interpreter can implement `currentfile` operators. + pub data: &'a [u8], + /// Current byte offset in [`Scanner::data`]. + pub pos: usize, +} + +impl<'a> Scanner<'a> { + /// Start scanning at a byte offset, clamped to the source length. + pub fn new(data: &'a [u8], pos: usize) -> Self { + Self { data, pos: pos.min(data.len()) } + } + + /// The next token; `{ … }` is returned as one procedure token. + pub fn token(&mut self) -> Option { + self.token_at_depth(0) + } + + fn token_at_depth(&mut self, depth: usize) -> Option { + self.skip_ws(); + let c = *self.data.get(self.pos)?; + Some(match c { + b'{' => { + self.pos += 1; + let mut body = Vec::new(); + loop { + self.skip_ws(); + match self.data.get(self.pos) { + None => break, + Some(b'}') => { + self.pos += 1; + break; + } + _ if depth >= MAX_PROCEDURE_DEPTH => break, + _ => match self.token_at_depth(depth + 1) { + Some(t) => body.push(t), + None => break, + }, + } + } + Token::Procedure(body) + } + b'}' => { + self.pos += 1; + Token::Null + } + b'/' => { + self.pos += 1; + let immediately_evaluated = self.data.get(self.pos) == Some(&b'/'); + if immediately_evaluated { + self.pos += 1; + } + let name = String::from_utf8_lossy(self.word()).into_owned(); + if immediately_evaluated { Token::Name(name) } else { Token::LiteralName(name) } + } + b'(' => Token::String(self.parenthesized()), + b'<' if self.data.get(self.pos + 1) == Some(&b'<') => { + self.pos += 2; + Token::Name("<<".to_owned()) + } + b'>' if self.data.get(self.pos + 1) == Some(&b'>') => { + self.pos += 2; + Token::Name(">>".to_owned()) + } + b'<' if self.data.get(self.pos + 1) == Some(&b'~') => self.ascii85(), + b'<' => Token::String(self.hex_string()), + b'[' | b']' => { + self.pos += 1; + Token::Name(char::from(c).to_string()) + } + b')' | b'>' => { + self.pos += 1; + Token::Null + } + _ => { + let word = self.word(); + if word.is_empty() { + self.pos += 1; + return Some(Token::Null); + } + match parse_number(word) { + Some(n) => Token::Number(n), + None => { + let name = String::from_utf8_lossy(word).into_owned(); + if let Some((radix, digits)) = name.split_once('#') { + let radix = radix.parse::().ok().filter(|r| (2..=36).contains(r)); + if let Some(number) = radix.and_then(|r| i64::from_str_radix(digits, r).ok()) { + return Some(Token::Number(number as f64)); + } + } + Token::Name(name) + } + } + } + }) + } + + /// Step over inline image data that follows an `image` operator reading `currentfile`. + pub fn skip_image_data(&mut self) { + self.skip_ws(); + let rest = self.data.get(self.pos..).unwrap_or_default(); + if rest.starts_with(b"<~") || self.data.get(self.pos).is_some_and(|c| (b'!'..=b'u').contains(c) && !c.is_ascii_hexdigit()) { + self.pos = match rest.windows(2).position(|w| w == b"~>") { + Some(p) => self.pos.saturating_add(p).saturating_add(2).min(self.data.len()), + None => self.data.len(), + }; + return; + } + while self.pos < self.data.len() && (self.data[self.pos].is_ascii_hexdigit() || is_white(self.data[self.pos])) { + self.pos += 1; + } + if self.data.get(self.pos) == Some(&b'>') { + self.pos += 1; + } + } + + fn skip_ws(&mut self) { + while self.pos < self.data.len() { + let c = self.data[self.pos]; + if is_white(c) { + self.pos += 1; + } else if c == b'%' { + let start = self.pos; + while self.pos < self.data.len() && !matches!(self.data[self.pos], b'\n' | b'\r') { + self.pos += 1; + } + let line = &self.data[start..self.pos]; + let end_marker: Option<&[u8]> = if line.starts_with(b"%%BeginData:") { + Some(b"%%EndData") + } else if line.starts_with(b"%%BeginBinary:") { + Some(b"%%EndBinary") + } else if line.starts_with(b"%%BeginPreview") { + Some(b"%%EndPreview") + } else { + None + }; + if let Some(marker) = end_marker { + self.pos = match self.data.get(self.pos..).unwrap_or_default().windows(marker.len()).position(|w| w == marker) { + Some(offset) => self.pos.saturating_add(offset).min(self.data.len()), + None => self.data.len(), + }; + } + } else { + break; + } + } + } + + fn word(&mut self) -> &[u8] { + let start = self.pos; + while self.pos < self.data.len() { + let c = self.data[self.pos]; + if is_white(c) || matches!(c, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') { + break; + } + self.pos += 1; + } + &self.data[start..self.pos] + } + + fn parenthesized(&mut self) -> Vec { + self.pos += 1; + let mut out = Vec::new(); + let mut nesting = 1usize; + while self.pos < self.data.len() { + let c = self.data[self.pos]; + self.pos += 1; + match c { + b'\\' => { + let e = self.data.get(self.pos).copied().unwrap_or(b'\\'); + self.pos = self.pos.saturating_add(1).min(self.data.len()); + match e { + b'n' => out.push(b'\n'), + b'r' => out.push(b'\r'), + b't' => out.push(b'\t'), + b'0'..=b'7' => { + let mut value = u32::from(e - b'0'); + for _ in 0..2 { + match self.data.get(self.pos) { + Some(d @ b'0'..=b'7') => { + value = value * 8 + u32::from(*d - b'0'); + self.pos += 1; + } + _ => break, + } + } + out.push(value as u8); + } + b'\n' | b'\r' => {} + other => out.push(other), + } + } + b'(' => { + nesting = nesting.saturating_add(1); + out.push(c); + } + b')' => { + nesting = nesting.saturating_sub(1); + if nesting == 0 { + break; + } + out.push(c); + } + _ => out.push(c), + } + } + out + } + + fn hex_string(&mut self) -> Vec { + self.pos += 1; + let mut hex = Vec::new(); + while self.pos < self.data.len() && self.data[self.pos] != b'>' { + if self.data[self.pos].is_ascii_hexdigit() { + hex.push(self.data[self.pos]); + } + self.pos += 1; + } + if self.data.get(self.pos) == Some(&b'>') { + self.pos += 1; + } + if hex.len() % 2 == 1 { + hex.push(b'0'); + } + hex.chunks(2).filter_map(|pair| Some((hex_value(*pair.first()?) << 4) | hex_value(*pair.get(1)?))).collect() + } + + fn ascii85(&mut self) -> Token { + let start = self.pos; + self.pos = self.pos.saturating_add(2).min(self.data.len()); + while self.pos + 1 < self.data.len() && !(self.data[self.pos] == b'~' && self.data[self.pos + 1] == b'>') { + self.pos += 1; + } + self.pos = self.pos.saturating_add(2).min(self.data.len()); + Token::Ascii85(self.data[start..self.pos].to_vec()) + } +} + +fn is_white(c: u8) -> bool { + matches!(c, 0 | 9 | 10 | 12 | 13 | 32) +} + +fn hex_value(c: u8) -> u8 { + (c as char).to_digit(16).unwrap_or(0) as u8 +} + +fn parse_number(word: &[u8]) -> Option { + if word.is_empty() || !word.iter().all(|c| c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.')) || !word.iter().any(u8::is_ascii_digit) { + return None; + } + let text = std::str::from_utf8(word).ok()?; + text.parse::() + .ok() + .or_else(|| text.trim_start_matches(['+', '-']).parse::().ok().map(|value| if text.starts_with('-') { -value } else { value })) +} + +#[cfg(test)] +mod stack_tests { + use super::{ExecutionBudget, OperandStack, StackOperator, StackOutcome}; + + #[test] + fn stack_operators_follow_postscript_order_and_respect_limit() { + let mut stack = OperandStack::new(8); + assert!(stack.push(1)); + assert!(stack.push(2)); + assert!(stack.push(3)); + stack.exchange(); + assert_eq!(stack.values(), &[1, 3, 2]); + stack.duplicate(); + assert_eq!(stack.values(), &[1, 3, 2, 2]); + stack.roll(4, 1); + assert_eq!(stack.values(), &[2, 1, 3, 2]); + stack.roll(4, -1); + assert_eq!(stack.values(), &[1, 3, 2, 2]); + stack.index(2); + assert_eq!(stack.values(), &[1, 3, 2, 2, 3]); + assert!(stack.copy_top(2)); + assert_eq!(stack.values(), &[1, 3, 2, 2, 3, 2, 3]); + stack.duplicate(); + assert_eq!(stack.len(), 8); + assert!(!stack.push(7)); + } + + #[test] + fn stack_underflow_and_invalid_rolls_are_safe() { + let mut stack = OperandStack::new(2); + assert_eq!(stack.pop_or(99), 99); + stack.duplicate_or(99); + assert_eq!(stack.values(), &[99]); + stack.clear(); + stack.exchange_or(99); + assert_eq!(stack.values(), &[99, 99]); + stack.clear(); + stack.roll(1, i64::MAX); + stack.index(usize::MAX); + assert!(stack.is_empty()); + assert!(stack.copy_top(0)); + assert!(stack.is_empty()); + } + + #[test] + fn stack_mutation_and_underflow_index_are_bounded() { + let mut stack = OperandStack::new(4); + assert!(stack.push(10)); + assert!(stack.push(20)); + stack.index_or(1, -1); + stack.index_or(9, -1); + assert_eq!(stack.values(), &[10, 20, 10, -1]); + stack.index_or(0, -1); + assert_eq!(stack.values(), &[10, 20, 10, -1]); // full stack silently drops the push + + assert_eq!(stack.top(), Some(&-1)); + stack.values_mut()[3] = 40; + stack.roll(3, i64::MIN); + assert_eq!(stack.values(), &[10, 40, 20, 10]); + assert!(stack.split_off(usize::MAX).is_empty()); + assert_eq!(stack.split_off(1), [40, 20, 10]); + assert_eq!(stack.values(), &[10]); + assert_eq!(stack.pop(), Some(10)); + assert_eq!(stack.pop(), None); + stack.clear(); + assert!(stack.is_empty()); + } + + #[test] + fn shared_stack_operator_dispatch_reports_only_value_results() { + let mut stack = OperandStack::new(4); + assert!(stack.push(1)); + assert!(stack.push(2)); + assert_eq!(stack.execute(StackOperator::Count, 0), StackOutcome::Count(2)); + assert_eq!(stack.execute(StackOperator::Exchange, 0), StackOutcome::None); + assert_eq!(stack.values(), &[2, 1]); + assert_eq!(stack.execute(StackOperator::Duplicate, 0), StackOutcome::None); + assert_eq!(stack.execute(StackOperator::Index(2), 0), StackOutcome::None); + assert_eq!(stack.values(), &[2, 1, 1, 2]); + assert_eq!(stack.execute(StackOperator::Roll { count: 3, shift: 1 }, 0), StackOutcome::None); + assert_eq!(stack.values(), &[2, 2, 1, 1]); + assert_eq!(stack.execute(StackOperator::CopyTop(2), 0), StackOutcome::Copied(false)); + assert_eq!(stack.execute(StackOperator::Pop, 0), StackOutcome::Popped(Some(1))); + assert_eq!(stack.execute(StackOperator::Clear, 0), StackOutcome::None); + assert!(stack.is_empty()); + } + + #[test] + fn execution_budget_charges_atomically_and_bounds_call_depth() { + let mut budget = ExecutionBudget::new(3, 1); + assert!(budget.spend(2)); + assert_eq!(budget.remaining(), 1); + assert!(!budget.spend(2)); + assert_eq!(budget.remaining(), 1); + budget.charge(2); + assert_eq!(budget.remaining(), 0); + assert!(!budget.spend(1)); + assert!(budget.enter_call()); + assert_eq!(budget.call_depth(), 1); + assert!(!budget.enter_call()); + budget.leave_call(); + budget.leave_call(); + assert_eq!(budget.call_depth(), 0); + assert!(budget.enter_call()); + } +} + +#[cfg(test)] +mod numeric_operator_tests { + use super::NumericOperator as N; + + #[test] + fn binary_numeric_operator_results_match_the_shared_vm_contract() { + assert_eq!(N::from_name("add"), Some(N::Add)); + assert_eq!(N::from_name("idiv").map(N::arity), Some(2)); + assert_eq!(N::from_name("sqrt").map(N::arity), Some(1)); + assert_eq!(N::from_name("setgray"), None); + assert_eq!(N::Add.apply_binary(2.0, 3.0), Some(5.0)); + assert_eq!(N::Subtract.apply_binary(2.0, 3.0), Some(-1.0)); + assert_eq!(N::Multiply.apply_binary(2.0, 3.0), Some(6.0)); + assert_eq!(N::Divide.apply_binary(7.0, 2.0), Some(3.5)); + assert_eq!(N::Divide.apply_binary(7.0, 0.0), Some(0.0)); + assert_eq!(N::IntegerDivide.apply_binary(-7.0, 2.0), Some(-3.0)); + assert_eq!(N::IntegerDivide.apply_binary(7.0, 0.0), Some(0.0)); + assert_eq!(N::IntegerDivide.apply_binary(i64::MIN as f64, -1.0), Some(0.0)); + assert_eq!(N::Modulo.apply_binary(-7.0, 2.0), Some(-1.0)); + assert_eq!(N::Modulo.apply_binary(7.0, 0.0), Some(0.0)); + assert_eq!(N::Atan.apply_binary(0.0, -1.0), Some(180.0)); + assert_eq!(N::Exponentiate.apply_binary(-2.0, 3.0), Some(-8.0)); + assert_eq!(N::Exponentiate.apply_binary(-2.0, 0.5), Some(0.0)); + assert_eq!(N::Maximum.apply_binary(2.0, 3.0), Some(3.0)); + assert_eq!(N::Minimum.apply_binary(2.0, 3.0), Some(2.0)); + assert_eq!(N::Negate.apply_binary(1.0, 2.0), None); + } + + #[test] + fn unary_numeric_operator_results_match_the_shared_vm_contract() { + assert_eq!(N::Negate.apply_unary(2.0), Some(-2.0)); + assert_eq!(N::Absolute.apply_unary(-2.0), Some(2.0)); + assert_eq!(N::SquareRoot.apply_unary(-2.0), Some(0.0)); + assert_eq!(N::Sine.apply_unary(30.0).map(|v| (v - 0.5).abs() < 1e-12), Some(true)); + assert_eq!(N::Cosine.apply_unary(60.0).map(|v| (v - 0.5).abs() < 1e-12), Some(true)); + assert_eq!(N::NaturalLog.apply_unary(-1.0), Some(0.0)); + assert_eq!(N::CommonLog.apply_unary(100.0), Some(2.0)); + assert_eq!(N::ToInteger.apply_unary(-2.9), Some(-2.0)); + assert_eq!(N::ToReal.apply_unary(2.5), Some(2.5)); + assert_eq!(N::Round.apply_unary(-1.5), Some(-1.0)); + assert_eq!(N::Floor.apply_unary(1.9), Some(1.0)); + assert_eq!(N::Ceiling.apply_unary(1.1), Some(2.0)); + assert_eq!(N::Truncate.apply_unary(-2.9), Some(-2.0)); + assert_eq!(N::Add.apply_unary(1.0), None); + } +} + +#[cfg(test)] +mod tests { + use super::{Scanner, Token}; + + fn scan(source: &[u8]) -> Vec { + let mut scanner = Scanner::new(source, 0); + let mut tokens = Vec::new(); + while let Some(token) = scanner.token() { + tokens.push(token); + } + tokens + } + + #[test] + fn scans_names_numbers_strings_and_procedures() { + assert_eq!( + scan(b"/x //y 16#ff { 2 (a\\n(b)) }"), + vec![ + Token::LiteralName("x".into()), + Token::Name("y".into()), + Token::Number(255.0), + Token::Procedure(vec![Token::Number(2.0), Token::String(b"a\n(b)".to_vec())]), + ] + ); + } + + #[test] + fn skips_dsc_binary_data_and_preserves_inline_ascii85() { + assert_eq!(scan(b"%%BeginBinary: 4\nxxxx%%EndBinary\n<~z~>"), vec![Token::Ascii85(b"<~z~>".to_vec())]); + } + + #[test] + fn malformed_delimiters_terminate_without_advancing_past_source() { + let mut scanner = Scanner::new(b", +} + +/// A decoded part whose channels are placed in the display window. +#[derive(Debug, Clone, PartialEq)] +pub struct DisplayPart { + pub info: PartInfo, + pub channels: Vec, +} + +/// Decodes the kept flat channels of one part and places them in its display window. +/// +/// Channels are decoded in their stored sample type, converted to `f32`, and clipped or padded +/// according to their data and display windows. `keep` and `fill` receive the part-qualified name +/// from [`part_channel_name`], which is also returned in [`DisplayChannel::name`]. Both decoded +/// block data and display-window buffers are bounded by `limits` before allocation. +pub fn decode_display_part( + bytes: &[u8], + index: usize, + keep: &dyn Fn(&str) -> bool, + fill: &dyn Fn(&str) -> f32, + limits: &Limits, +) -> Result { + // Only the caller-selected display planes are allocated here. Keep the shared header and + // expansion-ratio checks, but do not charge ignored channel data against the output budget. + let mut header_limits = *limits; + header_limits.max_width = u32::MAX; + header_limits.max_height = u32::MAX; + header_limits.max_pixels = u64::MAX; + header_limits.max_bytes = u64::MAX; + let meta = read_meta(bytes, &header_limits)?; + let info = meta.headers.get(index).map(|header| part_info(index, header)).ok_or_else(|| malformed(format!("part {index}")))?; + if info.deep { + return Err(Error::Unsupported("deep data (use the deep reader)".into())); + } + let display = info.display_window; + let pixels = u64::from(display.width) + .checked_mul(u64::from(display.height)) + .ok_or_else(|| Error::LimitExceeded("display window dimensions overflow".into()))?; + if pixels > limits.max_pixels { + return Err(Error::LimitExceeded(format!("display window of {pixels} pixels exceeds {}", limits.max_pixels))); + } + let kept = info.channels.iter().filter(|channel| keep(&part_channel_name(info.name.as_deref(), &channel.name))).count(); + let bytes_needed = pixels + .checked_mul(4) + .and_then(|bytes_per_channel| bytes_per_channel.checked_mul(kept as u64)) + .ok_or_else(|| Error::LimitExceeded("display window byte size overflow".into()))?; + if bytes_needed > limits.max_bytes || usize::try_from(bytes_needed).is_err() { + return Err(Error::LimitExceeded(format!("{bytes_needed} display-window bytes exceed {}", limits.max_bytes))); + } + let block_limit = std::cell::Cell::new(None); + let select = DisplaySelect { index, keep, fill, limits, seen: std::cell::Cell::new(0), block_limit: &block_limit }; + let image = ReadImage::new(ReadAllLayers { read_channels: select }, |_| {}) + .from_buffered(Cursor::new(bytes)) + .map_err(|error| block_limit.take().map(Error::LimitExceeded).unwrap_or_else(|| map_exr(error)))?; + let channels = image + .layer_data + .into_iter() + .nth(index) + .ok_or_else(|| malformed("the part was not read"))? + .channel_data + .into_iter() + .flatten() + .map(|(name, samples)| DisplayChannel { name, samples }) + .collect(); + Ok(DisplayPart { info, channels }) +} + +/// Filtered channel reader that writes each decoded block directly into a bounded display plane. +struct DisplaySelect<'a> { + index: usize, + keep: &'a dyn Fn(&str) -> bool, + fill: &'a dyn Fn(&str) -> f32, + limits: &'a Limits, + seen: std::cell::Cell, + block_limit: &'a std::cell::Cell>, +} + +struct DisplaySelectReader { + planes: Vec)>>, + offset: (i64, i64), + layer: (usize, usize), + display: (usize, usize), + f16s: Vec, + f32s: Vec, + u32s: Vec, +} + +impl<'s> ReadChannels<'s> for DisplaySelect<'_> { + type Reader = DisplaySelectReader; + + fn create_channels_reader(&'s self, header: &Header) -> exr::error::Result { + let part = self.seen.get(); + self.seen.set(part.saturating_add(1)); + let (layer_w, layer_h) = (header.layer_size.0, header.layer_size.1); + let display_window = header.shared_attributes.display_window; + let (display_w, display_h) = (display_window.size.0, display_window.size.1); + if part != self.index { + return Ok(DisplaySelectReader { + planes: header.channels.list.iter().map(|_| None).collect(), + offset: (0, 0), + layer: (layer_w, layer_h), + display: (display_w, display_h), + f16s: vec![], + f32s: vec![], + u32s: vec![], + }); + } + // The EXR crate decompresses each accepted block before `read_block` can discard ignored + // channels. Bound that all-channel input separately from the selected output planes. + let Some(block_bytes) = layer_w + .checked_mul(layer_h) + .and_then(|pixels| pixels.checked_mul(header.channels.list.len().max(1))) + .and_then(|samples| samples.checked_mul(std::mem::size_of::())) + else { + self.block_limit.set(Some(format!("data-window block size exceeds {}", self.limits.max_bytes))); + return Err(exr::error::Error::Invalid("data-window block size overflow".into())); + }; + if u64::try_from(block_bytes).map_or(true, |bytes| bytes > self.limits.max_bytes) || block_bytes > isize::MAX as usize { + self.block_limit.set(Some(format!("{block_bytes} data-window bytes exceed {}", self.limits.max_bytes))); + return Err(exr::error::Error::Invalid("data-window blocks exceed limit".into())); + } + let pixels = display_w.checked_mul(display_h).filter(|n| *n > 0).ok_or(exr::error::Error::Invalid("display window".into()))?; + let prefix = header.own_attributes.layer_name.as_ref().map(|name| name.to_string()).filter(|name| !name.is_empty()); + let kept = + header.channels.list.iter().filter(|channel| (self.keep)(&part_channel_name(prefix.as_deref(), &channel.name.to_string()))).count(); + let bytes = pixels + .checked_mul(4) + .and_then(|n| n.checked_mul(kept)) + .ok_or_else(|| exr::error::Error::Invalid("display planes exceed limit".into()))?; + if pixels as u64 > self.limits.max_pixels || bytes as u64 > self.limits.max_bytes || bytes > isize::MAX as usize { + return Err(exr::error::Error::Invalid("display planes exceed limit".into())); + } + let mut planes = Vec::with_capacity(header.channels.list.len()); + for channel in header.channels.list.iter() { + let name = part_channel_name(prefix.as_deref(), &channel.name.to_string()); + let plane = if (self.keep)(&name) { + if channel.sampling.0 != 1 || channel.sampling.1 != 1 { + return Err(exr::error::Error::NotSupported("subsampled channels".into())); + } + Some((name.clone(), vec![(self.fill)(&name); pixels])) + } else { + None + }; + planes.push(plane); + } + let position = header.own_attributes.layer_position; + Ok(DisplaySelectReader { + planes, + offset: (i64::from(position.0) - i64::from(display_window.position.0), i64::from(position.1) - i64::from(display_window.position.1)), + layer: (layer_w, layer_h), + display: (display_w, display_h), + f16s: vec![], + f32s: vec![], + u32s: vec![], + }) + } +} + +impl ChannelsReader for DisplaySelectReader { + type Channels = Vec)>>; + + fn filter_block(&self, tile: TileCoordinates) -> bool { + tile.is_largest_resolution_level() && self.planes.iter().any(Option::is_some) + } + + fn read_block(&mut self, header: &Header, block: UncompressedBlock) -> exr::error::UnitResult { + let ((layer_w, layer_h), (display_w, display_h)) = (self.layer, self.display); + for line in block.lines(&header.channels) { + let Some(Some((_, dst_plane))) = self.planes.get_mut(line.location.channel) else { continue }; + let (x, y, count) = (line.location.position.0, line.location.position.1, line.location.sample_count); + if y >= layer_h || x.checked_add(count).is_none_or(|end| end > layer_w) { + continue; + } + let Some(ty) = usize::try_from(y as i64 + self.offset.1).ok().filter(|ty| *ty < display_h) else { continue }; + let tx0 = x as i64 + self.offset.0; + let skip = usize::try_from(-tx0).unwrap_or(0).min(count); + let tx = usize::try_from(tx0.max(0)).unwrap_or(usize::MAX); + let take = (count - skip).min(display_w.saturating_sub(tx)); + if take == 0 { + continue; + } + let start = ty.checked_mul(display_w).and_then(|row| row.checked_add(tx)); + let Some(dst) = start.and_then(|s| dst_plane.get_mut(s..s.checked_add(take)?)) else { continue }; + match header.channels.list.get(line.location.channel).map(|c| c.sample_type) { + Some(ExrSample::F16) => { + self.f16s.resize(count, f16::ZERO); + line.read_samples_into_slice(&mut self.f16s)?; + for (d, s) in dst.iter_mut().zip(self.f16s.iter().skip(skip)) { + *d = s.to_f32(); + } + } + Some(ExrSample::F32) => { + self.f32s.resize(count, 0.0); + line.read_samples_into_slice(&mut self.f32s)?; + for (d, s) in dst.iter_mut().zip(self.f32s.iter().skip(skip)) { + *d = *s; + } + } + Some(ExrSample::U32) => { + self.u32s.resize(count, 0); + line.read_samples_into_slice(&mut self.u32s)?; + for (d, s) in dst.iter_mut().zip(self.u32s.iter().skip(skip)) { + *d = *s as f32; + } + } + None => continue, + } + } + Ok(()) + } + + fn into_channels(self) -> Self::Channels { + self.planes + } +} + /// Places a data-window plane in a display window: samples outside the display window are cut, /// the display window's pixels the data window does not cover are `fill`. `None` when the plane /// is not `data.width × data.height` samples or the display window has more than `max_pixels` diff --git a/crates/exr/src/decode_tests.rs b/crates/exr/src/decode_tests.rs index 69d8d07ac..54c28d9aa 100644 --- a/crates/exr/src/decode_tests.rs +++ b/crates/exr/src/decode_tests.rs @@ -118,6 +118,46 @@ fn display_window_placement() { assert_eq!(to_display_window(&[1.0, 2.0, 3.0, 4.0], far, display, 0.0, 100).unwrap(), [0.0; 6]); } +#[test] +fn decoded_display_part_places_selected_channels_and_checks_total_budget() { + let bytes = file(vec![layer(None, 2, 2, &["R", "G"], false, exr::prelude::Compression::ZIP1)], (3, 2)); + let part = decode_display_part(&bytes, 0, &|name| name == "R", &|_| 9.0, &Limits::default()).unwrap(); + assert_eq!(part.channels.len(), 1); + assert_eq!(part.channels[0].name, "R"); + assert_eq!(part.channels[0].samples, [0.0, 1.0, 9.0, 2.0, 3.0, 9.0]); + + let limits = Limits { max_bytes: 6 * 4 - 1, ..Limits::default() }; + assert!(matches!(decode_display_part(&bytes, 0, &all, &|_| 0.0, &limits), Err(Error::LimitExceeded(_)))); + + // One selected display plane fits exactly, but the EXR decoder must decompress both data + // channels in its input block before discarding the ignored one. + let block_limits = Limits { max_bytes: 6 * 4, ..Limits::default() }; + assert!(matches!(decode_display_part(&bytes, 0, &|name| name == "R", &|_| 0.0, &block_limits), Err(Error::LimitExceeded(_)))); +} + +#[test] +fn decoded_display_part_clips_a_wide_data_window_to_the_small_display() { + let width = (Limits::default().max_width as usize) + 1; + let bytes = file(vec![layer(None, width, 1, &["R"], false, exr::prelude::Compression::ZIP1)], (1, 1)); + let part = decode_display_part(&bytes, 0, &all, &|_| 9.0, &Limits::default()).unwrap(); + assert_eq!(part.channels.len(), 1); + assert_eq!(part.channels[0].samples, [0.0]); +} + +#[test] +fn decoded_display_part_rejects_kept_subsampled_channels() { + let mut bytes = file(vec![layer(None, 4, 1, &["R"], false, exr::prelude::Compression::Uncompressed)], (4, 1)); + // exr's writer doesn't emit subsampling yet, so patch the standard chlist sampling field in a + // valid uncompressed file. The reader must reject it before looking at the block payload. + let tag = b"channels\0chlist\0"; + let attr = bytes.windows(tag.len()).position(|window| window == tag).unwrap(); + let payload = attr + tag.len() + 4; + let name_end = payload + bytes[payload..].iter().position(|byte| *byte == 0).unwrap(); + let x_sampling = name_end + 1 + 4 + 1 + 3; + bytes[x_sampling..x_sampling + 4].copy_from_slice(&2u32.to_le_bytes()); + assert!(matches!(decode_display_part(&bytes, 0, &|name| name == "R", &|_| 0.0, &Limits::default()), Err(Error::Unsupported(_)))); +} + /// A 2x2 single-part file whose layer carries a 2x1 preview. fn with_preview() -> Vec { let mut attrs = LayerAttributes::named("rgb"); diff --git a/crates/fig/src/archive.rs b/crates/fig/src/archive.rs index e408ddbe7..e083aa1dc 100644 --- a/crates/fig/src/archive.rs +++ b/crates/fig/src/archive.rs @@ -12,8 +12,10 @@ use crate::{Error, corrupt}; const MAX_META: u64 = 1 << 20; /// Largest file [`write_archive`] writes (the canvas and the images together). const MAX_FILE: u64 = 2 * 1024 * 1024 * 1024; -/// Most entries an archive may declare; checked before the archive is indexed. -pub const MAX_ENTRIES: u64 = 1_000_000; +/// Most entries an archive may declare; checked before the archive is indexed. The archive holds one +/// entry per image, so 100 000 leaves room for far more than a `.fig` file carries, and a header +/// count can no longer make the index alone cost a hundred megabytes. +pub const MAX_ENTRIES: u64 = 100_000; /// What one open may read from `images/`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/figcraft-format/src/lib.rs b/crates/figcraft-format/src/lib.rs index be38562b3..7475c5e21 100644 --- a/crates/figcraft-format/src/lib.rs +++ b/crates/figcraft-format/src/lib.rs @@ -242,6 +242,57 @@ pub fn read_preview_document(bytes: &[u8]) -> Result>, + /// The first-page fields, absent when `document.json` is missing, damaged, or oversized. + pub document: Option, +} + +/// Read only the thumbnail member for a native archive-list thumbnail. +/// +/// This avoids unpacking the document when a caller needs only the image. Missing, damaged, +/// and oversized entries return None; an unreadable archive is an error. +pub fn read_preview_thumbnail(reader: R) -> Result>, FormatError> { + let mut archive = SeekArchive::open(reader, u64::MAX).map_err(|error| FormatError::Corrupt(error.to_string()))?; + Ok(archive.read("thumbnail.png", MAX_PREVIEW_THUMBNAIL_BYTES).ok().flatten()) +} + +/// Read the bounded native preview members of a `.figcraft` archive. +/// +/// An unreadable archive is an error; a missing, damaged, or oversized member is represented by +/// `None`, so the caller can still show the other part of the preview. The thumbnail and document +/// retain the separate limits used by the app's recent-file preview. +pub fn read_preview_archive(reader: R) -> Result { + let mut archive = SeekArchive::open(reader, u64::MAX).map_err(|error| FormatError::Corrupt(error.to_string()))?; + Ok(read_preview_archive_from(&mut archive)) +} + +/// Read bounded native preview members from an already-open shared archive reader. +/// +/// This lets callers preserve fallback handling for other ZIP formats without implementing ZIP +/// member access themselves. +pub fn read_preview_archive_from(archive: &mut impl NativeArchive) -> PreviewArchive { + let has_document = archive.contains("document.json"); + let thumbnail_png = archive.read_member("thumbnail.png", MAX_PREVIEW_THUMBNAIL_BYTES).ok().flatten(); + let document = if has_document { + archive.read_member("document.json", MAX_PREVIEW_DOCUMENT_BYTES).ok().flatten().and_then(|bytes| read_preview_document(&bytes).ok()) + } else { + None + }; + PreviewArchive { has_document, thumbnail_png, document } +} + pub fn check_version(h: &Header) -> Result<(), NewerVersion> { if let Some(v) = h.version && v > u64::from(VERSION) @@ -274,6 +325,55 @@ pub fn write_document_json(doc: &D, images: &[I #[cfg(test)] mod tests { use super::*; + + #[test] + fn preview_archive_reads_native_members_and_preserves_document_presence() { + let document = br#"{"pages":[7],"nodes":{"7":{"background":{"r":0.25}}},"kind":"board"}"#; + let bytes = write_archive([ + Member { name: "thumbnail.png", bytes: b"png bytes", compression: Compression::Stored }, + Member { name: "document.json", bytes: document, compression: Compression::Deflated }, + ]) + .unwrap(); + assert_eq!(read_preview_thumbnail(std::io::Cursor::new(bytes.clone())).unwrap().as_deref(), Some(b"png bytes".as_slice())); + let mut archive = SeekArchive::open(std::io::Cursor::new(bytes.clone()), u64::MAX).unwrap(); + assert!(read_preview_archive_from(&mut archive).has_document); + let preview = read_preview_archive(std::io::Cursor::new(bytes)).unwrap(); + assert!(preview.has_document); + assert_eq!(preview.thumbnail_png.as_deref(), Some(b"png bytes".as_slice())); + let document = preview.document.unwrap(); + assert_eq!(document.pages, [7]); + assert_eq!(document.kind, PreviewKind::Board); + assert_eq!(document.nodes["7"].background.as_ref().unwrap()["r"], 0.25); + + // A malformed native document still identifies this as a FigCraft archive, allowing the + // app to retain its existing fallback instead of interpreting it as another ZIP format. + let bytes = write_archive([Member { name: "document.json", bytes: b"{", compression: Compression::Stored }]).unwrap(); + let preview = read_preview_archive(std::io::Cursor::new(bytes)).unwrap(); + assert!(preview.has_document); + assert!(preview.document.is_none()); + assert!(preview.thumbnail_png.is_none()); + assert!(read_preview_archive(std::io::Cursor::new(b"not a zip".as_slice())).is_err()); + } + + #[test] + fn preview_archive_keeps_thumbnail_and_document_size_limits_independent() { + let too_large_thumbnail = vec![0; MAX_PREVIEW_THUMBNAIL_BYTES as usize + 1]; + let bytes = write_archive([ + Member { name: "thumbnail.png", bytes: &too_large_thumbnail, compression: Compression::Deflated }, + Member { name: "document.json", bytes: br#"{"pages":[3]}"#, compression: Compression::Stored }, + ]) + .unwrap(); + let preview = read_preview_archive(std::io::Cursor::new(bytes)).unwrap(); + assert!(preview.thumbnail_png.is_none()); + assert_eq!(preview.document.unwrap().pages, [3]); + + let too_large_document = vec![b' '; MAX_PREVIEW_DOCUMENT_BYTES as usize + 1]; + let bytes = write_archive([Member { name: "document.json", bytes: &too_large_document, compression: Compression::Deflated }]).unwrap(); + let preview = read_preview_archive(std::io::Cursor::new(bytes)).unwrap(); + assert!(preview.has_document); + assert!(preview.document.is_none()); + } + #[test] fn header_skips_app_fields() { let h = read_header(r#"{"version":1,"imageIndex":[{"hash":"abc"}],"nested":{"unused":true}}"#).unwrap(); diff --git a/crates/file-formats/Cargo.toml b/crates/file-formats/Cargo.toml index a1a605918..afe7c6391 100644 --- a/crates/file-formats/Cargo.toml +++ b/crates/file-formats/Cargo.toml @@ -9,11 +9,39 @@ rust-version.workspace = true [dependencies] craft-eps = { workspace = true } +craft-image-codecs = { workspace = true, optional = true } +craft-raw = { workspace = true, optional = true } +craft-ora = { workspace = true, optional = true } +craft-kra = { workspace = true, optional = true } +craft-pcraft-bundle = { workspace = true, optional = true } craft-idml = { workspace = true } craft-svg = { workspace = true } craft-zip = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } +[features] +default = [] +# These flags report which shared parser/codec families a client builds. The application still +# selects the corresponding shared crates in its dependency graph. +raster-codecs = ["dep:craft-image-codecs"] +heif = ["raster-codecs", "craft-image-codecs/heif"] +avif = ["raster-codecs", "craft-image-codecs/avif"] +pdf = [] +svg = [] +ora = ["dep:craft-ora"] +kra = ["dep:craft-kra"] +xcf = [] +pdn = [] +raw = ["dep:craft-raw"] +psd = [] +affinity = [] +pcraft = ["dep:craft-pcraft-bundle"] +ase = [] +office = [] +designcraft = [] +stencilcraft = [] +plotter = [] + [lints] workspace = true diff --git a/crates/file-formats/src/lib.rs b/crates/file-formats/src/lib.rs index 7859bf539..38619075f 100644 --- a/crates/file-formats/src/lib.rs +++ b/crates/file-formats/src/lib.rs @@ -23,6 +23,22 @@ pub enum Format { Tiff, WebP, Heif, + Tga, + Ico, + Pnm, + Pcx, + Xpm, + Dds, + Qoi, + OpenExr, + Hdr, + Avif, + Fits, + Dpx, + Jxl, + Cineon, + Dicom, + Iff, Ase, Psd, Affinity, @@ -54,9 +70,366 @@ pub enum Format { StencilCraft, } +/// Availability of one operation in the current client's shared-format build. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Availability { + /// The shared reader or writer is included in this build. + Available, + /// This format is known, but the corresponding shared operation is not implemented. + Unsupported, + /// The operation exists behind a Cargo feature that this client did not enable. + BuildDisabled, +} + +/// Shared reader/writer capability and sequence behavior for a known format. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Capabilities { + pub read: Availability, + pub write: Availability, + /// Input may contain multiple frames/pages that the shared reader can expose individually. + pub multiple_frames: bool, + /// This format can be opened as an ordered sequence of files by an application adapter. + pub file_sequence: bool, +} + +const fn capability(feature: bool, read: bool, write: bool, multiple_frames: bool, file_sequence: bool) -> Capabilities { + Capabilities { read: availability(feature, read), write: availability(feature, write), multiple_frames, file_sequence } +} + +const fn availability(feature: bool, supported: bool) -> Availability { + if !supported { + Availability::Unsupported + } else if feature { + Availability::Available + } else { + Availability::BuildDisabled + } +} + +impl Format { + /// Every known format, including formats whose reader or writer is not enabled in this build. + pub const ALL: [Format; 56] = [ + Self::Pdf, + Self::Eps, + Self::PostScript, + Self::Illustrator, + Self::Dxf, + Self::Svg, + Self::Svgz, + Self::Png, + Self::Jpeg, + Self::Bmp, + Self::Gif, + Self::Tiff, + Self::WebP, + Self::Heif, + Self::Tga, + Self::Ico, + Self::Pnm, + Self::Pcx, + Self::Xpm, + Self::Dds, + Self::Qoi, + Self::OpenExr, + Self::Hdr, + Self::Avif, + Self::Fits, + Self::Dpx, + Self::Jxl, + Self::Cineon, + Self::Dicom, + Self::Iff, + Self::Ase, + Self::Psd, + Self::Affinity, + Self::Ora, + Self::Kra, + Self::Xcf, + Self::Pdn, + Self::Raw, + Self::Pcraft, + Self::Idml, + Self::DesignCraft, + Self::DesignCraftJson, + Self::Indd, + Self::Docx, + Self::LegacyDoc, + Self::Rtf, + Self::Xlsx, + Self::TaggedText, + Self::Pptx, + Self::PlainText, + Self::Csv, + Self::Tsv, + Self::LegacyExcel, + Self::Studio, + Self::StencilCraft, + Self::Gcode, + ]; + + /// Known extensions in lowercase form, in preferred-output order. + pub fn extensions(self) -> &'static [&'static str] { + match self { + Self::Pdf => &["pdf"], + Self::Eps => &["eps"], + Self::PostScript => &["ps"], + Self::Illustrator => &["ai"], + Self::Dxf => &["dxf"], + Self::Svg => &["svg"], + Self::Svgz => &["svgz"], + Self::Png => &["png", "apng"], + Self::Jpeg => &["jpg", "jpeg", "jpe", "jfif"], + Self::Bmp => &["bmp", "dib"], + Self::Gif => &["gif"], + Self::Tiff => &["tif", "tiff"], + Self::WebP => &["webp"], + Self::Heif => &["heic", "heif", "hif"], + Self::Tga => &["tga", "icb", "vda", "vst"], + Self::Ico => &["ico"], + Self::Pnm => &["pnm", "pbm", "pgm", "ppm", "pam", "pfm"], + Self::Pcx => &["pcx"], + Self::Xpm => &["xpm"], + Self::Dds => &["dds"], + Self::Qoi => &["qoi"], + Self::OpenExr => &["exr"], + Self::Hdr => &["hdr"], + Self::Avif => &["avif"], + Self::Fits => &["fits", "fit", "fts"], + Self::Dpx => &["dpx"], + Self::Jxl => &["jxl"], + Self::Cineon => &["cin"], + Self::Dicom => &["dcm", "dicom", "dc3"], + Self::Iff => &["iff", "lbm", "ilbm"], + Self::Ase => &["ase"], + Self::Psd => &["psd", "psb", "psdt"], + Self::Affinity => &["afdesign", "afphoto", "afpub", "af"], + Self::Ora => &["ora"], + Self::Kra => &["kra"], + Self::Xcf => &["xcf"], + Self::Pdn => &["pdn"], + Self::Raw => &[ + "dng", "3fr", "ari", "arw", "bay", "cap", "cr2", "cr3", "dcs", "dcr", "drf", "eip", "erf", "fff", "gpr", "iiq", "k25", "kdc", "mdc", + "mef", "mos", "mrw", "nef", "nrw", "obm", "orf", "pef", "ptx", "pxn", "r3d", "raf", "raw", "rwl", "rw2", "rwz", "sr2", "srf", "sti", + "x3f", + ], + Self::Pcraft => &["pcraft"], + Self::Idml => &["idml"], + Self::DesignCraft => &["designcraft", "dcdoc"], + Self::DesignCraftJson => &[], + Self::Indd => &["indd", "indt"], + Self::Docx => &["docx"], + Self::LegacyDoc => &["doc"], + Self::Rtf => &["rtf"], + Self::Xlsx => &["xlsx"], + Self::TaggedText => &[], + Self::Pptx => &["pptx"], + Self::PlainText => &["txt", "text", "md"], + Self::Csv => &["csv"], + Self::Tsv => &["tsv", "tab"], + Self::LegacyExcel => &["xls", "xlsm"], + Self::Studio => &["studio", "studio3"], + Self::StencilCraft => &["stencilcraft"], + Self::Gcode => &["gcode", "nc"], + } + } + + /// Preferred extension for creating a new file of this type, if one is defined. + pub fn preferred_extension(self) -> Option<&'static str> { + self.extensions().first().copied() + } + + /// Registered MIME type, where the format has a stable MIME registration. + pub fn mime_type(self) -> Option<&'static str> { + Some(match self { + Self::Pdf => "application/pdf", + Self::Eps => "application/postscript", + Self::PostScript => "application/postscript", + Self::Illustrator => "application/illustrator", + Self::Dxf => "image/vnd.dxf", + Self::Svg | Self::Svgz => "image/svg+xml", + Self::Png => "image/png", + Self::Jpeg => "image/jpeg", + Self::Bmp => "image/bmp", + Self::Gif => "image/gif", + Self::Tiff => "image/tiff", + Self::WebP => "image/webp", + Self::Heif => "image/heif", + Self::Tga => "image/x-tga", + Self::Ico => "image/vnd.microsoft.icon", + Self::Pnm => "image/x-portable-anymap", + Self::Pcx => "image/vnd.zbrush.pcx", + Self::Xpm => "image/x-xpixmap", + Self::Dds => "image/vnd-ms.dds", + Self::Qoi => "image/qoi", + Self::OpenExr => "image/x-exr", + Self::Hdr => "image/vnd.radiance", + Self::Avif => "image/avif", + Self::Fits => "image/fits", + Self::Dpx => "image/dpx", + Self::Jxl => "image/jxl", + Self::Cineon => "image/x-cineon", + Self::Dicom => "application/dicom", + Self::Iff => "image/ilbm", + Self::Ase => "application/x-adobe-swatch-exchange", + Self::Psd => "image/vnd.adobe.photoshop", + Self::Affinity => "application/x-affinity", + Self::Ora => "image/openraster", + Self::Kra => "application/x-krita", + Self::Xcf => "image/x-xcf", + Self::Pdn => "application/x-paint.net", + Self::Raw => "image/x-camera-raw", + Self::Pcraft => "application/vnd.photocraft+zip", + Self::Idml => "application/vnd.adobe.indesign-idml-package", + Self::DesignCraft => "application/vnd.designcraft+zip", + Self::DesignCraftJson => "application/json", + Self::Indd => "application/x-indesign", + Self::Docx => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + Self::LegacyDoc => "application/msword", + Self::Rtf => "application/rtf", + Self::Xlsx => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + Self::TaggedText => "text/plain", + Self::Pptx => "application/vnd.openxmlformats-officedocument.presentationml.presentation", + Self::PlainText => "text/plain", + Self::Csv => "text/csv", + Self::Tsv => "text/tab-separated-values", + Self::LegacyExcel => "application/vnd.ms-excel", + Self::Studio => "application/x-silhouette-studio", + Self::StencilCraft => "application/vnd.stencilcraft+json", + Self::Gcode => "text/x.gcode", + }) + } + + /// The corresponding flat-raster codec, when this format is handled by `craft-image-codecs`. + #[cfg(feature = "raster-codecs")] + pub fn raster_codec(self) -> Option { + use craft_image_codecs::Format as Codec; + Some(match self { + Self::Png => Codec::Png, + Self::Jpeg => Codec::Jpeg, + Self::Bmp => Codec::Bmp, + Self::Gif => Codec::Gif, + Self::Tiff => Codec::Tiff, + Self::WebP => Codec::WebP, + Self::Heif => Codec::Heif, + Self::Tga => Codec::Tga, + Self::Ico => Codec::Ico, + Self::Pnm => Codec::Pnm, + Self::Pcx => Codec::Pcx, + Self::Xpm => Codec::Xpm, + Self::Dds => Codec::Dds, + Self::Qoi => Codec::Qoi, + Self::OpenExr => Codec::OpenExr, + Self::Hdr => Codec::Hdr, + Self::Avif => Codec::Avif, + Self::Fits => Codec::Fits, + Self::Dpx => Codec::Dpx, + Self::Jxl => Codec::Jxl, + Self::Cineon => Codec::Cineon, + Self::Dicom => Codec::Dicom, + Self::Iff => Codec::Iff, + _ => return None, + }) + } + + /// Operations exposed by this build's shared parser/codec features. + pub fn capabilities(self) -> Capabilities { + #[cfg(feature = "raster-codecs")] + if let Some(format) = self.raster_codec() { + let codec = format.caps(); + let read = if codec.read { + Availability::Available + } else if matches!(self, Self::Heif) && !cfg!(feature = "heif") { + Availability::BuildDisabled + } else { + Availability::Unsupported + }; + let write = if codec.write { + Availability::Available + } else if matches!(self, Self::Avif) && !cfg!(feature = "avif") { + Availability::BuildDisabled + } else { + Availability::Unsupported + }; + return Capabilities { read, write, multiple_frames: codec.animation, file_sequence: false }; + } + let raster = cfg!(feature = "raster-codecs"); + match self { + Self::Png | Self::Jpeg | Self::Bmp | Self::Gif | Self::Tiff | Self::WebP => { + capability(raster, true, true, matches!(self, Self::Png | Self::Gif | Self::WebP), false) + } + Self::Heif => Capabilities { + read: availability(cfg!(feature = "heif"), true), + write: Availability::Unsupported, + multiple_frames: true, + file_sequence: false, + }, + Self::Avif => Capabilities { + read: Availability::Unsupported, + write: availability(cfg!(feature = "avif"), true), + multiple_frames: false, + file_sequence: false, + }, + Self::Jxl => capability(raster, false, true, false, false), + Self::Pcx | Self::Xpm | Self::Dicom => capability(raster, true, false, false, false), + Self::Tga + | Self::Ico + | Self::Pnm + | Self::Dds + | Self::Qoi + | Self::OpenExr + | Self::Hdr + | Self::Fits + | Self::Dpx + | Self::Cineon + | Self::Iff => capability(raster, true, true, false, false), + Self::Pdf => capability(cfg!(feature = "pdf"), true, true, false, false), + Self::Eps | Self::PostScript | Self::Illustrator => capability(cfg!(feature = "pdf"), true, false, false, false), + Self::Svg | Self::Svgz => capability(cfg!(feature = "svg"), true, false, false, false), + Self::Dxf | Self::Gcode => capability(cfg!(feature = "plotter"), true, false, false, false), + Self::Ora => capability(cfg!(feature = "ora"), true, true, false, false), + Self::Kra => capability(cfg!(feature = "kra"), true, false, false, false), + Self::Xcf => capability(cfg!(feature = "xcf"), true, false, false, false), + Self::Pdn => capability(cfg!(feature = "pdn"), true, false, false, false), + Self::Raw => capability(cfg!(feature = "raw"), true, false, true, true), + Self::Psd => capability(cfg!(feature = "psd"), true, true, false, false), + Self::Affinity => capability(cfg!(feature = "affinity"), true, false, false, false), + Self::Pcraft => capability(cfg!(feature = "pcraft"), true, true, false, false), + Self::Ase => capability(cfg!(feature = "ase"), true, true, false, false), + Self::Studio => capability(cfg!(feature = "stencilcraft"), true, false, false, false), + Self::Idml | Self::Indd => capability(cfg!(feature = "designcraft"), true, false, false, false), + Self::DesignCraft | Self::DesignCraftJson => capability(cfg!(feature = "designcraft"), true, true, false, false), + Self::StencilCraft => capability(cfg!(feature = "stencilcraft"), true, true, false, false), + Self::Docx + | Self::LegacyDoc + | Self::Rtf + | Self::Xlsx + | Self::Pptx + | Self::TaggedText + | Self::PlainText + | Self::Csv + | Self::Tsv + | Self::LegacyExcel => capability(cfg!(feature = "office"), true, true, false, false), + } + } +} + /// Resolve a name and file bytes to a format. Strong signatures take precedence over /// extension hints. Only format-specific bounded probes and extension tables live here. pub fn detect(name: &str, bytes: &[u8]) -> Option { + // Container identifiers are stronger than generic ZIP signatures and filenames. The shared + // readers own their bounded, format-specific directory/mimetype probes. + #[cfg(feature = "pcraft")] + if craft_pcraft_bundle::is_pcraft_zip(bytes) { + return Some(Format::Pcraft); + } + #[cfg(feature = "ora")] + if craft_ora::is_ora(bytes) { + return Some(Format::Ora); + } + #[cfg(feature = "kra")] + if craft_kra::is_kra(bytes) { + return Some(Format::Kra); + } if craft_idml::is_idml(bytes) { return Some(Format::Idml); } @@ -86,12 +459,30 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option { if bytes.starts_with(b"PDN3") { return Some(Format::Pdn); } + // OpenEXR's four-byte magic is its canonical signature (v2, section 2.1.1). Keep it in + // the shared registry so file-handle importers can route without relying on a filename. + if bytes.starts_with(&[0x76, 0x2f, 0x31, 0x01]) { + return Some(Format::OpenExr); + } if bytes.starts_with(b"gimp xcf ") || gzipped_xcf(name, bytes) { return Some(Format::Xcf); } + // Several camera formats use TIFF containers. Ask the shared RAW parser before the generic + // raster signature so TIFF-based RAW files reach the RAW adapter, while ordinary TIFF files + // retain the raster classification. + #[cfg(feature = "raw")] + if craft_raw::probe(bytes).is_some() { + return Some(Format::Raw); + } if bytes.starts_with(b"\0\xffKA") { return Some(Format::Affinity); } + // The short `.af` alias is accepted only as an explicit Affinity filename. Treating it as + // a generic image based on unrelated pixel bytes makes misspelled native documents appear + // to open successfully as flat previews. + if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("af")) { + return Some(Format::Affinity); + } if let Some(raster) = raster_signature(bytes) { return Some(raster); } @@ -126,6 +517,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option { None } +#[cfg(test)] +mod tests; + /// DesignCraft's older ZIPs predate their leading `mimetype`; they are identified by the /// `document.json` member. The directory is bounded before it is indexed and no entry is inflated. fn designcraft_zip_has_document(bytes: &[u8]) -> bool { @@ -183,49 +577,8 @@ fn is_designcraft_json(bytes: &[u8]) -> bool { /// Resolve a file extension to a family, case-insensitively. pub fn from_extension(ext: &str) -> Option { - match ext.trim_start_matches('.').to_ascii_lowercase().as_str() { - "pdf" => Some(Format::Pdf), - "eps" => Some(Format::Eps), - "ps" => Some(Format::PostScript), - "ai" => Some(Format::Illustrator), - "dxf" => Some(Format::Dxf), - "svg" => Some(Format::Svg), - "svgz" => Some(Format::Svgz), - "png" => Some(Format::Png), - "jpg" | "jpeg" => Some(Format::Jpeg), - "bmp" => Some(Format::Bmp), - "gif" => Some(Format::Gif), - "tif" | "tiff" => Some(Format::Tiff), - "webp" => Some(Format::WebP), - "heic" | "heif" => Some(Format::Heif), - "ase" => Some(Format::Ase), - "psd" | "psb" => Some(Format::Psd), - "afdesign" | "afphoto" | "afpub" => Some(Format::Affinity), - "ora" => Some(Format::Ora), - "kra" => Some(Format::Kra), - "xcf" => Some(Format::Xcf), - "pdn" => Some(Format::Pdn), - "dng" | "3fr" | "ari" | "arw" | "bay" | "cap" | "cr2" | "cr3" | "dcs" | "dcr" | "drf" | "eip" | "erf" | "fff" | "gpr" | "iiq" | "k25" - | "kdc" | "mdc" | "mef" | "mos" | "mrw" | "nef" | "nrw" | "obm" | "orf" | "pef" | "ptx" | "pxn" | "r3d" | "raf" | "raw" | "rwl" | "rw2" - | "rwz" | "sr2" | "srf" | "sti" | "x3f" => Some(Format::Raw), - "pcraft" => Some(Format::Pcraft), - "idml" => Some(Format::Idml), - "designcraft" | "dcdoc" => Some(Format::DesignCraft), - "indd" | "indt" => Some(Format::Indd), - "docx" => Some(Format::Docx), - "doc" => Some(Format::LegacyDoc), - "rtf" => Some(Format::Rtf), - "xlsx" => Some(Format::Xlsx), - "pptx" => Some(Format::Pptx), - "txt" | "text" | "md" => Some(Format::PlainText), - "csv" => Some(Format::Csv), - "tsv" | "tab" => Some(Format::Tsv), - "xls" | "xlsm" => Some(Format::LegacyExcel), - "studio" | "studio3" => Some(Format::Studio), - "stencilcraft" => Some(Format::StencilCraft), - "gcode" | "nc" => Some(Format::Gcode), - _ => None, - } + let ext = ext.trim_start_matches('.'); + Format::ALL.into_iter().find(|format| format.extensions().iter().any(|candidate| candidate.eq_ignore_ascii_case(ext))) } const INDD_SIGNATURE: [u8; 16] = [0x06, 0x06, 0xED, 0xF5, 0xD8, 0x1D, 0x46, 0xE5, 0xBD, 0x31, 0xEF, 0xE7, 0xFE, 0x74, 0xB7, 0x1D]; diff --git a/crates/file-formats/src/tests.rs b/crates/file-formats/src/tests.rs new file mode 100644 index 000000000..84c6fcb87 --- /dev/null +++ b/crates/file-formats/src/tests.rs @@ -0,0 +1,57 @@ +use super::{Availability, Format}; + +#[test] +fn every_registered_family_has_consistent_metadata_and_extension_lookup() { + for format in Format::ALL { + let extensions = format.extensions(); + assert_eq!(format.preferred_extension(), extensions.first().copied()); + assert!(format.mime_type().is_some()); + let _capabilities = format.capabilities(); + #[cfg(feature = "raster-codecs")] + let _codec = format.raster_codec(); + + for extension in extensions { + assert_eq!(super::from_extension(extension), Some(format), "{format:?}: {extension}"); + assert_eq!(super::from_extension(&extension.to_ascii_uppercase()), Some(format), "{format:?}: {extension}"); + } + } +} + +#[test] +fn known_formats_separate_build_disabled_and_unsupported_operations() { + let jpeg = Format::Jpeg.capabilities(); + assert!(!jpeg.multiple_frames && !jpeg.file_sequence); + #[cfg(feature = "raster-codecs")] + assert_eq!(jpeg.read, Availability::Available); + #[cfg(not(feature = "raster-codecs"))] + assert_eq!(jpeg.read, Availability::BuildDisabled); + + assert_eq!(Format::Jxl.capabilities().read, Availability::Unsupported); + #[cfg(not(feature = "raster-codecs"))] + assert_eq!(Format::Jxl.capabilities().write, Availability::BuildDisabled); + assert!(!Format::Psd.capabilities().file_sequence); + assert!(Format::Raw.capabilities().file_sequence); + assert!(Format::Raw.capabilities().multiple_frames); +} + +#[test] +fn bounded_probes_prefer_signatures_and_resolve_extensions() { + assert_eq!(super::detect("misnamed.png", b"\x76\x2f\x31\x01rest"), Some(Format::OpenExr)); + assert_eq!(super::detect("misnamed.exr", b"\x89PNG\r\n\x1a\n"), Some(Format::Png)); + assert_eq!(super::detect("native.psdt", b"8BPS\0\0"), Some(Format::Psd)); + assert_eq!(super::detect("art.svg", b""), Some(Format::Svg)); + assert_eq!(super::detect("photo.EXR", b""), Some(Format::OpenExr)); + assert_eq!(super::detect("notes.txt", b""), Some(Format::PlainText)); + assert_eq!(super::detect("unknown", b""), None); +} + +#[test] +fn registered_mime_and_preferred_extensions_remain_distinct() { + assert_eq!(Format::Svg.mime_type(), Format::Svgz.mime_type()); + assert_eq!(Format::Svg.preferred_extension(), Some("svg")); + assert_eq!(Format::Svgz.preferred_extension(), Some("svgz")); + assert_eq!(Format::DesignCraftJson.mime_type(), Some("application/json")); + assert_eq!(Format::DesignCraftJson.preferred_extension(), None); + assert_eq!(Format::TaggedText.preferred_extension(), None); + assert_eq!(super::from_extension("not-a-format"), None); +} diff --git a/crates/file-import/Cargo.toml b/crates/file-import/Cargo.toml new file mode 100644 index 000000000..011943521 --- /dev/null +++ b/crates/file-import/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "craft-file-import" +description = "Shared format registry and bounded neutral scene import dispatch" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +craft-file-formats = { workspace = true } +craft-raster-codecs = { workspace = true } +craft-svg = { workspace = true } +craft-dxf = { workspace = true } +craft-pdf = { workspace = true, features = ["paths", "write"] } +craft-eps = { workspace = true, features = ["paths"] } +kurbo = { workspace = true } +thiserror = { workspace = true } +vectorcraft-geom = { workspace = true } + +[lints] +workspace = true diff --git a/crates/file-import/src/lib.rs b/crates/file-import/src/lib.rs new file mode 100644 index 000000000..195363da0 --- /dev/null +++ b/crates/file-import/src/lib.rs @@ -0,0 +1,405 @@ +//! Shared format selection and bounded decoding into neutral vector scenes or raster pixels. +//! +//! Applications own only the mapping from these generic results into their document models and +//! product-specific placement options. Format detection, supported import capabilities, reader +//! selection, unit normalization, and raster codec dispatch live here. + +use kurbo::{Affine, BezPath, PathEl, Point}; + +pub mod write; +pub use craft_file_formats::Format as DetectedFormat; + +/// The maximum encoded input accepted by the import facade. +pub const MAX_INPUT_BYTES: usize = 64 * 1024 * 1024; +pub const MAX_SHAPES: usize = 200_000; +const MM_PER_PT: f64 = 25.4 / 72.0; + +/// A product-neutral input family supported by this reader registry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ImportFormat { + Svg, + Svgz, + Dxf, + Pdf, + Eps, + Raster, +} + +/// Reader and writer capabilities for one family in the shared registry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Capability { + pub format: ImportFormat, + pub detected_formats: &'static [craft_file_formats::Format], + pub extensions: &'static [&'static str], + pub write_extensions: &'static [&'static str], + pub mime_types: &'static [&'static str], + pub raster: bool, + pub vector: bool, +} + +/// Format, reader and writer support for callers that build dialogs or query capabilities. +pub const CAPABILITIES: &[Capability] = &[ + Capability { + format: ImportFormat::Svg, + detected_formats: &[craft_file_formats::Format::Svg], + extensions: &["svg"], + write_extensions: &["svg"], + mime_types: &["image/svg+xml"], + raster: false, + vector: true, + }, + Capability { + format: ImportFormat::Svgz, + detected_formats: &[craft_file_formats::Format::Svgz], + extensions: &["svgz"], + write_extensions: &["svgz"], + mime_types: &["image/svg+xml"], + raster: false, + vector: true, + }, + Capability { + format: ImportFormat::Dxf, + detected_formats: &[craft_file_formats::Format::Dxf], + extensions: &["dxf"], + write_extensions: &["dxf"], + mime_types: &["image/vnd.dxf", "application/dxf"], + raster: false, + vector: true, + }, + Capability { + format: ImportFormat::Pdf, + detected_formats: &[craft_file_formats::Format::Pdf], + extensions: &["pdf"], + write_extensions: &["pdf"], + mime_types: &["application/pdf"], + raster: false, + vector: true, + }, + Capability { + format: ImportFormat::Eps, + detected_formats: &[craft_file_formats::Format::Eps, craft_file_formats::Format::PostScript, craft_file_formats::Format::Illustrator], + extensions: &["eps", "ps", "ai"], + write_extensions: &[], + mime_types: &["application/postscript"], + raster: false, + vector: true, + }, + Capability { + format: ImportFormat::Raster, + detected_formats: &[ + craft_file_formats::Format::Png, + craft_file_formats::Format::Jpeg, + craft_file_formats::Format::Bmp, + craft_file_formats::Format::Gif, + craft_file_formats::Format::Tiff, + craft_file_formats::Format::WebP, + ], + extensions: &["png", "jpg", "jpeg", "bmp", "gif", "tif", "tiff", "webp"], + write_extensions: &["png", "jpg", "jpeg"], + mime_types: &["image/png", "image/jpeg", "image/bmp", "image/gif", "image/tiff", "image/webp"], + raster: true, + vector: false, + }, +]; + +/// A vector path with generic source metadata. `tag` and `layer` are source labels; applications +/// may interpret their own conventions while the geometry and parsing stay shared. +#[derive(Debug, Clone, PartialEq)] +pub struct SceneShape { + pub path: BezPath, + pub tag: Option, + pub class: Option, + pub stroke: Option, + /// Parsed RGB stroke color when the source stroke is a concrete CSS color. + pub stroke_rgb: Option<[u8; 3]>, + pub layer: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct VectorScene { + pub format: ImportFormat, + pub width_mm: f64, + pub height_mm: f64, + pub shapes: Vec, + pub warnings: Vec, + /// Additional warnings omitted by the SVG reader's bounded warning collection. + pub dropped_warnings: usize, +} + +#[derive(Debug, Clone)] +pub struct RasterImage { + pub format: ImportFormat, + pub width: u32, + pub height: u32, + /// Straight-alpha RGBA pixels, row-major. + pub rgba: Vec, +} + +#[derive(Debug, Clone)] +pub enum Imported { + Vector(VectorScene), + Raster(RasterImage), +} + +#[derive(Debug, Clone, Copy)] +pub struct Limits { + pub max_input_bytes: usize, + pub max_shapes: usize, + pub max_raster_width: u32, + pub max_raster_height: u32, + pub max_raster_pixels: u64, + pub max_raster_alloc_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { + max_input_bytes: MAX_INPUT_BYTES, + max_shapes: MAX_SHAPES, + max_raster_width: 10_000, + max_raster_height: 10_000, + max_raster_pixels: 16_000_000, + max_raster_alloc_bytes: 256 * 1024 * 1024, + } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("unrecognized or unsupported import format")] + Unsupported, + #[error("input is {size} bytes; limit is {limit}")] + InputLimit { size: usize, limit: usize }, + #[error("{0}")] + Decode(String), + #[error("import produced invalid or non-finite geometry")] + InvalidGeometry, + #[error("import exceeds the configured shape limit")] + ShapeLimit, + #[error("format writer failed: {0}")] + Write(String), +} + +impl From for Error { + fn from(error: craft_pdf::write::WriteError) -> Self { + Self::Write(error.to_string()) + } +} + +/// Resolve detected file kinds to this reader registry. Illustrator files with PDF content use +/// the PDF path reader; PostScript-family files use the EPS/PostScript interpreter. +pub fn format_for(name: &str, bytes: &[u8]) -> Option { + use craft_file_formats::Format as F; + match craft_file_formats::detect(name, bytes)? { + F::Svg => Some(ImportFormat::Svg), + F::Svgz => Some(ImportFormat::Svgz), + F::Dxf => Some(ImportFormat::Dxf), + F::Pdf => Some(ImportFormat::Pdf), + F::Illustrator if bytes.starts_with(b"%PDF-") => Some(ImportFormat::Pdf), + F::Eps | F::PostScript | F::Illustrator => Some(ImportFormat::Eps), + F::Png | F::Jpeg | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster), + _ => None, + } +} + +/// Return supported extensions in the same registry used by [`format_for`]. +pub fn supported_extensions() -> Vec<&'static str> { + CAPABILITIES.iter().flat_map(|capability| capability.extensions.iter().copied()).collect() +} + +/// Raw detected kinds routed to one reader family, for app open-dialog and capability adapters. +pub fn supported_formats(format: ImportFormat) -> &'static [craft_file_formats::Format] { + CAPABILITIES.iter().find(|capability| capability.format == format).map_or(&[], |capability| capability.detected_formats) +} + +/// Whether the registry has a writer for an extension. +pub fn supports_write_extension(extension: &str) -> bool { + let extension = extension.trim_start_matches('.'); + CAPABILITIES.iter().any(|capability| capability.write_extensions.iter().any(|candidate| candidate.eq_ignore_ascii_case(extension))) +} + +/// Whether a family has at least one output writer in the shared registry. +pub fn supports_writer(format: ImportFormat) -> bool { + CAPABILITIES.iter().find(|capability| capability.format == format).is_some_and(|capability| !capability.write_extensions.is_empty()) +} + +/// Detect, select a reader, and decode the input into a neutral vector scene or RGBA image. +pub fn import(name: &str, bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.max_input_bytes { + return Err(Error::InputLimit { size: bytes.len(), limit: limits.max_input_bytes }); + } + let format = format_for(name, bytes).ok_or(Error::Unsupported)?; + let imported = match format { + ImportFormat::Svg | ImportFormat::Svgz => import_svg(name, bytes, format, limits), + ImportFormat::Dxf => import_dxf(bytes, format, limits), + ImportFormat::Pdf => import_pdf(bytes, format, limits), + ImportFormat::Eps => import_eps(bytes, format, limits), + ImportFormat::Raster => import_raster(bytes, format, limits), + }?; + if let Imported::Vector(scene) = &imported + && (!(scene.width_mm.is_finite() && scene.height_mm.is_finite() && scene.width_mm > 0.0 && scene.height_mm > 0.0) + || scene.shapes.iter().any(|shape| !path_is_finite(&shape.path))) + { + return Err(Error::InvalidGeometry); + } + Ok(imported) +} + +#[derive(Debug, Clone, Default)] +struct SvgTag { + data_kind: Option, + class: Option, +} + +impl craft_svg::paths::Kind for SvgTag { + const PROPERTIES: &'static [&'static str] = &["data-kind"]; + + fn of(style: &craft_svg::paths::StyleMap, class: &str) -> Option { + let data_kind = style.get("data-kind").cloned(); + let class = (!class.is_empty()).then(|| class.to_owned()); + (data_kind.is_some() || class.is_some()).then_some(Self { data_kind, class }) + } +} + +fn import_svg(name: &str, bytes: &[u8], format: ImportFormat, limits: Limits) -> Result { + let text = craft_svg::svgz::text(bytes, limits.max_input_bytes).map_err(|error| Error::Decode(error.to_string()))?; + let imported = craft_svg::paths::import::(&text, name).map_err(|error| Error::Decode(error.to_string()))?; + if imported.shapes.len() > limits.max_shapes { + return Err(Error::ShapeLimit); + } + let mut shapes = Vec::with_capacity(imported.shapes.len()); + for shape in &imported.shapes { + let path = imported.clipped_path(shape).map_err(|error| Error::Decode(error.to_string()))?; + shapes.push(SceneShape { + path, + tag: shape.kind.data_kind.clone(), + class: shape.kind.class.clone(), + stroke: shape.stroke.clone(), + stroke_rgb: shape.stroke.as_deref().and_then(|value| craft_svg::color::parse_color(value).ok()).map(|color| [color.r, color.g, color.b]), + layer: shape.layer.clone(), + }); + } + Ok(Imported::Vector(VectorScene { + format, + width_mm: imported.width_mm, + height_mm: imported.height_mm, + shapes, + warnings: imported.warnings, + dropped_warnings: imported.dropped_warnings, + })) +} + +fn import_dxf(bytes: &[u8], format: ImportFormat, limits: Limits) -> Result { + let imported = craft_dxf::paths::import(bytes).map_err(|error| Error::Decode(error.to_string()))?; + if imported.paths.len() > limits.max_shapes { + return Err(Error::ShapeLimit); + } + let (width_mm, height_mm, transform) = match imported.bounds { + Some(bounds) => ( + (bounds.width() * imported.unit_to_mm).max(1.0), + (bounds.height() * imported.unit_to_mm).max(1.0), + Affine::new([imported.unit_to_mm, 0.0, 0.0, -imported.unit_to_mm, -bounds.x0 * imported.unit_to_mm, bounds.y1 * imported.unit_to_mm]), + ), + None => (100.0, 150.0, Affine::IDENTITY), + }; + let shapes = imported + .paths + .into_iter() + .map(|path| SceneShape { path: transform * path, tag: None, class: None, stroke: None, stroke_rgb: None, layer: None }) + .collect(); + Ok(Imported::Vector(VectorScene { format, width_mm, height_mm, shapes, warnings: imported.warnings, dropped_warnings: 0 })) +} + +fn import_pdf(bytes: &[u8], format: ImportFormat, limits: Limits) -> Result { + let imported = craft_pdf::paths::import_page( + bytes, + 0, + craft_pdf::paths::Limits { max_input_bytes: limits.max_input_bytes, max_paths: limits.max_shapes, ..Default::default() }, + ) + .map_err(|error| Error::Decode(error.to_string()))?; + let page = imported.pages.into_iter().next().ok_or_else(|| Error::Decode("PDF has no pages".into()))?; + let bounds = page.crop_box; + let mut warnings = imported.warnings; + if page.omitted_text > 0 || page.omitted_images > 0 { + warnings.push(format!("PDF omitted {} text and {} image items", page.omitted_text, page.omitted_images)); + } + let shapes = page + .paths + .into_iter() + .map(|path| SceneShape { path: Affine::scale(MM_PER_PT) * path, tag: None, class: None, stroke: None, stroke_rgb: None, layer: None }) + .collect(); + Ok(Imported::Vector(VectorScene { + format, + width_mm: bounds.width() * MM_PER_PT, + height_mm: bounds.height() * MM_PER_PT, + shapes, + warnings, + dropped_warnings: 0, + })) +} + +fn import_eps(bytes: &[u8], format: ImportFormat, limits: Limits) -> Result { + let imported = craft_eps::paths::import( + bytes, + craft_eps::paths::Limits { max_input_bytes: limits.max_input_bytes, max_paths: limits.max_shapes, ..Default::default() }, + ) + .map_err(|error| Error::Decode(error.to_string()))?; + let bounds = imported.page_bounds; + let transform = Affine::scale(MM_PER_PT); + let mut warnings = imported.warnings; + if imported.preview_fallback { + warnings.push("embedded raster preview was not imported as paths".into()); + } + let shapes = imported + .paths + .into_iter() + .map(|path| SceneShape { path: transform * path, tag: None, class: None, stroke: None, stroke_rgb: None, layer: None }) + .collect(); + Ok(Imported::Vector(VectorScene { + format, + width_mm: (bounds.width() * MM_PER_PT).max(1.0), + height_mm: (bounds.height() * MM_PER_PT).max(1.0), + shapes, + warnings, + dropped_warnings: 0, + })) +} + +fn import_raster(bytes: &[u8], format: ImportFormat, limits: Limits) -> Result { + let rgba = craft_raster_codecs::common::decode_rgba( + bytes, + craft_raster_codecs::common::DecodeLimits { + max_file_bytes: limits.max_input_bytes, + max_width: limits.max_raster_width, + max_height: limits.max_raster_height, + max_pixels: limits.max_raster_pixels, + max_alloc_bytes: limits.max_raster_alloc_bytes, + }, + ) + .map_err(|error| Error::Decode(error.to_string()))?; + let (width, height) = rgba.dimensions(); + Ok(Imported::Raster(RasterImage { format, width, height, rgba: rgba.into_raw() })) +} + +fn path_is_finite(path: &BezPath) -> bool { + path.elements().iter().all(|element| { + let finite = |point: Point| point.x.is_finite() && point.y.is_finite(); + match *element { + PathEl::MoveTo(point) | PathEl::LineTo(point) => finite(point), + PathEl::QuadTo(a, b) => finite(a) && finite(b), + PathEl::CurveTo(a, b, c) => finite(a) && finite(b) && finite(c), + PathEl::ClosePath => true, + } + }) +} + +#[cfg(test)] +mod format_tests { + use super::*; + + #[test] + fn pdf_based_illustrator_is_routed_to_pdf_reader() { + let bytes = b"%PDF-1.7\n/AIPrivateData"; + assert_eq!(format_for("illustration.ai", bytes), Some(ImportFormat::Pdf)); + } +} diff --git a/crates/file-import/src/write.rs b/crates/file-import/src/write.rs new file mode 100644 index 000000000..676206282 --- /dev/null +++ b/crates/file-import/src/write.rs @@ -0,0 +1,447 @@ +//! Shared writer selection and serialization for neutral scenes and pixels. + +use kurbo::{BezPath, PathEl, Point}; + +use crate::{CAPABILITIES, Error, ImportFormat}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WriteFormat { + Svg, + Svgz, + Dxf, + Pdf, + Png, + Jpeg, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct OutputLayer { + /// Product-facing name. SVG stores it as `data-layer`. + pub name: String, + /// Already mapped/sanitized format name, supplied by the application adapter. + pub dxf_name: String, + pub visible: bool, + pub dxf_color_index: u8, + pub class: Option, + pub data_kind: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct OutputPath { + pub path: BezPath, + pub layer: usize, + pub color_rgb: [u8; 3], + pub stroke_width_mm: f64, + pub class: Option, + pub data_kind: Option, + /// Close each open contour for formats that require closed cutting operations. + pub close_open_contours: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct OutputScene { + pub width_mm: f64, + pub height_mm: f64, + pub view_box: [f64; 4], + pub layers: Vec, + pub paths: Vec, +} + +/// One page for the shared PDF path writer. Coordinates and stroke widths are millimetres. +#[derive(Debug, Clone, PartialEq)] +pub struct PdfPage { + pub width_mm: f64, + pub height_mm: f64, + pub view_box: [f64; 4], + pub paths: Vec, +} + +/// A PDF path with either a fill or a stroke. `None` fills the path; `Some(width)` strokes it. +#[derive(Debug, Clone, PartialEq)] +pub struct PdfPath { + pub path: BezPath, + pub color_rgb: [u8; 3], + pub stroke_width_mm: Option, +} + +/// Match a target extension to the centralized writer registry. +pub fn writer_format_for_extension(extension: &str) -> Option { + let family = writer_family_for_extension(extension)?; + let extension = extension.trim_start_matches('.'); + Some(match family { + ImportFormat::Svg => WriteFormat::Svg, + ImportFormat::Svgz => WriteFormat::Svgz, + ImportFormat::Dxf => WriteFormat::Dxf, + ImportFormat::Pdf => WriteFormat::Pdf, + ImportFormat::Raster if extension.eq_ignore_ascii_case("png") => WriteFormat::Png, + ImportFormat::Raster => WriteFormat::Jpeg, + ImportFormat::Eps => return None, + }) +} + +/// Product handler family for a writer extension. +pub fn writer_family_for_extension(extension: &str) -> Option { + let extension = extension.trim_start_matches('.'); + for capability in CAPABILITIES { + if !capability.write_extensions.iter().any(|candidate| candidate.eq_ignore_ascii_case(extension)) { + continue; + } + return Some(capability.format); + } + None +} + +/// Vector extensions the writer registry supports. +pub fn supported_vector_write_extensions() -> Vec<&'static str> { + CAPABILITIES.iter().filter(|capability| capability.vector).flat_map(|capability| capability.write_extensions.iter().copied()).collect() +} + +/// Serialize a neutral vector scene as SVG, SVGZ, DXF, or PDF according to the extension. +pub fn write_vector(extension: &str, scene: &OutputScene) -> Result, Error> { + match writer_format_for_extension(extension).ok_or_else(|| Error::Write(format!("no writer for .{extension}")))? { + WriteFormat::Svg => write_svg(scene).map(String::into_bytes), + WriteFormat::Svgz => write_svg(scene).map(|svg| craft_svg::svgz::compress(svg.as_bytes())), + WriteFormat::Dxf => write_dxf(scene).map(String::into_bytes), + WriteFormat::Pdf => write_pdf(scene), + WriteFormat::Png | WriteFormat::Jpeg => Err(Error::Write("raster output requires pixels".into())), + } +} + +/// Encode an RGBA image using the writer selected by its extension. +pub fn write_raster(extension: &str, width: u32, height: u32, rgba: &[u8], jpeg_quality: u8) -> Result, Error> { + let pixels = craft_raster_codecs::common::Pixels::from_raw(width, height, rgba.to_vec()).ok_or(Error::InvalidGeometry)?; + match writer_format_for_extension(extension).ok_or_else(|| Error::Write(format!("no writer for .{extension}")))? { + WriteFormat::Png => craft_raster_codecs::common::encode_png(&pixels).map_err(|error| Error::Write(error.to_string())), + WriteFormat::Jpeg => craft_raster_codecs::common::encode_jpeg(&pixels, jpeg_quality).map_err(|error| Error::Write(error.to_string())), + _ => Err(Error::Write("vector output requires paths".into())), + } +} + +fn write_svg(scene: &OutputScene) -> Result { + validate_scene(scene)?; + let view_scale = (scene.width_mm / scene.view_box[2]).min(scene.height_mm / scene.view_box[3]); + if !(view_scale.is_finite() && view_scale > 0.0) { + return Err(Error::InvalidGeometry); + } + let paths_by_layer = paths_by_layer(scene); + let elements = scene + .layers + .iter() + .enumerate() + .map(|(layer_index, layer)| { + let paths = paths_by_layer[layer_index] + .iter() + .map(|path| { + let color = path.color_rgb; + let mut attributes = vec![ + craft_svg::write::Attribute::text("fill", "none"), + craft_svg::write::Attribute::text("stroke", format!("#{:02x}{:02x}{:02x}", color[0], color[1], color[2])), + craft_svg::write::Attribute::text("stroke-width", format_float(path.stroke_width_mm / view_scale)), + ]; + if let Some(class) = &path.class { + attributes.push(craft_svg::write::Attribute::text("class", class.clone())); + } + if let Some(data_kind) = &path.data_kind { + attributes.push(craft_svg::write::Attribute::text("data-kind", data_kind.clone())); + } + craft_svg::write::Element::Path { attributes, path: path.path.clone() } + }) + .collect::>(); + let mut attributes = vec![ + craft_svg::write::Attribute::text("data-layer", layer.name.clone()), + craft_svg::write::Attribute::text("style", if layer.visible { "display:inline" } else { "display:none" }), + ]; + if let Some(class) = &layer.class { + attributes.push(craft_svg::write::Attribute::text("class", class.clone())); + } + if let Some(data_kind) = &layer.data_kind { + attributes.push(craft_svg::write::Attribute::text("data-kind", data_kind.clone())); + } + craft_svg::write::Element::Group { attributes, children: paths } + }) + .collect(); + Ok(craft_svg::write::Scene { width_mm: scene.width_mm, height_mm: scene.height_mm, view_box: scene.view_box, elements }.write()) +} + +fn write_pdf(scene: &OutputScene) -> Result, Error> { + validate_scene(scene)?; + let paths_by_layer = paths_by_layer(scene); + // Match SVG's painter order: layers in order, then paths in source order within each layer. + let paths = scene + .layers + .iter() + .enumerate() + .filter(|(_, layer)| layer.visible) + .flat_map(|(layer_index, _)| paths_by_layer[layer_index].iter().copied()) + .map(|path| PdfPath { path: path.path.clone(), color_rgb: path.color_rgb, stroke_width_mm: Some(path.stroke_width_mm) }) + .collect(); + write_pdf_pages(&[PdfPage { width_mm: scene.width_mm, height_mm: scene.height_mm, view_box: scene.view_box, paths }]) +} + +/// Group the neutral paths once so writing does not rescan all paths for every layer. +fn paths_by_layer(scene: &OutputScene) -> Vec> { + let mut grouped: Vec> = (0..scene.layers.len()).map(|_| Vec::new()).collect(); + for path in &scene.paths { + if let Some(layer) = grouped.get_mut(path.layer) { + layer.push(path); + } + } + grouped +} + +/// Encode a neutral list of laid-out pages with vector paths as PDF. +pub fn write_pdf_pages(pages: &[PdfPage]) -> Result, Error> { + use craft_pdf::write::{Metadata, Writer, backend}; + const PT_PER_MM: f64 = 72.0 / 25.4; + craft_pdf::write::guard(|| { + let settings = backend::SerializeSettings { + configuration: craft_pdf::write::configuration(backend::configure::PdfVersion::Pdf14, None)?, + ..Default::default() + }; + let mut writer = Writer::new(settings, Metadata::default()); + for source_page in pages { + let [view_x, view_y, view_width, view_height] = source_page.view_box; + if !(source_page.width_mm.is_finite() + && source_page.height_mm.is_finite() + && source_page.width_mm > 0.0 + && source_page.height_mm > 0.0 + && view_x.is_finite() + && view_y.is_finite() + && view_width.is_finite() + && view_height.is_finite() + && view_width > 0.0 + && view_height > 0.0) + { + return Err(Error::InvalidGeometry); + } + let width = source_page.width_mm * PT_PER_MM; + let height = source_page.height_mm * PT_PER_MM; + if !(width.is_finite() + && height.is_finite() + && width > 0.0 + && height > 0.0 + && width <= f64::from(f32::MAX) + && height <= f64::from(f32::MAX)) + { + return Err(Error::Write("page dimensions are outside the PDF range".into())); + } + let page_settings = backend::page::PageSettings::from_wh(width as f32, height as f32) + .ok_or_else(|| Error::Write("page dimensions are not finite or positive".into()))?; + let mut page = writer.document_mut().start_page_with(page_settings); + let mut surface = page.surface(); + let view_scale = (source_page.width_mm / view_width).min(source_page.height_mm / view_height); + let offset_x = (source_page.width_mm - view_width * view_scale) / 2.0; + let offset_y = (source_page.height_mm - view_height * view_scale) / 2.0; + if !(view_scale.is_finite() && view_scale > 0.0 && offset_x.is_finite() && offset_y.is_finite()) { + return Err(Error::InvalidGeometry); + } + for source in &source_page.paths { + let mut path = backend::geom::PathBuilder::new(); + for element in source.path.elements() { + let point = |p: Point| -> Result<(f32, f32), Error> { + let x = ((p.x - view_x) * view_scale + offset_x) * PT_PER_MM; + let y = ((p.y - view_y) * view_scale + offset_y) * PT_PER_MM; + if !(p.x.is_finite() + && p.y.is_finite() + && x.is_finite() + && y.is_finite() + && x.abs() <= f64::from(f32::MAX) + && y.abs() <= f64::from(f32::MAX)) + { + return Err(Error::Write("path coordinate is outside the PDF range".into())); + } + Ok((x as f32, y as f32)) + }; + match *element { + PathEl::MoveTo(p) => { + let (x, y) = point(p)?; + path.move_to(x, y); + } + PathEl::LineTo(p) => { + let (x, y) = point(p)?; + path.line_to(x, y); + } + PathEl::QuadTo(a, b) => { + let (x1, y1) = point(a)?; + let (x, y) = point(b)?; + path.quad_to(x1, y1, x, y); + } + PathEl::CurveTo(a, b, c) => { + let (x1, y1) = point(a)?; + let (x2, y2) = point(b)?; + let (x, y) = point(c)?; + path.cubic_to(x1, y1, x2, y2, x, y); + } + PathEl::ClosePath => path.close(), + } + } + if let Some(path) = path.finish() { + let color = backend::color::rgb::Color::new(source.color_rgb[0], source.color_rgb[1], source.color_rgb[2]); + match source.stroke_width_mm { + Some(width_mm) => { + let width_pt = width_mm * PT_PER_MM; + if !(width_mm.is_finite() && width_mm > 0.0 && width_pt.is_finite() && width_pt <= f64::from(f32::MAX)) { + return Err(Error::Write("stroke width must be finite and positive".into())); + } + surface.set_fill(None); + surface.set_stroke(Some(backend::paint::Stroke { paint: color.into(), width: width_pt as f32, ..Default::default() })); + } + None => { + surface.set_stroke(None); + surface.set_fill(Some(backend::paint::Fill { paint: color.into(), ..Default::default() })); + } + } + surface.draw_path(&path); + } + } + surface.finish(); + page.finish(); + } + writer.finish().map_err(|error| Error::Write(error.to_string())) + }) +} + +fn write_dxf(scene: &OutputScene) -> Result { + validate_scene(scene)?; + let mut drawing = craft_dxf::model::write::Drawing::default(); + drawing.format = craft_dxf::model::write::Format::R14; + drawing.insunits = 4; + drawing.metric = true; + drawing.extents = [0.0, 0.0, scene.width_mm, scene.height_mm]; + drawing.limits = drawing.extents; + for layer in &scene.layers { + drawing.layers.push(craft_dxf::model::Layer { + handle: None, + name: layer.dxf_name.clone(), + color: craft_dxf::model::Color::Index(layer.dxf_color_index), + on: layer.visible, + frozen: false, + vp_freeze_new: false, + locked: false, + plot: true, + linetype: "Continuous".into(), + lineweight: craft_dxf::model::Lineweight::Default, + plot_style: None, + transparency: craft_dxf::model::Transparency::ByLayer, + description: None, + }); + } + for output in &scene.paths { + let Some(layer) = scene.layers.get(output.layer) else { + return Err(Error::InvalidGeometry); + }; + let view_scale = (scene.width_mm / scene.view_box[2]).min(scene.height_mm / scene.view_box[3]); + let offset_x = (scene.width_mm - scene.view_box[2] * view_scale) / 2.0; + let offset_y = (scene.height_mm - scene.view_box[3] * view_scale) / 2.0; + let mut page_path = output.path.clone(); + page_path.apply_affine(kurbo::Affine::new([ + view_scale, + 0.0, + 0.0, + view_scale, + offset_x - scene.view_box[0] * view_scale, + offset_y - scene.view_box[1] * view_scale, + ])); + for (points, closed) in flatten(&page_path)? { + if points.len() < 2 { + continue; + } + let mut vertices = Vec::with_capacity(points.len()); + for point in points { + if !(point.x.is_finite() && point.y.is_finite()) { + return Err(Error::InvalidGeometry); + } + vertices.push(craft_dxf::model::LwVertex { x: point.x, y: scene.height_mm - point.y, ..Default::default() }); + } + drawing.entities.push(craft_dxf::model::Entity { + common: craft_dxf::model::Common { + handle: None, + owner: None, + layer: layer.dxf_name.clone(), + linetype: None, + color: craft_dxf::model::Color::ByLayer, + lineweight: craft_dxf::model::Lineweight::ByLayer, + ltscale: 1.0, + visible: true, + paper_space: false, + transparency: craft_dxf::model::Transparency::ByLayer, + thickness: 0.0, + extrusion: [0.0, 0.0, 1.0], + plot_style: None, + }, + kind: craft_dxf::model::EntityKind::LwPolyline(craft_dxf::model::LwPolyline { + vertices, + closed: closed || output.close_open_contours, + plinegen: false, + const_width: 0.0, + elevation: 0.0, + }), + }); + } + } + let (tags, skipped) = drawing.tags(); + if skipped > 0 { + return Err(Error::Write(format!("DXF writer skipped {skipped} entities"))); + } + Ok(craft_dxf::write_ascii(&tags)) +} + +fn flatten(path: &BezPath) -> Result, bool)>, Error> { + const MAX_POINTS: usize = 2_000_000; + let mut contours: Vec<(Vec, bool)> = Vec::new(); + let mut count = 0usize; + vectorcraft_geom::flatten(path.iter(), 0.05, |element| { + count = count.saturating_add(1); + if count > MAX_POINTS { + return; + } + match element { + PathEl::MoveTo(point) => contours.push((vec![point], false)), + PathEl::LineTo(point) => { + if let Some((points, _)) = contours.last_mut() { + points.push(point); + } + } + PathEl::ClosePath => { + if let Some((_, closed)) = contours.last_mut() { + *closed = true; + } + } + PathEl::QuadTo(..) | PathEl::CurveTo(..) => {} + } + }); + if count > MAX_POINTS { + return Err(Error::Write("path exceeds the DXF flattening limit".into())); + } + Ok(contours) +} + +fn validate_scene(scene: &OutputScene) -> Result<(), Error> { + if !(scene.width_mm.is_finite() && scene.height_mm.is_finite() && scene.width_mm > 0.0 && scene.height_mm > 0.0) { + return Err(Error::InvalidGeometry); + } + if !(scene.view_box.iter().all(|value| value.is_finite()) && scene.view_box[2] > 0.0 && scene.view_box[3] > 0.0) + || scene.paths.len() > crate::MAX_SHAPES + || scene.paths.iter().any(|path| { + path.layer >= scene.layers.len() + || !(path.stroke_width_mm.is_finite() && path.stroke_width_mm > 0.0) + || path.path.elements().iter().any(|element| match *element { + PathEl::MoveTo(point) | PathEl::LineTo(point) => !point_is_finite(point), + PathEl::QuadTo(a, b) => !point_is_finite(a) || !point_is_finite(b), + PathEl::CurveTo(a, b, c) => !point_is_finite(a) || !point_is_finite(b) || !point_is_finite(c), + PathEl::ClosePath => false, + }) + }) + { + return Err(Error::InvalidGeometry); + } + Ok(()) +} + +fn point_is_finite(point: Point) -> bool { + point.x.is_finite() && point.y.is_finite() +} + +fn format_float(value: f64) -> String { + value.to_string() +} diff --git a/crates/gif/Cargo.toml b/crates/gif/Cargo.toml index ac2b599d5..909d9b605 100644 --- a/crates/gif/Cargo.toml +++ b/crates/gif/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-gif" -description = "GIF block reader: the logical screen, each frame's position, delay and transparency, the loop count and colour tables, without decompressing pixels." +description = "GIF block reader, bounded frame decoder and animation writer." version.workspace = true edition.workspace = true license.workspace = true @@ -15,8 +15,8 @@ workspace = true frames = ["dep:image"] [dependencies] +gif = "0.14" image = { version = "0.25", default-features = false, features = ["gif"], optional = true } [dev-dependencies] -# Writes the animated test files the scan is checked against; not a product dependency. image = { version = "0.25", default-features = false, features = ["gif"] } diff --git a/crates/gif/src/frames.rs b/crates/gif/src/frames.rs index fdaec81b7..12ae37dda 100644 --- a/crates/gif/src/frames.rs +++ b/crates/gif/src/frames.rs @@ -22,13 +22,18 @@ pub struct FrameLimits { pub max_bytes: u64, /// Largest canvas (logical screen) in bytes at 4 bytes a pixel. Default 512 MiB. pub max_canvas_bytes: u64, + /// Combined decoder working-allocation budget. The persistent canvas reserves budget before + /// the frame buffer. `None` uses twice `max_canvas_bytes`, matching the decoder's working + /// buffer allowance. Set this when an application has a tighter allocator budget. Default + /// `None`. + pub max_decode_bytes: Option, /// Merge a frame identical to the one before into it (its delay added). Default off. pub merge_identical: bool, } impl Default for FrameLimits { fn default() -> Self { - FrameLimits { max_frames: 100_000, max_bytes: 1 << 30, max_canvas_bytes: 512 << 20, merge_identical: false } + FrameLimits { max_frames: 100_000, max_bytes: 1 << 30, max_canvas_bytes: 512 << 20, max_decode_bytes: None, merge_identical: false } } } @@ -87,12 +92,27 @@ impl std::error::Error for FrameError {} /// Decodes the frames of a GIF. pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result { - let info = crate::scan(bytes, 1).ok_or_else(|| FrameError::Malformed("not a GIF".into()))?; + if limits.max_frames == 0 { + return Err(FrameError::LimitExceeded("the frame limit is zero".into())); + } + let inspect_limit = limits.max_frames.saturating_add(1); + let info = crate::scan(bytes, inspect_limit).ok_or_else(|| FrameError::Malformed("not a GIF".into()))?; + let has_more = if info.frames.len() > limits.max_frames { + Some(true) + } else if info.complete { + Some(false) + } else { + None + }; let (width, height) = (u32::from(info.width), u32::from(info.height)); let canvas = u64::from(width) * u64::from(height) * 4; if canvas > limits.max_canvas_bytes { return Err(FrameError::LimitExceeded(format!("a {width}x{height} canvas is over {} bytes", limits.max_canvas_bytes))); } + let max_decode_bytes = limits.max_decode_bytes.unwrap_or_else(|| limits.max_canvas_bytes.saturating_mul(2)); + if canvas > max_decode_bytes { + return Err(FrameError::LimitExceeded(format!("a {width}x{height} canvas is over the {max_decode_bytes} byte decode-allocation limit"))); + } // The decoder sets up the whole logical screen before the first frame: the file must back it. if !crate::plausible(info.bytes_to_back(4, 1 << 28), bytes.len(), 1 << 14) { return Err(FrameError::LimitExceeded(format!("a {} byte file cannot hold a {width}x{height} picture", bytes.len()))); @@ -100,21 +120,43 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result Option> { + let mut decoder = GifDecoder::new(Cursor::new(bytes)).ok()?; + decoder.icc_profile().ok().flatten() } /// Keeps the frames `frames` yields under `limits`. -fn collect(width: u32, height: u32, frames: image::Frames<'_>, limits: &FrameLimits) -> Result { +fn collect( + width: u32, + height: u32, + frames: impl Iterator>, + limits: &FrameLimits, + has_more: Option, +) -> Result { let frame_bytes = u64::from(width) * u64::from(height) * 4; let mut out: Vec = Vec::new(); + let mut decoded_frames = 0; let mut stop = Stop::End; for frame in frames { + decoded_frames += 1; let frame = match frame { Ok(f) => f, - Err(e) if out.is_empty() => return Err(FrameError::Malformed(e.to_string())), + Err(e) if out.is_empty() => { + let message = e.to_string(); + return Err(if matches!(e, image::ImageError::Limits(_)) { + FrameError::LimitExceeded(message) + } else { + FrameError::Malformed(message) + }); + } Err(e) => { stop = Stop::Damaged(e.to_string()); break; @@ -140,6 +182,13 @@ fn collect(width: u32, height: u32, frames: image::Frames<'_>, limits: &FrameLim } out.push(AnimFrame { rgba, delay_ms }); } + if stop == Stop::End && decoded_frames == limits.max_frames { + stop = match has_more { + Some(true) => Stop::FrameLimit, + Some(false) => Stop::End, + None => Stop::Damaged("could not inspect the blocks after the kept frames".into()), + }; + } if out.is_empty() { return Err(FrameError::Malformed("no frame".into())); } @@ -150,6 +199,7 @@ fn collect(width: u32, height: u32, frames: image::Frames<'_>, limits: &FrameLim mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use super::*; + use std::borrow::Cow; /// An animated GIF of solid 3 × 2 frames, written by `image`: (red level, delay in hundredths). fn gif(frames: &[(u8, u32)]) -> Vec { @@ -176,6 +226,63 @@ mod tests { assert!(a.frames.iter().all(|f| f.rgba.len() == 24)); } + #[test] + fn first_frame_pixel_count_tracks_the_lzw_output() { + let mut gif = Vec::new(); + let pixels = image::RgbaImage::from_fn(640, 480, |x, y| image::Rgba([(x / 4) as u8, (y / 3) as u8, 17, 255])); + image::codecs::gif::GifEncoder::new_with_speed(&mut gif, 30).encode_frame(image::Frame::new(pixels)).unwrap(); + assert_eq!(crate::first_frame_decoded_pixels(&gif), Some(640 * 480)); + assert_eq!(crate::first_frame_decoded_pixels(b"not a gif"), None); + } + + #[test] + fn reads_the_optional_icc_application_extension() { + let mut bytes = gif(&[(10, 5)]); + let frame = crate::scan(&bytes, 1).unwrap().frames[0]; + let profile = [1, 2, 3, 4, 5]; + let mut extension = vec![0x21, 0xff, 0x0b]; + extension.extend_from_slice(b"ICCRGBG1012"); + extension.push(profile.len() as u8); + extension.extend_from_slice(&profile); + extension.push(0); + bytes.splice(frame.offset..frame.offset, extension); + + assert_eq!(icc_profile(&bytes).as_deref(), Some(profile.as_slice())); + } + + #[test] + fn partial_frames_composite_and_background_disposal_is_applied() { + let palette = [0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 255, 0]; + let (mut bytes, first, second, third) = (Vec::new(), [1], [2], [0]); + { + let mut encoder = gif::Encoder::new(&mut bytes, 2, 1, &palette).unwrap(); + let a = gif::Frame { width: 1, height: 1, buffer: Cow::Borrowed(&first), transparent: Some(0), delay: 2, ..gif::Frame::default() }; + encoder.write_frame(&a).unwrap(); + + let b = gif::Frame { + left: 1, + width: 1, + height: 1, + buffer: Cow::Borrowed(&second), + transparent: Some(0), + dispose: gif::DisposalMethod::Background, + delay: 3, + ..gif::Frame::default() + }; + encoder.write_frame(&b).unwrap(); + + let c = gif::Frame { width: 1, height: 1, buffer: Cow::Borrowed(&third), transparent: Some(0), delay: 4, ..gif::Frame::default() }; + encoder.write_frame(&c).unwrap(); + } + + let a = read_frames(&bytes, &FrameLimits::default()).unwrap(); + assert_eq!((a.width, a.height, a.stop), (2, 1, Stop::End)); + assert_eq!(a.frames.iter().map(|f| f.delay_ms).collect::>(), [20, 30, 40]); + assert_eq!(a.frames[0].rgba, [255, 0, 0, 255, 0, 0, 0, 0]); + assert_eq!(a.frames[1].rgba, [255, 0, 0, 255, 0, 0, 255, 255]); + assert_eq!(a.frames[2].rgba, [255, 0, 0, 255, 0, 0, 0, 0]); + } + #[test] fn identical_frames_merge_when_asked() { let bytes = gif(&[(10, 5), (10, 7), (200, 1), (200, 1), (10, 2)]); @@ -195,6 +302,46 @@ mod tests { assert_eq!((a.frames.len(), a.stop), (2, Stop::ByteLimit)); assert!(matches!(read_frames(&bytes, &FrameLimits { max_canvas_bytes: 23, ..FrameLimits::default() }), Err(FrameError::LimitExceeded(_)))); assert!(read_frames(&bytes, &FrameLimits { max_canvas_bytes: 24, ..FrameLimits::default() }).is_ok()); + // Canvas and frame buffer each need 24 bytes; decoder allocations share this budget. + assert!(matches!( + read_frames(&bytes, &FrameLimits { max_decode_bytes: Some(24), ..FrameLimits::default() }), + Err(FrameError::LimitExceeded(_)) + )); + assert!(read_frames(&bytes, &FrameLimits { max_decode_bytes: Some(1), ..FrameLimits::default() }).is_err()); + assert!( + matches!(read_frames(&bytes, &FrameLimits { max_frames: 0, ..FrameLimits::default() }), Err(FrameError::LimitExceeded(message)) if message.contains("frame limit is zero")) + ); + } + + #[test] + fn merged_frames_still_report_the_decode_frame_limit() { + let bytes = gif(&[(10, 5), (10, 7), (200, 1)]); + let animation = read_frames(&bytes, &FrameLimits { max_frames: 2, merge_identical: true, ..FrameLimits::default() }).unwrap(); + assert_eq!(reds(&animation), [(10, 120)]); + assert_eq!(animation.stop, Stop::FrameLimit); + } + + #[test] + fn a_frame_beyond_the_limit_is_not_decoded_or_allocated() { + let mut bytes = gif(&[(1, 1), (2, 1)]); + let info = crate::scan(&bytes, 2).unwrap(); + let second = info.frames[1]; + // The first frame and canvas fit in 24 bytes; the second frame must not be decoded. + bytes[second.offset + 5..second.offset + 9].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]); + let limits = FrameLimits { max_frames: 1, max_bytes: 24, max_canvas_bytes: 24, max_decode_bytes: Some(1024), ..FrameLimits::default() }; + let animation = read_frames(&bytes, &limits).unwrap(); + assert_eq!(animation.frames.len(), 1); + assert_eq!(animation.stop, Stop::FrameLimit); + } + + #[test] + fn decoder_allocation_limit_is_not_reported_as_malformed_input() { + let mut bytes = gif(&[(1, 1)]); + // The logical screen is 1×1, while the frame data still decodes to 3×2. The canvas + // passes the eight-byte decode cap, but the decoder's frame allocation does not. + bytes[6..10].copy_from_slice(&[1, 0, 1, 0]); + let limits = FrameLimits { max_canvas_bytes: 4, max_decode_bytes: Some(8), ..FrameLimits::default() }; + assert!(matches!(read_frames(&bytes, &limits), Err(FrameError::LimitExceeded(_)))); } #[test] diff --git a/crates/gif/src/lib.rs b/crates/gif/src/lib.rs index 33cdad53c..db9e830ab 100644 --- a/crates/gif/src/lib.rs +++ b/crates/gif/src/lib.rs @@ -1,7 +1,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -//! The blocks of a GIF, read without decompressing any pixels (GIF89a specification: Logical -//! Screen Descriptor, Global and Local Color Tables, Graphic Control Extension, Application -//! Extension, Image Descriptor). +//! GIF reading and writing. The block reader reads without decompressing pixels (GIF89a +//! specification: Logical Screen Descriptor, Global and Local Color Tables, Graphic Control +//! Extension, Application Extension, Image Descriptor). //! //! [`scan`] walks the file once and reports what an importer needs before it decodes anything: //! the logical screen size, every frame's position, size, delay and transparent colour, whether @@ -12,6 +12,10 @@ //! //! With feature `frames`, [`frames::read_frames`] decodes every frame through the `image` crate's //! GIF decoder, after the checks [`scan`] makes possible, with bounded memory. +//! [`write::animation`] writes full-canvas RGBA8 animation frames with GIF palette quantization, +//! timing, loop and disposal metadata. Parallel producers can quantize frames with +//! [`write::prepare_frame`] and pass the compact results to +//! [`write::AnimationWriter::write_prepared_frame`]. //! //! Input is treated as hostile: every read is bounds-checked, and the number of frames recorded //! is capped by the caller. @@ -20,6 +24,8 @@ pub mod frames; #[cfg(test)] mod tests; +/// GIF image and animation encoding. +pub mod write; /// One frame (image descriptor) of a GIF. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -188,6 +194,94 @@ pub fn palette(bytes: &[u8]) -> Option<(Vec<[u8; 3]>, Option)> { Some((colors, transparent)) } +/// Counts pixels emitted by the first GIF frame's LZW stream, up to its declared area. +/// Returns `None` when the first frame or its LZW minimum code size is unreadable. This reads +/// code lengths only; it does not allocate or materialize pixel values. +pub fn first_frame_decoded_pixels(bytes: &[u8]) -> Option { + let parsed = scan(bytes, 1)?; + let frame = parsed.frames.first()?; + let packed = *bytes.get(frame.offset.checked_add(9)?)?; + let table_bytes = table_len(packed); + let code_size_at = frame.offset.checked_add(10)?.checked_add(table_bytes)?; + let min_size = *bytes.get(code_size_at)?; + if !(1..=11).contains(&min_size) { + return None; + } + let clear = 1usize << min_size; + let end = clear + 1; + let max = u64::from(frame.width) * u64::from(frame.height); + let mut lengths = [1u16; 4096]; + let (mut width, mut next, mut previous) = (u32::from(min_size) + 1, end + 1, None::); + let (mut bits, mut held, mut pixels) = (0u32, 0u32, 0u64); + let mut pos = code_size_at.checked_add(1)?; + while let Some(&length) = bytes.get(pos) { + let start = pos.checked_add(1)?; + pos = start.checked_add(usize::from(length))?; + if length == 0 { + break; + } + for &byte in bytes.get(start..pos.min(bytes.len()))? { + bits |= u32::from(byte) << held; + held += 8; + while held >= width { + let code = (bits & ((1 << width) - 1)) as usize; + bits >>= width; + held -= width; + if code == clear { + (width, next, previous) = (u32::from(min_size) + 1, end + 1, None); + continue; + } + let string_len = match previous { + _ if code == end => return Some(pixels), + None if code < clear => 1, + Some(_) if code < next => lengths.get(code).copied().unwrap_or(1), + Some(prev) if code == next => lengths.get(prev).copied().unwrap_or(1).saturating_add(1), + _ => return Some(pixels), + }; + let defined_len = previous.map(|prev| lengths.get(prev).copied().unwrap_or(1).saturating_add(1)); + if let Some(defined_len) = defined_len + && let Some(slot) = lengths.get_mut(next) + { + *slot = defined_len; + next += 1; + if next == 1 << width && width < 12 { + width += 1; + } + } + previous = Some(code); + pixels = pixels.saturating_add(u64::from(string_len)); + if pixels >= max { + return Some(max); + } + } + } + } + Some(pixels) +} + +/// Counts compressed image-data bytes in the first frame's sub-blocks, excluding its LZW code-size +/// byte and all later blocks. A truncated final sub-block contributes only the bytes present. +pub fn first_frame_compressed_bytes(bytes: &[u8]) -> Option { + let parsed = scan(bytes, 1)?; + let frame = parsed.frames.first()?; + let packed = *bytes.get(frame.offset.checked_add(9)?)?; + let mut pos = frame.offset.checked_add(10)?.checked_add(table_len(packed))?.checked_add(1)?; + let mut total = 0usize; + loop { + let length = usize::from(*bytes.get(pos)?); + pos = pos.checked_add(1)?; + if length == 0 { + return Some(total); + } + let end = pos.checked_add(length)?; + total = total.checked_add(end.min(bytes.len()).saturating_sub(pos))?; + if end > bytes.len() { + return Some(total); + } + pos = end; + } +} + /// Whether a file of `file_len` bytes can plausibly hold `declared_bytes` of decoded picture: at /// most `max_ratio` decoded bytes for each file byte, plus 1 MiB. A decoder that sets up the whole /// logical screen before it reads a frame should be given only files that pass this. diff --git a/crates/gif/src/tests.rs b/crates/gif/src/tests.rs index a75743b19..6a776eb50 100644 --- a/crates/gif/src/tests.rs +++ b/crates/gif/src/tests.rs @@ -54,6 +54,15 @@ fn animated(delays_cs: &[u32], repeat: Option) -> Ve out } +#[test] +fn first_frame_compressed_bytes_exclude_extensions_after_the_image_data() { + let mut bytes = gif(&[[1, 2, 3], [4, 5, 6]], None, None); + assert_eq!(first_frame_compressed_bytes(&bytes), Some(2)); + bytes.splice(bytes.len() - 1..bytes.len() - 1, [0x21, 0xFE, 1, b'x', 0]); + assert_eq!(first_frame_compressed_bytes(&bytes), Some(2)); + assert_eq!(first_frame_compressed_bytes(b"not a gif"), None); +} + #[test] fn the_first_frames_table_and_transparent_entry() { let g = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]]; diff --git a/crates/gif/src/write.rs b/crates/gif/src/write.rs new file mode 100644 index 000000000..259aa78f1 --- /dev/null +++ b/crates/gif/src/write.rs @@ -0,0 +1,343 @@ +//! Bounded-shape GIF animation writing from full-canvas RGBA8 frames. +//! +//! Timing and frame production remain the caller's choice. This module owns the GIF-specific +//! encoding rules: palette quantization, loop extension, transparency and disposal metadata. + +use std::io::Write; + +/// Disposal behavior to write for every frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Disposal { + /// Leave the encoded disposal method unspecified (`0`). + Unspecified, + /// Do not dispose of the current frame (`1`), matching `gif::Frame`'s default. + Keep, + /// Restore the logical screen to the background after each frame. + Background, +} + +/// GIF encoding options. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Options { + /// Loop indefinitely. `false` uses `gif`'s `Finite(0)` setting (no repeat extension). + pub loop_forever: bool, + /// Disposal metadata to attach to each frame. + pub disposal: Disposal, + /// `gif` encoder palette quality (`1` is best, `30` is fastest). Default 10. + pub speed: i32, +} + +impl Default for Options { + fn default() -> Self { + Self { loop_forever: true, disposal: Disposal::Keep, speed: 10 } + } +} + +/// A full-canvas, straight-alpha RGBA8 frame. Delays are centiseconds, as stored in GIF. +#[derive(Debug, Clone, Copy)] +pub struct RgbaFrame<'a> { + pub pixels: &'a [u8], + pub delay_cs: u16, +} + +/// Why the requested animation could not be encoded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + Dimensions { width: u32, height: u32 }, + InvalidSpeed(i32), + FrameLength { index: usize, actual: usize, expected: usize }, + PreparedDimensions { actual_width: u16, actual_height: u16, expected_width: u16, expected_height: u16 }, + NoFrames, + Encode(String), +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Dimensions { width, height } => write!(f, "GIF dimensions {width}x{height} exceed the 65535 px limit"), + Self::InvalidSpeed(speed) => write!(f, "GIF quantization speed {speed} is outside 1–30"), + Self::FrameLength { index, actual, expected } => write!(f, "GIF frame {index} has {actual} bytes; expected {expected} RGBA bytes"), + Self::PreparedDimensions { actual_width, actual_height, expected_width, expected_height } => { + write!(f, "prepared GIF frame is {actual_width}x{actual_height}; expected {expected_width}x{expected_height}") + } + Self::NoFrames => f.write_str("GIF animation has no frames"), + Self::Encode(message) => write!(f, "GIF encode failed: {message}"), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(error: gif::EncodingError) -> Self { + Self::Encode(error.to_string()) + } +} + +/// A palette-quantized GIF frame ready for a writer. +/// +/// Prepare these inside a parallel render batch to keep only indexed frame data in the batch, +/// rather than retaining every source RGBA buffer until the writer reaches it. +pub struct PreparedFrame { + width: u16, + height: u16, + frame: gif::Frame<'static>, +} + +/// Quantize one owned full-canvas RGBA8 frame using the GIF encoder's speed setting. +pub fn prepare_frame(width: u32, height: u32, mut pixels: Vec, speed: i32) -> Result { + let (width, height) = dimensions(width, height)?; + if !(1..=30).contains(&speed) { + return Err(Error::InvalidSpeed(speed)); + } + let expected = rgba_len(width, height)?; + if pixels.len() != expected { + return Err(Error::FrameLength { index: 0, actual: pixels.len(), expected }); + } + let frame = gif::Frame::from_rgba_speed(width, height, &mut pixels, speed); + Ok(PreparedFrame { width, height, frame }) +} + +fn rgba_len(width: u16, height: u16) -> Result { + usize::from(width) + .checked_mul(usize::from(height)) + .and_then(|pixels| pixels.checked_mul(4)) + .ok_or(Error::Dimensions { width: u32::from(width), height: u32::from(height) }) +} + +fn dimensions(width: u32, height: u32) -> Result<(u16, u16), Error> { + if width == 0 || height == 0 || width > u32::from(u16::MAX) || height > u32::from(u16::MAX) { + return Err(Error::Dimensions { width, height }); + } + Ok((width as u16, height as u16)) +} + +/// A writer that appends encoded frames to an output incrementally. +pub struct AnimationWriter { + encoder: gif::Encoder, + width: u16, + height: u16, + options: Options, + frames_written: usize, +} + +impl AnimationWriter { + /// Start an animation on `output`; subsequent calls write one frame at a time. + pub fn new(output: W, width: u32, height: u32, options: Options) -> Result { + if width == 0 || height == 0 || width > u32::from(u16::MAX) || height > u32::from(u16::MAX) { + return Err(Error::Dimensions { width, height }); + } + if !(1..=30).contains(&options.speed) { + return Err(Error::InvalidSpeed(options.speed)); + } + let width = width as u16; + let height = height as u16; + let mut encoder = gif::Encoder::new(output, width, height, &[]).map_err(Error::from)?; + encoder.set_repeat(if options.loop_forever { gif::Repeat::Infinite } else { gif::Repeat::Finite(0) }).map_err(Error::from)?; + Ok(Self { encoder, width, height, options, frames_written: 0 }) + } + + /// Encode and append one full-canvas RGBA8 frame. + pub fn write_frame(&mut self, frame: RgbaFrame<'_>) -> Result<(), Error> { + let expected = rgba_len(self.width, self.height)?; + if frame.pixels.len() != expected { + return Err(Error::FrameLength { index: self.frames_written, actual: frame.pixels.len(), expected }); + } + let prepared = + prepare_frame(u32::from(self.width), u32::from(self.height), frame.pixels.to_vec(), self.options.speed).map_err(|error| match error { + Error::FrameLength { actual, expected, .. } => Error::FrameLength { index: self.frames_written, actual, expected }, + error => error, + })?; + self.write_prepared_frame(prepared, frame.delay_cs) + } + + /// Append a previously quantized frame without copying its pixel buffer. + pub fn write_prepared_frame(&mut self, mut prepared: PreparedFrame, delay_cs: u16) -> Result<(), Error> { + if prepared.width != self.width || prepared.height != self.height { + return Err(Error::PreparedDimensions { + actual_width: prepared.width, + actual_height: prepared.height, + expected_width: self.width, + expected_height: self.height, + }); + } + prepared.frame.delay = delay_cs; + prepared.frame.dispose = match self.options.disposal { + Disposal::Unspecified => gif::DisposalMethod::Any, + Disposal::Keep => gif::DisposalMethod::Keep, + Disposal::Background => gif::DisposalMethod::Background, + }; + self.encoder.write_frame(&prepared.frame).map_err(Error::from)?; + self.frames_written = self.frames_written.saturating_add(1); + Ok(()) + } + + /// Finish the GIF and return the underlying output. + pub fn finish(self) -> Result { + self.encoder.into_inner().map_err(Error::from) + } +} + +/// Encode an animation into a complete GIF file. +/// +/// Every input frame must cover the whole canvas and contain exactly `width * height * 4` bytes. +/// At most one mutable frame copy is made at a time for the quantizer. This is intentionally a +/// streaming writer so callers can render and encode frames incrementally. +pub fn animation(width: u32, height: u32, frames: &[RgbaFrame<'_>], options: Options) -> Result, Error> { + if frames.is_empty() { + return Err(Error::NoFrames); + } + let mut writer = AnimationWriter::new(Vec::new(), width, height, options)?; + for frame in frames { + writer.write_frame(*frame)?; + } + writer.finish() +} + +/// Encode a single pre-quantized indexed-color frame as a GIF89a image. +/// +/// `palette` holds 1 to 256 RGB triplets; `indices` is `width * height` row-major palette indices. +/// When `interlaced` is true, rows are reordered into GIF's 4-pass interlaced order before writing. +pub fn encode_indexed( + width: u32, + height: u32, + palette: &[[u8; 3]], + indices: &[u8], + transparent: Option, + interlaced: bool, +) -> Result, Error> { + let (w, h) = dimensions(width, height)?; + let expected = usize::from(w) * usize::from(h); + if indices.len() != expected { + return Err(Error::FrameLength { index: 0, actual: indices.len(), expected }); + } + if palette.is_empty() || palette.len() > 256 { + return Err(Error::Encode("GIF palette must hold 1 to 256 entries".into())); + } + let flat_palette: Vec = palette.iter().flat_map(|c| *c).collect(); + let buffer = if interlaced { std::borrow::Cow::Owned(interlace(indices, usize::from(w))) } else { std::borrow::Cow::Borrowed(indices) }; + let mut enc = gif::Encoder::new(Vec::new(), w, h, &flat_palette).map_err(Error::from)?; + let frame = gif::Frame { width: w, height: h, buffer, transparent, interlaced, ..gif::Frame::default() }; + enc.write_frame(&frame).map_err(Error::from)?; + enc.into_inner().map_err(Error::from) +} + +/// The rows of a `width`-wide image in GIF's interlaced order: every 8th row from 0, every 8th +/// from 4, every 4th from 2, then every 2nd from 1. +fn interlace(px: &[u8], width: usize) -> Vec { + let rows: Vec<&[u8]> = px.chunks(width.max(1)).collect(); + [(0, 8), (4, 8), (2, 4), (1, 2)] + .into_iter() + .flat_map(|(start, step)| rows.iter().skip(start).step_by(step)) + .flat_map(|r| r.iter().copied()) + .collect() +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::{Disposal, Options, RgbaFrame, animation, prepare_frame}; + + #[test] + fn writes_repeat_delays_disposal_and_dimensions() { + let red = [255, 0, 0, 255]; + let blue = [0, 0, 255, 255]; + let bytes = animation( + 1, + 1, + &[RgbaFrame { pixels: &red, delay_cs: 4 }, RgbaFrame { pixels: &blue, delay_cs: 7 }], + Options { loop_forever: false, disposal: Disposal::Background, speed: 10 }, + ) + .unwrap(); + let info = crate::scan(&bytes, 4).unwrap(); + assert_eq!((info.width, info.height), (1, 1)); + assert_eq!(info.loop_count, None); + assert_eq!(info.frames.iter().map(|f| f.delay_cs).collect::>(), [4, 7]); + assert!(info.frames.iter().all(|f| f.disposal == 2)); + } + + #[test] + fn default_disposal_matches_gif_frame_default() { + let bytes = animation(1, 1, &[RgbaFrame { pixels: &[1, 2, 3, 255], delay_cs: 1 }], Options::default()).unwrap(); + let info = crate::scan(&bytes, 1).unwrap(); + assert_eq!(info.frames[0].disposal, 1); + } + + #[test] + fn rejects_dimensions_empty_animation_and_wrong_pixel_lengths() { + assert!(matches!(animation(0, 1, &[RgbaFrame { pixels: &[0; 4], delay_cs: 1 }], Options::default()), Err(super::Error::Dimensions { .. }))); + assert!(matches!(animation(1, 1, &[], Options::default()), Err(super::Error::NoFrames))); + assert!(matches!(animation(1, 1, &[RgbaFrame { pixels: &[0; 3], delay_cs: 1 }], Options::default()), Err(super::Error::FrameLength { .. }))); + assert!(matches!( + animation(1, 1, &[RgbaFrame { pixels: &[0; 4], delay_cs: 1 }], Options { speed: 0, ..Options::default() }), + Err(super::Error::InvalidSpeed(0)) + )); + assert!(matches!( + animation(1, 1, &[RgbaFrame { pixels: &[0; 4], delay_cs: 1 }, RgbaFrame { pixels: &[0; 3], delay_cs: 1 }], Options::default()), + Err(super::Error::FrameLength { index: 1, .. }) + )); + } + + #[test] + fn streaming_writer_preserves_empty_output_behavior() { + let bytes = super::AnimationWriter::new(Vec::new(), 1, 1, Options::default()).unwrap().finish().unwrap(); + assert!(bytes.starts_with(b"GIF89a")); + assert_eq!(bytes.last(), Some(&b';')); + } + + #[cfg(feature = "frames")] + #[test] + fn prepared_frames_stream_without_changing_decoded_pixels() { + let red = vec![255, 0, 0, 255]; + let blue = vec![0, 0, 255, 255]; + let mut writer = super::AnimationWriter::new(Vec::new(), 1, 1, Options::default()).unwrap(); + writer.write_prepared_frame(prepare_frame(1, 1, red, 10).unwrap(), 3).unwrap(); + writer.write_prepared_frame(prepare_frame(1, 1, blue, 10).unwrap(), 5).unwrap(); + let bytes = writer.finish().unwrap(); + let expected = animation( + 1, + 1, + &[RgbaFrame { pixels: &[255, 0, 0, 255], delay_cs: 3 }, RgbaFrame { pixels: &[0, 0, 255, 255], delay_cs: 5 }], + Options::default(), + ) + .unwrap(); + assert_eq!(bytes, expected); + let decoded = crate::frames::read_frames(&bytes, &crate::frames::FrameLimits::default()).unwrap(); + assert_eq!(decoded.frames[0].rgba, [255, 0, 0, 255]); + assert_eq!(decoded.frames[1].rgba, [0, 0, 255, 255]); + assert_eq!(decoded.frames.iter().map(|frame| frame.delay_ms).collect::>(), [30, 50]); + } + + #[test] + fn rejects_prepared_frames_with_other_dimensions() { + let prepared = prepare_frame(2, 1, vec![0; 8], 10).unwrap(); + let mut writer = super::AnimationWriter::new(Vec::new(), 1, 1, Options::default()).unwrap(); + assert!(matches!(writer.write_prepared_frame(prepared, 1), Err(super::Error::PreparedDimensions { .. }))); + } + + #[cfg(feature = "frames")] + #[test] + fn encoded_frames_decode_to_the_requested_colors() { + let red = [255, 0, 0, 255]; + let blue = [0, 0, 255, 255]; + let bytes = + animation(1, 1, &[RgbaFrame { pixels: &red, delay_cs: 1 }, RgbaFrame { pixels: &blue, delay_cs: 2 }], Options::default()).unwrap(); + let decoded = crate::frames::read_frames(&bytes, &crate::frames::FrameLimits::default()).unwrap(); + assert_eq!(decoded.frames[0].rgba, red); + assert_eq!(decoded.frames[1].rgba, blue); + } + + #[test] + fn encode_indexed_validates_and_writes_gif() { + let palette = [[255, 0, 0], [0, 255, 0]]; + let indices = [0u8, 1, 1, 0, 0, 1, 1, 0, 0]; + let bytes = super::encode_indexed(3, 3, &palette, &indices, Some(1), true).unwrap(); + let info = crate::scan(&bytes, 4).unwrap(); + assert_eq!((info.width, info.height), (3, 3)); + assert_eq!(info.frames.len(), 1); + assert_eq!(info.frames[0].transparent, Some(1)); + assert!(super::encode_indexed(2, 2, &[], &[0; 4], None, false).is_err()); + assert!(super::encode_indexed(2, 2, &palette, &[0; 3], None, false).is_err()); + } +} diff --git a/crates/hdr/src/lib.rs b/crates/hdr/src/lib.rs index 9d7d3272c..d46232306 100644 --- a/crates/hdr/src/lib.rs +++ b/crates/hdr/src/lib.rs @@ -11,7 +11,9 @@ //! //! Input is treated as hostile: the header length and the picture size are capped by [`Limits`], //! and every scan line is validated before the float picture is allocated, so a short file cannot -//! ask for a large allocation. +//! ask for a large allocation. Whatever the limits, no buffer is requested past the target's +//! largest allocation (`isize::MAX` bytes), so raised limits on a 32-bit target such as `wasm32` +//! give [`Error::LimitExceeded`] instead of a panic. #[cfg(test)] mod tests; @@ -42,6 +44,7 @@ pub type Result = std::result::Result; #[non_exhaustive] pub struct Limits { /// Most pixels (width × height) a picture may have; each takes 12 bytes decoded. Default 2^26. + /// A picture over the target's largest allocation is refused at any setting. pub max_pixels: u64, /// Longest header read, in bytes (real ones are a few hundred). Default 64 KiB. pub max_header: usize, @@ -62,6 +65,27 @@ pub struct Picture { pub rgb: Vec, } +/// The largest allocation in bytes that a `Vec` or `String` can make on the target. +const MAX_ALLOC_BYTES: u64 = isize::MAX as u64; + +/// Bytes taken by `count` elements of `element_bytes` each, or `None` when the count overflows `u64`. +fn checked_byte_len(count: u64, element_bytes: usize) -> Option { + count.checked_mul(element_bytes as u64) +} + +/// `count` as a length when `count` elements of `element_bytes` each fit in `max_alloc_bytes`. +fn alloc_len(count: u64, element_bytes: usize, max_alloc_bytes: u64) -> Option { + checked_byte_len(count, element_bytes).filter(|&bytes| bytes <= max_alloc_bytes).and_then(|_| usize::try_from(count).ok()) +} + +/// Bytes of `String::from_utf8_lossy(bytes)`: each invalid sequence becomes one U+FFFD (3 bytes). +fn lossy_len(bytes: &[u8]) -> Option { + bytes.utf8_chunks().try_fold(0u64, |n, chunk| { + let invalid = if chunk.invalid().is_empty() { 0 } else { '\u{FFFD}'.len_utf8() }; + n.checked_add(chunk.valid().len() as u64)?.checked_add(invalid as u64) + }) +} + /// Whether `bytes` starts like a Radiance picture. pub fn sniff(bytes: &[u8]) -> bool { bytes.starts_with(b"#?RADIANCE") || bytes.starts_with(b"#?RGBE") @@ -158,6 +182,11 @@ fn scanline(b: &[u8], pos: &mut usize, line: &mut [[u8; 4]]) -> Result<()> { /// Decodes a Radiance picture to linear float RGB, top row first. pub fn decode(b: &[u8], limits: &Limits) -> Result { + decode_within(b, limits, MAX_ALLOC_BYTES) +} + +/// [`decode`] with `max_alloc_bytes` as the largest allocation the target allows. +fn decode_within(b: &[u8], limits: &Limits, max_alloc_bytes: u64) -> Result { if !sniff(b) { return Err(Error::NotHdr); } @@ -166,7 +195,11 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { let line = |pos: &mut usize| -> Result { let rest = b.get(*pos..).ok_or(Error::Malformed("truncated header"))?; let end = rest.iter().take(limits.max_header).position(|&c| c == b'\n').ok_or(Error::Malformed("truncated header"))?; - let s = String::from_utf8_lossy(rest.get(..end).unwrap_or_default()).trim_end_matches('\r').to_string(); + let raw = rest.get(..end).unwrap_or_default(); + if lossy_len(raw).is_none_or(|n| n > max_alloc_bytes) { + return Err(Error::LimitExceeded("header length")); + } + let s = String::from_utf8_lossy(raw).trim_end_matches('\r').to_string(); *pos += end + 1; Ok(s) }; @@ -188,8 +221,9 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { } let res = line(&mut pos)?; let bad = Error::Malformed("bad resolution line"); - let t: Vec<&str> = res.split_whitespace().collect(); - let &[a1, n1, a2, n2] = t.as_slice().first_chunk::<4>().ok_or(bad.clone())?; + // Tokens after the fourth are ignored, so they are not collected. + let mut t = res.split_whitespace(); + let (Some(a1), Some(n1), Some(a2), Some(n2)) = (t.next(), t.next(), t.next(), t.next()) else { return Err(bad) }; let ((x1, p1), (x2, p2)) = (axis(a1).ok_or(bad.clone())?, axis(a2).ok_or(bad.clone())?); if x1 == x2 { return Err(Error::Malformed("resolution line names one axis twice")); @@ -205,6 +239,10 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { if pixels > limits.max_pixels { return Err(Error::LimitExceeded("pixel count")); } + // One scan line of RGBE pixels and the float picture, each within the target's largest allocation. + let scan_len = alloc_len(u64::from(if x1 { height } else { width }), size_of::<[u8; 4]>(), max_alloc_bytes); + let rgb_len = pixels.checked_mul(3).and_then(|floats| alloc_len(floats, size_of::(), max_alloc_bytes)); + let (Some(scan_len), Some(total)) = (scan_len, rgb_len) else { return Err(Error::LimitExceeded("pixel count")) }; // A scan line takes at least a few bits of file, so a header cannot ask for more than the data has. if (b.len().saturating_sub(pos) as u64).saturating_mul(4096) < pixels { return Err(Error::Malformed("truncated pixel data")); @@ -212,12 +250,11 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { // Validate every encoded scan line before allocating the float picture: a short file could // otherwise ask for the whole limit of zeroed pixels and only then fail on its first line. let pixel_data = pos; - let mut scan = vec![[0u8; 4]; n2]; + let mut scan = vec![[0u8; 4]; scan_len]; for _ in 0..n1 { scanline(b, &mut pos, &mut scan)?; } - let total = w.checked_mul(h).and_then(|n| n.checked_mul(3)).ok_or(Error::LimitExceeded("pixel count"))?; let mut rgb = vec![0f32; total]; pos = pixel_data; for i in 0..n1 { diff --git a/crates/hdr/src/tests.rs b/crates/hdr/src/tests.rs index 7e40454b1..576a8db3f 100644 --- a/crates/hdr/src/tests.rs +++ b/crates/hdr/src/tests.rs @@ -142,3 +142,57 @@ fn limits_are_checked_before_allocating() { assert_eq!(decode(&long, &Limits { max_header: 8, ..Limits::default() }), Err(Error::Malformed("truncated header"))); assert_eq!((Limits::default().max_pixels, Limits::default().max_header), (1 << 26, 64 << 10)); } + +/// `isize::MAX` on a 32-bit target such as `wasm32`. +const BOUND_32: u64 = i32::MAX as u64; + +#[test] +fn buffer_lengths_respect_target_isize_bound() { + // A scan line of RGBE pixels, 4 bytes each. + assert_eq!(alloc_len(536_870_911, 4, BOUND_32), Some(536_870_911)); + assert_eq!(alloc_len(536_870_912, 4, BOUND_32), None); + assert_eq!(alloc_len(u64::from(u32::MAX), 4, BOUND_32), None); + // The float picture: 3 floats of 4 bytes a pixel. + assert_eq!(alloc_len(178_956_970 * 3, 4, BOUND_32), Some(178_956_970 * 3)); + assert_eq!(alloc_len(178_956_971 * 3, 4, BOUND_32), None); + // The default pixel limit fits a 32-bit target. + assert_eq!(alloc_len(Limits::default().max_pixels * 3, 4, BOUND_32), Some(3 << 26)); + assert_eq!(checked_byte_len(u64::MAX, 4), None); + assert_eq!(alloc_len(u64::MAX, 1, MAX_ALLOC_BYTES), None); +} + +#[test] +fn raised_pixel_limit_stops_at_the_target_bound() { + let open = Limits { max_pixels: u64::MAX, ..Limits::default() }; + // 2 × 2 needs an 8-byte scan line and a 48-byte float picture. + let ok = file("-Y 2 +X 2", &[0; 16]); + assert!(decode_within(&ok, &open, 48).is_ok()); + assert_eq!(decode_within(&ok, &open, 47), Err(Error::LimitExceeded("pixel count"))); + // A 1 × 536,870,912 picture is past the 32-bit bound in both buffers; refused before + // anything is allocated, ahead of the scan-line validation. + let wide = file("-Y 1 +X 536870912", &[0; 131_072]); + assert_eq!(decode_within(&wide, &open, BOUND_32), Err(Error::LimitExceeded("pixel count"))); + // 178,956,971 one-pixel scan lines fit the scan buffer but not the float picture. + let tall = file("-Y 178956971 +X 1", &[0; 43_692]); + assert_eq!(decode_within(&tall, &open, BOUND_32), Err(Error::LimitExceeded("pixel count"))); +} + +#[test] +fn header_lines_are_measured_after_lossy_conversion() { + // `#` and ten bytes that are not UTF-8: 11 bytes in the file, 31 as text. + let mut f = b"#?RADIANCE\n#".to_vec(); + f.extend_from_slice(&[0xff; 10]); + f.extend_from_slice(b"\n\n-Y 1 +X 1\n\0\0\0\0"); + assert_eq!(lossy_len(&f[11..22]), Some(31)); + assert!(decode_within(&f, &Limits::default(), 31).is_ok()); + assert_eq!(decode_within(&f, &Limits::default(), 30), Err(Error::LimitExceeded("header length"))); + assert_eq!(lossy_len(b"ok \xe2\x82"), Some(6)); + assert_eq!(lossy_len(b""), Some(0)); +} + +#[test] +fn resolution_tokens_after_the_fourth_are_ignored() { + let f = dec(&file("-Y 1 +X 1 a b c d e f", &[0; 4])).unwrap(); + assert_eq!((f.width, f.height), (1, 1)); + assert_eq!(dec(&file("-Y 1 +X", &[0; 4])), Err(Error::Malformed("bad resolution line"))); +} diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rs index 07405a959..3b2cf45f7 100644 --- a/crates/idml/src/lib.rs +++ b/crates/idml/src/lib.rs @@ -39,7 +39,10 @@ pub mod value; pub use craft_xml::{El, Local, Node}; pub use package::{Document, Limits, Package, write_package}; -pub use part::{CONTAINER_XML, Props, designmap_xml, parse_part, part_root, part_xml, prop, with_props, xml_limits}; +pub use part::{ + CONTAINER_XML, Props, designmap_include, designmap_root, designmap_xml, designmap_xml_with_pi, parse_part, part_root, part_xml, prop, with_props, + xml_limits, +}; /// The IDML package mimetype (content of the first, stored `mimetype` entry). pub const MIMETYPE: &str = "application/vnd.adobe.indesign-idml-package"; @@ -48,6 +51,14 @@ pub const DOM_VERSION: &str = "16.0"; /// The namespace of the `idPkg` prefix. pub const PACKAGING_NS: &str = "http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"; +/// Writes the bounded XMP metadata packet used by an IDML package. Dates are already normalized +/// ISO-8601 values supplied by the caller; this function owns the XML vocabulary and envelope. +pub fn xmp_metadata(create_date: &str, modify_date: &str) -> String { + format!( + "\n\n \n \n {create_date}\n {modify_date}\n \n \n\n" + ) +} + /// Why a package was not read or not written. #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] pub enum Error { diff --git a/crates/idml/src/model/document.rs b/crates/idml/src/model/document.rs new file mode 100644 index 000000000..830b95a3f --- /dev/null +++ b/crates/idml/src/model/document.rs @@ -0,0 +1,525 @@ +//! The `Document` tree: root values and included designmap nodes in source order. + +use craft_xml::El; + +use super::{AlternatingFillValues, AlternatingStrokeValues, Spread, Story, StrokeValues, Values}; + +/// One IDML table-of-contents style entry before document style names are resolved. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TocStyleEntryValues { + pub style: Option, + pub level: Option, + pub page_number_position: Option, + pub separator: Option, + pub entry_style: Option, + pub page_number_style: Option, + pub separator_style: Option, + pub sort: Option, +} + +/// An IDML table-of-contents style and its entry grammar. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TocStyleValues { + pub self_id: Option, + pub title: Option, + pub title_style: Option, + pub create_bookmarks: Option, + pub entries: Vec, +} + +/// Date-based IDML text variable kinds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextDateKind { + Creation, + Modification, + Output, +} + +/// Semantically classified `TextVariable` definitions before caller model mapping. +#[derive(Clone, Debug, PartialEq)] +pub enum TextVariableKind { + CustomText { text: String }, + LastPageNumber { section: bool }, + ChapterNumber, + FileName { extension: bool }, + Date { kind: TextDateKind, format: String }, + RunningHeader { style: String, character: bool, last_on_page: bool }, + CrossReference { page_number: bool }, + Imported { variable_type: String, settings_element: String, settings: Vec<(String, String)> }, +} + +/// Parsed values from an IDML `TextVariable` definition. +#[derive(Clone, Debug, PartialEq)] +pub struct TextVariableValues { + pub self_id: Option, + pub name: String, + pub before: String, + pub after: String, + pub kind: TextVariableKind, +} + +/// A recognized IDML cross-reference format building block. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CrossReferenceBuildingBlock { + CustomText(String), + FullParagraph, + ParagraphText, + ParagraphNumber, + PageNumber, + BookmarkName, + ChapterNumber, + FileName, + PartialParagraph { delimiter: String, include_delimiter: bool }, +} + +/// Parsed IDML cross-reference format definition. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CrossReferenceFormatValues { + pub self_id: Option, + pub name: String, + pub blocks: Vec, +} + +impl CrossReferenceFormatValues { + /// Reads a `CrossReferenceFormat` and recognizes its building-block grammar. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let mut result = + Self { self_id: values.self_id().map(str::to_owned), name: values.get("Name").unwrap_or("Format").to_owned(), blocks: Vec::new() }; + for block in el.elements().filter(|child| child.local() == "BuildingBlock") { + let values = Values::of(block); + let text = |key: &str| values.get(key).filter(|value| *value != "$ID/").unwrap_or("").to_owned(); + let parsed = match values.get("BlockType").unwrap_or("") { + "CustomStringBuildingBlock" => Some(CrossReferenceBuildingBlock::CustomText(text("CustomText"))), + "FullParagraphBuildingBlock" => Some(CrossReferenceBuildingBlock::FullParagraph), + "ParagraphTextBuildingBlock" => Some(CrossReferenceBuildingBlock::ParagraphText), + "ParagraphNumberBuildingBlock" => Some(CrossReferenceBuildingBlock::ParagraphNumber), + "PageNumberBuildingBlock" => Some(CrossReferenceBuildingBlock::PageNumber), + "BookmarkNameBuildingBlock" => Some(CrossReferenceBuildingBlock::BookmarkName), + "ChapterNumberBuildingBlock" => Some(CrossReferenceBuildingBlock::ChapterNumber), + "FileNameBuildingBlock" => Some(CrossReferenceBuildingBlock::FileName), + "PartialParagraphBuildingBlock" => Some(CrossReferenceBuildingBlock::PartialParagraph { + delimiter: text("AppliedDelimiter"), + include_delimiter: values.get("IncludeDelimiter") == Some("true"), + }), + _ => None, + }; + if let Some(parsed) = parsed { + result.blocks.push(parsed); + } + } + result + } + + /// Builds an IDML cross-reference format from DesignCraft's stored token definition. + pub fn to_el(self_id: &str, name: &str, definition: &str) -> El { + let mut root = El::new("CrossReferenceFormat").with_attr("Self", self_id).with_attr("Name", name).with_attr("AppliedCharacterStyle", "n"); + let mut index = 0; + let mut block = |root: &mut El, kind: &str, text: &str, delimiter: &str, include: bool| { + root.push( + El::new("BuildingBlock") + .with_attr("Self", format!("{self_id}BuildingBlock{index}")) + .with_attr("BlockType", kind) + .with_attr("AppliedCharacterStyle", "n") + .with_attr("CustomText", if text.is_empty() { "$ID/" } else { text }) + .with_attr("AppliedDelimiter", if delimiter.is_empty() { "$ID/" } else { delimiter }) + .with_attr("IncludeDelimiter", if include { "true" } else { "false" }), + ); + index += 1; + }; + let mut rest = definition; + while let Some(start) = rest.find('<') { + let Some(end) = rest[start..].find('>') else { break }; + if start > 0 { + block(&mut root, "CustomStringBuildingBlock", &rest[..start], "", false); + } + let tag = rest[start + 1..start + end].trim().trim_end_matches('/').trim(); + let attr = + |key: &str| tag.find(&format!("{key}=\"")).and_then(|position| tag[position + key.len() + 2..].split('"').next()).unwrap_or(""); + match tag.split_whitespace().next().unwrap_or("") { + "fullPara" => block(&mut root, "FullParagraphBuildingBlock", "", "", false), + "paraText" => block(&mut root, "ParagraphTextBuildingBlock", "", "", false), + "paraNum" => block(&mut root, "ParagraphNumberBuildingBlock", "", "", false), + "pageNum" => block(&mut root, "PageNumberBuildingBlock", "", "", false), + "txtAnchrName" => block(&mut root, "BookmarkNameBuildingBlock", "", "", false), + "chapNum" => block(&mut root, "ChapterNumberBuildingBlock", "", "", false), + "fileName" => block(&mut root, "FileNameBuildingBlock", "", "", false), + "partialPara" => block(&mut root, "PartialParagraphBuildingBlock", "", attr("delim"), attr("includeDelim") == "true"), + _ => block(&mut root, "CustomStringBuildingBlock", &rest[start..start + end + 1], "", false), + } + rest = &rest[start + end + 1..]; + } + if !rest.is_empty() { + block(&mut root, "CustomStringBuildingBlock", rest, "", false); + } + root + } +} + +/// Parsed EPUB document-splitting preference. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EpubSplitValues { + pub break_document: bool, + pub paragraph_style: Option, +} + +/// Parsed IDML condition metadata. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ConditionValues { + pub self_id: Option, + pub name: Option, + pub indicator_rgb: Option<[u8; 3]>, + pub visible: bool, +} + +impl ConditionValues { + /// Reads condition fields and its optional three-channel indicator color. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let rgb: Vec = values + .get("IndicatorColor") + .unwrap_or("") + .split_whitespace() + .filter_map(|value| value.parse::().ok()) + .map(|value| value.clamp(0.0, 255.0) as u8) + .collect(); + Self { + self_id: values.self_id().map(str::to_owned), + name: values.get("Name").map(str::to_owned), + indicator_rgb: (rgb.len() == 3).then(|| [rgb[0], rgb[1], rgb[2]]), + visible: values.get("Visible") != Some("false"), + } + } +} + +/// Parsed IDML numbering-list metadata. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NumberingListValues { + pub name: String, + pub continue_across_stories: bool, +} + +/// Parsed cell-style assignments that are independent of DesignCraft's style resolution. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CellStyleValues { + pub self_id: Option, + pub name: Option, + pub based_on: Option, + pub fill: Option, + pub fill_tint: Option, + pub insets: [Option; 4], + pub vertical_justification: Option, + pub first_baseline: Option, + pub first_baseline_min: Option, + pub paragraph_style: Option, + pub edge_strokes: [StrokeValues; 4], +} + +impl CellStyleValues { + /// Reads the cell-style value assignments and supports the older inset property names. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let inset = |modern, legacy| values.num(modern).or_else(|| values.num(legacy)).map(|v| v.max(0.0)); + Self { + self_id: values.self_id().map(str::to_owned), + name: values.name().map(str::to_owned), + based_on: values.prop("BasedOn"), + fill: values.prop("FillColor"), + fill_tint: values.num("FillTint"), + insets: [ + inset("TextTopInset", "TopInset"), + inset("TextLeftInset", "LeftInset"), + inset("TextBottomInset", "BottomInset"), + inset("TextRightInset", "RightInset"), + ], + vertical_justification: values.get("VerticalJustification").map(str::to_owned), + first_baseline: values.get("FirstBaselineOffset").map(str::to_owned), + first_baseline_min: values.num("MinimumFirstBaselineOffset").filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 8640.0)), + paragraph_style: values.get("AppliedParagraphStyle").map(str::to_owned), + edge_strokes: ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"].map(|edge| values.stroke_values(edge)), + } + } +} + +/// Parsed table-style assignments that are independent of DesignCraft's style resolution. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableStyleValues { + pub name: Option, + pub based_on: Option, + pub header_cell_style: Option, + pub body_cell_style: Option, + pub footer_cell_style: Option, + pub left_column_cell_style: Option, + pub right_column_cell_style: Option, + pub header_same_as_body: Option, + pub footer_same_as_body: Option, + pub left_column_same_as_body: Option, + pub right_column_same_as_body: Option, + pub space_before: Option, + pub space_after: Option, + pub border_strokes: [StrokeValues; 4], + pub row_fills: AlternatingFillValues, + pub column_fills: AlternatingFillValues, + pub row_strokes: AlternatingStrokeValues, + pub column_strokes: AlternatingStrokeValues, +} + +impl TableStyleValues { + /// Reads table-style regions, inheritance, spacing, and region reuse values. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + name: values.name().map(str::to_owned), + based_on: values.prop("BasedOn"), + header_cell_style: values.get("HeaderRegionCellStyle").map(str::to_owned), + body_cell_style: values.get("BodyRegionCellStyle").map(str::to_owned), + footer_cell_style: values.get("FooterRegionCellStyle").map(str::to_owned), + left_column_cell_style: values.get("LeftColumnRegionCellStyle").map(str::to_owned), + right_column_cell_style: values.get("RightColumnRegionCellStyle").map(str::to_owned), + header_same_as_body: values.boolean("HeaderRegionSameAsBodyRegion"), + footer_same_as_body: values.boolean("FooterRegionSameAsBodyRegion"), + left_column_same_as_body: values.boolean("LeftColumnRegionSameAsBodyRegion"), + right_column_same_as_body: values.boolean("RightColumnRegionSameAsBodyRegion"), + space_before: values.num("SpaceBefore"), + space_after: values.num("SpaceAfter"), + border_strokes: ["TopBorder", "LeftBorder", "BottomBorder", "RightBorder"].map(|border| values.stroke_values(border)), + row_fills: values.alternating_fill_values("Row"), + column_fills: values.alternating_fill_values("Column"), + row_strokes: values.alternating_stroke_values("Row"), + column_strokes: values.alternating_stroke_values("Column"), + } + } +} + +impl NumberingListValues { + /// Reads a `NumberingList` element. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + name: values.get("Name").unwrap_or("").to_owned(), + continue_across_stories: values.boolean("ContinueNumbersAcrossStories") == Some(true), + } + } +} + +impl EpubSplitValues { + /// Reads an `EPubExportPreference` element. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { break_document: values.boolean("BreakDocument") == Some(true), paragraph_style: values.get("ParagraphStyleName").map(str::to_owned) } + } +} + +impl TextVariableValues { + /// Reads a `TextVariable` and its preference record. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let preference = el.elements().find(|child| child.name.ends_with("Preference")); + let attr = |key: &str| preference.and_then(|child| child.attr(key)).unwrap_or(""); + let variable_type = values.get("VariableType").unwrap_or(""); + let date = |kind| TextVariableKind::Date { kind, format: if attr("Format").is_empty() { "MM/dd/yy".into() } else { attr("Format").into() } }; + let kind = match variable_type { + "CustomTextType" => TextVariableKind::CustomText { text: attr("Contents").into() }, + "LastPageNumberType" => TextVariableKind::LastPageNumber { section: attr("Scope") == "SectionScope" }, + "ChapterNumberType" => TextVariableKind::ChapterNumber, + "FileNameType" if attr("IncludePath") != "true" => TextVariableKind::FileName { extension: attr("IncludeExtension") == "true" }, + "CreationDateType" => date(TextDateKind::Creation), + "ModificationDateType" => date(TextDateKind::Modification), + "OutputDateType" => date(TextDateKind::Output), + "MatchParagraphStyleType" | "MatchCharacterStyleType" => { + let character = variable_type == "MatchCharacterStyleType"; + let style = attr(if character { "AppliedCharacterStyle" } else { "AppliedParagraphStyle" }); + if style.is_empty() { + TextVariableKind::Imported { + variable_type: variable_type.into(), + settings_element: preference.map(|child| child.name.clone()).unwrap_or_default(), + settings: preference.map(|child| child.attrs.clone()).unwrap_or_default(), + } + } else { + TextVariableKind::RunningHeader { style: style.into(), character, last_on_page: attr("SearchStrategy") == "LastOnPage" } + } + } + _ if variable_type.starts_with("Xref") => TextVariableKind::CrossReference { page_number: variable_type == "XrefPageNumberType" }, + _ => TextVariableKind::Imported { + variable_type: variable_type.into(), + settings_element: preference.map(|child| child.name.clone()).unwrap_or_default(), + settings: preference.map(|child| child.attrs.clone()).unwrap_or_default(), + }, + }; + let text = |key: &str| preference.and_then(|child| child.attr(key)).or_else(|| values.get(key)).unwrap_or("").to_owned(); + Self { + self_id: values.self_id().map(str::to_owned), + name: values.get("Name").unwrap_or("").to_owned(), + before: text("TextBefore"), + after: text("TextAfter"), + kind, + } + } +} + +impl TocStyleValues { + /// Reads a `TOCStyle` element and its bounded `TOCStyleEntry` children. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let mut result = Self { + self_id: values.self_id().map(str::to_owned), + title: values.get("Title").map(str::to_owned), + title_style: values.get("TitleStyle").map(str::to_owned), + create_bookmarks: values.get("CreateBookmarks").or_else(|| values.get("CreatePdfBookmarks")).map(|value| value == "true"), + entries: Vec::new(), + }; + result.entries.extend(el.elements().filter(|entry| entry.local() == "TOCStyleEntry").take(64).map(|entry| { + let values = Values::of(entry); + TocStyleEntryValues { + style: values.get("Name").map(str::to_owned), + level: values.get("Level").and_then(|value| value.trim().parse().ok()), + page_number_position: values.get("PageNumberPosition").map(str::to_owned), + separator: values.get("Separator").map(str::to_owned), + entry_style: values.prop("FormatStyle"), + page_number_style: values.prop("PageNumberStyle"), + separator_style: values.prop("SeparatorStyle"), + sort: values.get("Sort").map(|value| value.trim() == "true"), + } + })); + result + } +} + +/// The top-level IDML elements consumed by document importers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TopLevelKind { + DocumentPreference, + TransparencyPreference, + TextPreference, + MarginPreference, + ViewPreference, + GridPreference, + PasteboardPreference, + CompositeFont, + KinsokuTable, + MojikumiTable, + FootnoteOption, + EpubExportPreference, + Layer, + CrossReferenceFormat, + Index, + TextVariable, + Story, + Hyperlink, + HyperlinkUrlDestination, + HyperlinkPageDestination, + HyperlinkPageItemSource, + HyperlinkOtherDestination, + MasterSpread, + Spread, + Section, + TocStyle, + Condition, + NumberingList, + StyleGroup, + Other, +} + +/// One included node in `designmap.xml`, classified by the shared IDML grammar. +#[derive(Clone, Debug, PartialEq)] +pub struct TopLevelNode { + pub kind: TopLevelKind, + data: TopLevelData, +} + +#[derive(Clone, Debug, PartialEq)] +enum TopLevelData { + Story(Story), + Spread(Spread), + Raw(El), +} + +impl TopLevelNode { + fn from_el(el: El) -> TopLevelNode { + let kind = top_level_kind(el.local()); + let data = match kind { + TopLevelKind::Story => TopLevelData::Story(Story::from_el(&el)), + TopLevelKind::Spread | TopLevelKind::MasterSpread => TopLevelData::Spread(Spread::from_el(&el)), + _ => TopLevelData::Raw(el), + }; + TopLevelNode { kind, data } + } + + /// The typed story or spread tree when this is one of those parts. + pub fn story(&self) -> Option<&Story> { + if let TopLevelData::Story(story) = &self.data { Some(story) } else { None } + } + + pub fn spread(&self) -> Option<&Spread> { + if let TopLevelData::Spread(spread) = &self.data { Some(spread) } else { None } + } + + /// The original element, reconstructed from the typed story/spread model where applicable. + pub fn to_el(&self) -> El { + match &self.data { + TopLevelData::Story(story) => story.to_el(), + TopLevelData::Spread(spread) => spread.to_el(), + TopLevelData::Raw(el) => el.clone(), + } + } + + pub fn values(&self) -> Values { + Values::of(&self.to_el()) + } +} + +/// A neutral view of an IDML package's designmap and included top-level parts. +#[derive(Clone, Debug, PartialEq)] +pub struct ModelDocument { + pub root: Values, + pub top: Vec, + pub warnings: Vec, + pub metadata: Option, +} + +impl ModelDocument { + /// Converts the shared bounded package reader's parsed document into typed document nodes. + pub fn from_package(document: crate::Document) -> ModelDocument { + ModelDocument { + root: Values::of(&document.root), + top: document.top.into_iter().map(TopLevelNode::from_el).collect(), + warnings: document.warnings, + metadata: document.metadata, + } + } +} + +fn top_level_kind(name: &str) -> TopLevelKind { + match name { + "DocumentPreference" => TopLevelKind::DocumentPreference, + "TransparencyPreference" => TopLevelKind::TransparencyPreference, + "TextPreference" => TopLevelKind::TextPreference, + "MarginPreference" => TopLevelKind::MarginPreference, + "ViewPreference" => TopLevelKind::ViewPreference, + "GridPreference" => TopLevelKind::GridPreference, + "PasteboardPreference" => TopLevelKind::PasteboardPreference, + "CompositeFont" => TopLevelKind::CompositeFont, + "KinsokuTable" => TopLevelKind::KinsokuTable, + "MojikumiTable" => TopLevelKind::MojikumiTable, + "FootnoteOption" => TopLevelKind::FootnoteOption, + "EPubExportPreference" => TopLevelKind::EpubExportPreference, + "Layer" => TopLevelKind::Layer, + "CrossReferenceFormat" => TopLevelKind::CrossReferenceFormat, + "Index" => TopLevelKind::Index, + "TextVariable" => TopLevelKind::TextVariable, + "Story" => TopLevelKind::Story, + "Hyperlink" => TopLevelKind::Hyperlink, + "HyperlinkURLDestination" => TopLevelKind::HyperlinkUrlDestination, + "HyperlinkPageDestination" => TopLevelKind::HyperlinkPageDestination, + "HyperlinkPageItemSource" => TopLevelKind::HyperlinkPageItemSource, + "MasterSpread" => TopLevelKind::MasterSpread, + "Spread" => TopLevelKind::Spread, + "Section" => TopLevelKind::Section, + "TOCStyle" => TopLevelKind::TocStyle, + "Condition" => TopLevelKind::Condition, + "NumberingList" => TopLevelKind::NumberingList, + name if name.starts_with("Root") && name.ends_with("StyleGroup") => TopLevelKind::StyleGroup, + name if name.starts_with("Hyperlink") && name.ends_with("Destination") => TopLevelKind::HyperlinkOtherDestination, + _ => TopLevelKind::Other, + } +} diff --git a/crates/idml/src/model/effects.rs b/crates/idml/src/model/effects.rs new file mode 100644 index 000000000..8f5fa9530 --- /dev/null +++ b/crates/idml/src/model/effects.rs @@ -0,0 +1,404 @@ +//! The IDML transparency/effect settings found on page items and object styles. + +use craft_xml::{El, Local, Node}; + +use super::Values; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DropShadowValues { + pub mode: Option, + pub x_offset: Option, + pub y_offset: Option, + pub color: Option, + pub opacity: Option, + pub size: Option, + pub spread: Option, + pub blend_mode: Option, +} + +impl DropShadowValues { + pub fn to_el(&self) -> El { + let mut element = El::new("DropShadowSetting"); + if let Some(value) = &self.mode { + element.set_attr("Mode", value); + } + for (key, value) in + [("XOffset", self.x_offset), ("YOffset", self.y_offset), ("Size", self.size), ("Spread", self.spread), ("Opacity", self.opacity)] + { + if let Some(value) = value { + element.set_attr(key, crate::value::num(value)); + } + } + if let Some(value) = &self.blend_mode { + element.set_attr("BlendMode", value); + } + if let Some(value) = &self.color { + element.set_attr("EffectColor", value); + } + element + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FeatherValues { + pub mode: Option, + pub width: Option, + pub choke_amount: Option, + pub corner_type: Option, +} + +impl FeatherValues { + pub fn to_el(&self) -> El { + let mut element = El::new("FeatherSetting"); + if let Some(value) = &self.mode { + element.set_attr("Mode", value); + } + for (key, value) in [("Width", self.width), ("ChokeAmount", self.choke_amount)] { + if let Some(value) = value { + element.set_attr(key, crate::value::num(value)); + } + } + if let Some(value) = &self.corner_type { + element.set_attr("CornerType", value); + } + element + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct OpacityStopValues { + pub location: Option, + pub opacity: Option, +} + +impl OpacityStopValues { + pub fn to_el(&self, self_id: &str, midpoint: bool) -> El { + let mut element = El::new("OpacityGradientStop").with_attr("Self", self_id); + if let Some(value) = self.opacity { + element.set_attr("Opacity", crate::value::num(value)); + } + if let Some(value) = self.location { + element.set_attr("Location", crate::value::num(value)); + } + if midpoint { + element.set_attr("Midpoint", "50"); + } + element + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct GradientFeatherValues { + pub applied: bool, + pub radial: bool, + pub angle: Option, + pub length: Option, + pub start: Option<[f64; 2]>, + pub stops: Vec, +} + +impl GradientFeatherValues { + pub fn to_el(&self, id_prefix: &str) -> El { + let mut element = + El::new("GradientFeatherSetting").with_attr("Applied", "true").with_attr("Type", if self.radial { "Radial" } else { "Linear" }); + if let Some(value) = self.angle { + element.set_attr("Angle", crate::value::num(value)); + } + if let Some(value) = self.length { + element.set_attr("Length", crate::value::num(value)); + } + if let Some([x, y]) = self.start { + element.set_attr("GradientStart", format!("{} {}", crate::value::num(x), crate::value::num(y))); + } + for (index, stop) in self.stops.iter().enumerate() { + let stop_id = format!("{id_prefix}TransparencySetting1GradientFeatherSetting1OpacityGradientStop{index}"); + element.push(stop.to_el(&stop_id, index > 0)); + } + element + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DirectionalFeatherValues { + pub applied: bool, + pub widths: [Option; 4], +} + +impl DirectionalFeatherValues { + pub fn to_el(&self) -> El { + let mut element = El::new("DirectionalFeatherSetting").with_attr("Applied", "true"); + for (key, value) in + [("LeftWidth", self.widths[1]), ("RightWidth", self.widths[3]), ("TopWidth", self.widths[0]), ("BottomWidth", self.widths[2])] + { + if let Some(value) = value { + element.set_attr(key, crate::value::num(value)); + } + } + element + } +} + +/// A typed view of an IDML `TransparencySetting` and its effect elements. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TransparencySetting { + pub blend_mode: Option, + pub opacity: Option, + pub drop_shadow: Option, + pub feather: Option, + pub gradient_feather: Option, + pub directional_feather: Option, +} + +impl TransparencySetting { + pub fn to_el(&self, id_prefix: &str) -> El { + let mut element = El::new("TransparencySetting"); + if self.blend_mode.is_some() || self.opacity.is_some() { + let mut blending = El::new("BlendingSetting"); + if let Some(value) = &self.blend_mode { + blending.set_attr("BlendMode", value); + } + if let Some(value) = self.opacity { + blending.set_attr("Opacity", crate::value::num(value)); + } + element.push(blending); + } + if let Some(effect) = &self.drop_shadow { + element.push(effect.to_el()); + } + if let Some(effect) = &self.feather { + element.push(effect.to_el()); + } + if let Some(effect) = &self.directional_feather { + element.push(effect.to_el()); + } + if let Some(effect) = &self.gradient_feather { + element.push(effect.to_el(id_prefix)); + } + element + } + + pub fn from_el(el: &El) -> Self { + let child = |name: &str| el.child(Local(name)); + let blending = child("BlendingSetting").map(Values::of); + let drop_shadow = child("DropShadowSetting").map(|el| { + let values = Values::of(el); + DropShadowValues { + mode: values.get("Mode").map(str::to_owned), + x_offset: values.num("XOffset"), + y_offset: values.num("YOffset"), + color: values.get("EffectColor").map(str::to_owned), + opacity: values.num("Opacity"), + size: values.num("Size"), + spread: values.num("Spread"), + blend_mode: values.get("BlendMode").map(str::to_owned), + } + }); + let feather = child("FeatherSetting").map(|el| { + let values = Values::of(el); + FeatherValues { + mode: values.get("Mode").map(str::to_owned), + width: values.num("Width"), + choke_amount: values.num("ChokeAmount"), + corner_type: values.get("CornerType").map(str::to_owned), + } + }); + let gradient_feather = child("GradientFeatherSetting").map(|el| { + let values = Values::of(el); + let start = values + .prop("GradientStart") + .and_then(|value| value.split_whitespace().map(|part| part.parse::().ok().filter(|n| n.is_finite())).collect::>>()) + .and_then(|parts| <[f64; 2]>::try_from(parts).ok()); + GradientFeatherValues { + applied: values.boolean("Applied") == Some(true), + radial: values.get("Type") == Some("Radial"), + angle: values.num("Angle"), + length: values.num("Length"), + start, + stops: el + .elements() + .filter(|stop| stop.local() == "OpacityGradientStop") + .map(|stop| { + let values = Values::of(stop); + OpacityStopValues { location: values.num("Location"), opacity: values.num("Opacity") } + }) + .collect(), + } + }); + let directional_feather = child("DirectionalFeatherSetting").map(|el| { + let values = Values::of(el); + DirectionalFeatherValues { + applied: values.boolean("Applied") == Some(true), + widths: [values.num("TopWidth"), values.num("LeftWidth"), values.num("BottomWidth"), values.num("RightWidth")], + } + }); + Self { + blend_mode: blending.as_ref().and_then(|values| values.get("BlendMode").map(str::to_owned)), + opacity: blending.as_ref().and_then(|values| values.num("Opacity")), + drop_shadow, + feather, + gradient_feather, + directional_feather, + } + } +} + +/// Resolved object-style chain used to inherit item-level IDML settings. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ObjectStyleStack { + chain: Vec, +} + +impl ObjectStyleStack { + /// Resolves a style reference and its `BasedOn` chain (nearest first, cycle-safe, max 16). + pub fn from_styles(styles: &[El], reference: Option<&str>, include_none: bool) -> Self { + let find = |reference: &str| { + styles.iter().find(|style| Values::of(style).self_id() == Some(reference)).or_else(|| { + let normalized = if reference.starts_with("ObjectStyle/") { + reference.to_owned() + } else { + format!("ObjectStyle/{}", crate::value::escape_id(reference.trim())) + }; + styles.iter().find(|style| Values::of(style).self_id() == Some(normalized.as_str())) + }) + }; + let mut chain = Vec::new(); + let mut next = reference.map(str::to_owned); + while let Some(id) = next { + let Some(style) = find(&id) else { break }; + let self_id = Values::of(style).self_id().map(str::to_owned); + if chain.len() >= 16 || self_id.as_deref().is_some_and(|id| chain.iter().any(|entry: &El| Values::of(entry).self_id() == Some(id))) { + break; + } + chain.push(style.clone()); + next = Values::of(style).prop("BasedOn").map(|base| { + let base = base.trim(); + if base.starts_with("ObjectStyle/") { base.to_owned() } else { format!("ObjectStyle/{}", crate::value::escape_id(base)) } + }); + } + if include_none + && !chain.iter().any(|style| Values::of(style).self_id() == Some("ObjectStyle/$ID/[None]")) + && let Some(none) = find("ObjectStyle/$ID/[None]") + { + chain.push(none.clone()); + } + Self { chain } + } + + /// The resolved style elements, nearest first. + pub fn styles(&self) -> &[El] { + &self.chain + } + + /// Merges an item's child over the corresponding elements in the resolved style chain. + pub fn merged_child(&self, item: &El, name: &str) -> Option { + let category = match name { + "TransparencySetting" => Some("ObjectStyleObjectEffectsCategorySettings"), + "StrokeTransparencySetting" => Some("ObjectStyleStrokeEffectsCategorySettings"), + "FillTransparencySetting" => Some("ObjectStyleFillEffectsCategorySettings"), + "ContentTransparencySetting" => Some("ObjectStyleContentEffectsCategorySettings"), + _ => None, + }; + let enabled = |effect: &str| { + let (Some(category), Some(flag)) = (category, effect_flag(effect)) else { return true }; + self.chain.iter().find_map(|style| style.child(Local(category)).and_then(|c| Values::of(c).get(flag).map(str::to_owned))).as_deref() + != Some("false") + }; + let mut result = None; + for style in self.chain.iter().rev() { + let Some(child) = style.child(Local(name)) else { continue }; + let mut child = child.clone(); + child.children.retain(|node| !matches!(node, Node::El(element) if !enabled(element.local()))); + match &mut result { + Some(current) => overlay(current, &child, 0), + None => result = Some(child), + } + } + if let Some(child) = item.child(Local(name)) { + match &mut result { + Some(current) => overlay(current, child, 0), + None => result = Some(child.clone()), + } + } + result + } + + /// Returns the drop-shadow and feather records enabled by the style's effect category. + pub fn enabled_shadow_feather(&self) -> Option { + let category = self.chain.iter().find_map(|style| style.child(Local("ObjectStyleObjectEffectsCategorySettings"))); + let setting = |name: &str| self.chain.iter().find_map(|style| style.child(Local("TransparencySetting"))?.child(Local(name)).cloned()); + let mut result = El::new("TransparencySetting"); + let mut any = false; + for (name, flag) in [("DropShadowSetting", "EnableDropShadow"), ("FeatherSetting", "EnableFeather")] { + let element = setting(name); + let on = match category { + Some(category) => Values::of(category).get(flag) == Some("true"), + None => element.as_ref().and_then(|element| Values::of(element).get("Mode").map(str::to_owned)).is_some_and(|mode| mode != "None"), + }; + any |= on; + if let (true, Some(element)) = (on, element) { + result.push(element); + } + } + any.then_some(result) + } +} + +fn effect_flag(effect: &str) -> Option<&'static str> { + Some(match effect { + "BlendingSetting" => "EnableTransparency", + "DropShadowSetting" => "EnableDropShadow", + "FeatherSetting" => "EnableFeather", + "InnerShadowSetting" => "EnableInnerShadow", + "OuterGlowSetting" => "EnableOuterGlow", + "InnerGlowSetting" => "EnableInnerGlow", + "BevelAndEmbossSetting" => "EnableBevelEmboss", + "SatinSetting" => "EnableSatin", + "DirectionalFeatherSetting" => "EnableDirectionalFeather", + "GradientFeatherSetting" => "EnableGradientFeather", + _ => return None, + }) +} + +fn overlay(base: &mut El, top: &El, depth: usize) { + if depth > 32 { + *base = top.clone(); + return; + } + for (key, value) in &top.attrs { + base.set_attr(key, value); + if let Some(Node::El(properties)) = base.children.iter_mut().find(|node| matches!(node, Node::El(el) if el.local() == "Properties")) { + properties.children.retain(|node| !matches!(node, Node::El(el) if el.local() == key)); + } + } + if let Some(properties) = top.child(Local("Properties")) { + let names: Vec<&str> = properties.elements().map(El::local).collect(); + base.attrs.retain(|(key, _)| !names.contains(&key.as_str())); + } + let has_text = top.children.iter().any(|node| matches!(node, Node::Text(text) | Node::CData(text) if !text.trim().is_empty())); + if has_text { + base.children.retain(|node| !matches!(node, Node::Text(_) | Node::CData(_))); + } + let mut seen: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for node in &top.children { + match node { + Node::El(child) => { + let index = seen.entry(child.local()).or_insert(0); + let slot = base + .children + .iter_mut() + .filter_map(|node| match node { + Node::El(el) if el.local() == child.local() => Some(el), + _ => None, + }) + .nth(*index); + *index += 1; + match slot { + Some(slot) => overlay(slot, child, depth + 1), + None => base.children.push(node.clone()), + } + } + Node::Text(_) | Node::CData(_) if has_text => base.children.push(node.clone()), + Node::Text(_) | Node::CData(_) | Node::Comment(_) | Node::Pi { .. } => {} + } + } +} diff --git a/crates/idml/src/model/geometry.rs b/crates/idml/src/model/geometry.rs index 02b00ddaf..804774291 100644 --- a/crates/idml/src/model/geometry.rs +++ b/crates/idml/src/model/geometry.rs @@ -5,6 +5,19 @@ use craft_xml::{El, Local}; use crate::value::{nums, point_str}; +/// Why a bounded path geometry was refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum PathGeometryError { + #[error("too many points")] + TooManyPoints, + #[error("point without an anchor")] + MissingAnchor, + #[error("malformed point")] + MalformedPoint, + #[error("non-finite point")] + NonFinitePoint, +} + /// Most points one geometry keeps by default; points past it are dropped. pub const MAX_PATH_POINTS: usize = 1_000_000; @@ -84,6 +97,45 @@ impl PathGeometry { PathGeometry { paths } } + /// Parse a path geometry without silently discarding malformed points, keeping at most + /// `max` point elements. Missing direction handles default to the anchor. + pub fn try_from_el_capped(pg: &El, max: usize) -> Result { + let point = |value: Option<&str>, required: bool| -> Result, PathGeometryError> { + let Some(value) = value else { + return if required { Err(PathGeometryError::MissingAnchor) } else { Ok(None) }; + }; + let mut nums = value.split_whitespace(); + let Some(x) = nums.next().and_then(|n| n.parse::().ok()) else { return Err(PathGeometryError::MalformedPoint) }; + let Some(y) = nums.next().and_then(|n| n.parse::().ok()) else { return Err(PathGeometryError::MalformedPoint) }; + if nums.next().is_some() { + return Err(PathGeometryError::MalformedPoint); + } + if !(x.is_finite() && y.is_finite()) { + return Err(PathGeometryError::NonFinitePoint); + } + Ok(Some([x, y])) + }; + let mut count = 0usize; + let mut paths = Vec::new(); + for geometry in pg.children(Local("GeometryPathType")) { + let mut points = Vec::new(); + if let Some(array) = geometry.child(Local("PathPointArray")) { + for el in array.children(Local("PathPointType")) { + count = count.saturating_add(1); + if count > max { + return Err(PathGeometryError::TooManyPoints); + } + let anchor = point(el.attr("Anchor"), true)?.ok_or(PathGeometryError::MissingAnchor)?; + let left = point(el.attr("LeftDirection"), false)?.unwrap_or(anchor); + let right = point(el.attr("RightDirection"), false)?.unwrap_or(anchor); + points.push(PathPoint { anchor, left, right }); + } + } + paths.push(SubPath { open: geometry.attr("PathOpen") == Some("true"), points }); + } + Ok(PathGeometry { paths }) + } + /// The `PathGeometry` element. pub fn to_el(&self) -> El { let mut pg = El::new("PathGeometry"); diff --git a/crates/idml/src/model/mod.rs b/crates/idml/src/model/mod.rs index 049f10175..a4560b22e 100644 --- a/crates/idml/src/model/mod.rs +++ b/crates/idml/src/model/mod.rs @@ -12,20 +12,44 @@ //! Nodes are built from the elements [`crate::Package::document`] gives ([`Spread::from_el`], //! [`spreads`]) and written back with `to_el`, then [`crate::part_xml`]. +mod document; +mod effects; mod geometry; +mod preferences; mod resources; mod spread; mod story; -pub use geometry::{MAX_PATH_POINTS, PathGeometry, PathPoint, SubPath}; -pub use resources::{ - ColorGroup, ColorSpace, GradientStop, StrokeStyle, StrokeStyleKind, Style, StyleGroup, StyleKind, StyleNode, Swatch, SwatchKind, color_groups, - named, preference, stroke_styles, style_groups, swatches, -}; -pub use spread::{Graphic, GraphicChild, GraphicKind, Guide, ItemChild, ItemKind, Link, Page, PageChild, PageItem, Spread, SpreadChild, spreads}; -pub use story::{Ace, CONTAINERS, Cell, Container, ContentPart, Range, Story, Table, TableChild, TextNode, stories}; - use craft_xml::{El, Local, Node}; +pub use document::{ + CellStyleValues, ConditionValues, CrossReferenceBuildingBlock, CrossReferenceFormatValues, EpubSplitValues, ModelDocument, NumberingListValues, + TableStyleValues, TextDateKind, TextVariableKind, TextVariableValues, TocStyleEntryValues, TocStyleValues, TopLevelKind, TopLevelNode, +}; +pub use effects::{ + DirectionalFeatherValues, DropShadowValues, FeatherValues, GradientFeatherValues, ObjectStyleStack, OpacityStopValues, TransparencySetting, +}; +pub use geometry::{MAX_PATH_POINTS, PathGeometry, PathGeometryError, PathPoint, SubPath}; +pub use preferences::{DocumentPreferences, FootnotePreferences, GridPreferences, TextFramePreferences}; +pub use resources::{ + CharacterAppearanceValues, CharacterSpecialValues, CharacterTypographyValues, CjkCharacterValues, CjkParagraphValues, ColorDefinition, + ColorGroup, ColorGroupDefinition, ColorGroupMember, ColorSpace, CompositeFontDefinition, CompositeFontEntryDefinition, EpubExportTagMap, + FontDefinition, FontFamilyDefinition, FontsPart, GradientDefinition, GradientStop, GradientStopDefinition, GradientStopValue, GraphicPart, + GrepStyleValue, Ink, InkDefinition, MojikumiRow, NestedLineStyleValue, NestedStyleValue, NestedStyleValues, ObjectStyleValues, + OpenTypeFeatureValues, ParagraphAlignmentValues, ParagraphBoxValues, ParagraphFlowValues, ParagraphListValues, ParagraphSpanValues, RubyValues, + StrokeDefinition, StrokeStyle, StrokeStyleKind, Style, StyleGroup, StyleGroupWriter, StyleKind, StyleNode, Swatch, SwatchKind, TabStopValues, + TextDecorationValues, TintDefinition, color_groups, inks, named, preference, stroke_styles, style_groups, swatches, +}; +pub use spread::{ + BaselineFrameGridOption, BaselineFrameGridRelative, ClippingPathValues, FrameFittingOption, Graphic, GraphicChild, GraphicKind, + GraphicLayerOptions, Guide, ItemChild, ItemKind, Link, MarginPreference, Page, PageChild, PageItem, PdfAttribute, Spread, SpreadChild, TextPath, + TextWrapPreference, spreads, +}; +pub use story::{ + Ace, AnchoredObjectSetting, AnchoredObjectValues, CONTAINERS, Cell, CellOptions, Container, ContainerKind, ContentPart, CrossReferenceSource, + IndexCrossReferenceValues, IndexDocument, IndexReference, IndexTopicPath, IndexValues, PageReference, Range, SavedCrossReference, + SavedCrossReferencePart, Story, StoryAnchor, StoryPreference, Table, TableChild, TableColumn, TableLayout, TableRow, TextNode, TrackedChangeKind, + stories, +}; use crate::value::{matrix, nums}; @@ -43,6 +67,157 @@ pub struct Values { pub properties: Vec, } +/// Raw IDML stroke values before the caller maps swatches and stroke styles into its model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StrokeValues { + pub weight: Option, + pub color: Option, + pub tint: Option, + pub kind: Option, + pub alignment: Option, + pub cap: Option, + pub join: Option, + pub miter_limit: Option, + pub start: Option, + pub end: Option, + pub gap_color: Option, + pub gap_tint: Option, + pub overprint: Option, + pub gap_overprint: Option, +} + +impl StrokeValues { + /// Reads stroke properties from elements in precedence order (item first, then nearer styles). + pub fn from_elements(elements: &[&El]) -> StrokeValues { + let mut result = StrokeValues::default(); + for el in elements { + let values = Values::of(el); + let num_attr = |key: &str| values.get(key).and_then(|value| value.parse::().ok()).filter(|value| value.is_finite()); + let bool_attr = |key: &str| match values.get(key) { + Some("true") => Some(true), + Some("false") => Some(false), + _ => None, + }; + if result.weight.is_none() { + result.weight = num_attr("StrokeWeight"); + } + if result.color.is_none() { + result.color = values.get("StrokeColor").map(str::to_owned); + } + if result.tint.is_none() { + result.tint = num_attr("StrokeTint"); + } + if result.kind.is_none() { + result.kind = values.get("StrokeType").map(str::to_owned); + } + if result.alignment.is_none() { + result.alignment = values.get("StrokeAlignment").map(str::to_owned); + } + if result.cap.is_none() { + result.cap = values.get("EndCap").map(str::to_owned); + } + if result.join.is_none() { + result.join = values.get("EndJoin").map(str::to_owned); + } + if result.miter_limit.is_none() { + result.miter_limit = num_attr("MiterLimit"); + } + if result.start.is_none() { + result.start = values.get("LeftLineEnd").map(str::to_owned); + } + if result.end.is_none() { + result.end = values.get("RightLineEnd").map(str::to_owned); + } + if result.gap_color.is_none() { + result.gap_color = values.get("GapColor").map(str::to_owned); + } + if result.gap_tint.is_none() { + result.gap_tint = num_attr("GapTint"); + } + if result.overprint.is_none() { + result.overprint = bool_attr("OverprintStroke"); + } + if result.gap_overprint.is_none() { + result.gap_overprint = bool_attr("OverprintGap"); + } + } + result + } +} + +/// Raw fill properties before a caller resolves swatch names to its own colour model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FillValues { + pub color: Option, + pub tint: Option, + pub overprint: Option, +} + +impl FillValues { + /// Reads fill attributes in precedence order (item first, then nearer styles). + pub fn from_elements(elements: &[&El]) -> FillValues { + let mut result = FillValues::default(); + for el in elements { + let values = Values::of(el); + if result.color.is_none() { + result.color = values.get("FillColor").map(str::to_owned); + } + if result.tint.is_none() { + result.tint = values.get("FillTint").and_then(|value| value.parse::().ok()); + } + if result.overprint.is_none() { + result.overprint = match values.get("OverprintFill") { + Some("true") => Some(true), + Some("false") => Some(false), + _ => None, + }; + } + } + result + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AlternatingFillValues { + pub first_count: Option, + pub first_color: Option, + pub first_tint: Option, + pub next_count: Option, + pub next_color: Option, + pub next_tint: Option, + pub skip_first: Option, + pub skip_last: Option, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AlternatingStrokeValues { + pub first_count: Option, + pub next_count: Option, + pub first: StrokeValues, + pub next: StrokeValues, + pub skip_first: Option, + pub skip_last: Option, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableOptions { + pub direction: Option, + pub header_rows: Option, + pub footer_rows: Option, + pub applied_style: Option, + pub space_before: Option, + pub space_after: Option, + pub repeat_header: bool, + pub repeat_footer: bool, + pub borders: [StrokeValues; 4], +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CornerValues { + pub option: Option, + pub radius: Option, +} + impl Values { /// The attributes and `` of `el`. pub fn of(el: &El) -> Values { @@ -104,6 +279,13 @@ impl Values { self.prop(key).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()) } + /// A two-number value (for properties such as `GradientFillStart`), bounded to three tokens. + pub fn pair(&self, key: &str) -> Option<[f64; 2]> { + let source = self.prop(key)?; + let values: Vec = source.split_whitespace().take(3).filter_map(|v| v.parse::().ok()).collect(); + <[f64; 2]>::try_from(values).ok().filter(|v| v.iter().all(|n| n.is_finite())) + } + /// `true` or `false`; anything else counts as absent. pub fn boolean(&self, key: &str) -> Option { match self.prop(key)?.trim() { @@ -154,6 +336,77 @@ impl Values { } el } + + /// Read an IDML stroke attribute family such as `TopEdgeStrokeWeight` or + /// `StartRowStrokeColor`. + pub fn stroke_values(&self, prefix: &str) -> StrokeValues { + StrokeValues { + weight: self.num(&format!("{prefix}StrokeWeight")).map(|v| v.max(0.0)), + color: self.value(&format!("{prefix}StrokeColor")), + tint: self.num(&format!("{prefix}StrokeTint")), + kind: self.value(&format!("{prefix}StrokeType")), + gap_color: self.value(&format!("{prefix}StrokeGapColor")), + gap_tint: self.num(&format!("{prefix}StrokeGapTint")), + ..StrokeValues::default() + } + } + + pub fn alternating_fill_values(&self, kind: &str) -> AlternatingFillValues { + let num = |key: &str| self.num(key).map(|v| v.max(0.0)); + AlternatingFillValues { + first_count: num(&format!("Start{kind}FillCount")), + first_color: self.value(&format!("Start{kind}FillColor")), + first_tint: self.num(&format!("Start{kind}FillTint")), + next_count: num(&format!("End{kind}FillCount")), + next_color: self.value(&format!("End{kind}FillColor")), + next_tint: self.num(&format!("End{kind}FillTint")), + skip_first: num(&format!("SkipFirstAlternatingFill{kind}s")), + skip_last: num(&format!("SkipLastAlternatingFill{kind}s")), + } + } + + pub fn alternating_stroke_values(&self, kind: &str) -> AlternatingStrokeValues { + let num = |key: &str| self.num(key).map(|v| v.max(0.0)); + let mut next = self.stroke_values(&format!("End{kind}")); + // IDML writes this one table-column value as LineStyle rather than StrokeType. + if kind == "Column" { + next.kind = self.value("EndColumnLineStyle").or(next.kind); + } + AlternatingStrokeValues { + first_count: num(&format!("Start{kind}StrokeCount")), + next_count: num(&format!("End{kind}StrokeCount")), + first: self.stroke_values(&format!("Start{kind}")), + next, + skip_first: num(&format!("SkipFirstAlternatingStroke{kind}s")), + skip_last: num(&format!("SkipLastAlternatingStroke{kind}s")), + } + } + + pub fn table_options(&self) -> TableOptions { + TableOptions { + direction: self.value("TableDirection"), + header_rows: self.num("HeaderRowCount"), + footer_rows: self.num("FooterRowCount"), + applied_style: self.value("AppliedTableStyle"), + space_before: self.num("SpaceBefore"), + space_after: self.num("SpaceAfter"), + repeat_header: self.get("HeaderBehavior") != Some("RepeatOnce"), + repeat_footer: self.get("FooterBehavior") != Some("RepeatOnce"), + borders: [ + self.stroke_values("TopBorder"), + self.stroke_values("LeftBorder"), + self.stroke_values("BottomBorder"), + self.stroke_values("RightBorder"), + ], + } + } + + pub fn corner_values(&self, corner: &str) -> CornerValues { + CornerValues { + option: self.value(&format!("{corner}CornerOption")).or_else(|| self.value("CornerOption")), + radius: self.num(&format!("{corner}CornerRadius")).or_else(|| self.num("CornerRadius")), + } + } } /// `el` without its indentation: the whitespace-only text between the children of an element diff --git a/crates/idml/src/model/preferences.rs b/crates/idml/src/model/preferences.rs new file mode 100644 index 000000000..b32317cbd --- /dev/null +++ b/crates/idml/src/model/preferences.rs @@ -0,0 +1,420 @@ +//! Typed views of IDML's reusable text-frame preference grammar. + +use craft_xml::El; + +use super::Values; + +/// Parsed values from IDML `DocumentPreference` elements. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DocumentPreferences { + pub overprint_black: Option, + pub page_width: Option, + pub page_height: Option, + pub facing_pages: Option, + pub page_binding: Option, + pub bleed: [Option; 4], + pub slug: [Option; 4], + pub intent: Option, + pub primary_text_frame: Option, + pub column_guides_locked: Option, +} + +impl DocumentPreferences { + /// Reads the document-level page, bleed, slug, and intent values. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + overprint_black: values.get("OverprintBlack").map(|value| value != "false"), + page_width: values.num("PageWidth"), + page_height: values.num("PageHeight"), + facing_pages: values.boolean("FacingPages"), + page_binding: values.prop("PageBinding"), + bleed: [ + values.num("DocumentBleedTopOffset"), + values.num("DocumentBleedBottomOffset"), + values.num("DocumentBleedInsideOrLeftOffset"), + values.num("DocumentBleedOutsideOrRightOffset"), + ], + slug: [ + values.num("SlugTopOffset"), + values.num("SlugBottomOffset"), + values.num("SlugInsideOrLeftOffset"), + values.num("SlugRightOrOutsideOffset"), + ], + intent: values.prop("Intent"), + primary_text_frame: values.boolean("CreatePrimaryTextFrame"), + column_guides_locked: values.boolean("ColumnGuideLocked"), + } + } + + /// Full canonical attributes for an exported IDML `DocumentPreference`. + pub fn to_export_attrs(&self) -> Vec<(String, String)> { + let mut attrs = Vec::new(); + for (key, value) in [("PageHeight", self.page_height), ("PageWidth", self.page_width)] { + if let Some(value) = value { + attrs.push((key.into(), crate::value::num(value))); + } + } + attrs.push(("PagesPerDocument".into(), "1".into())); + if let Some(value) = self.facing_pages { + attrs.push(("FacingPages".into(), if value { "true" } else { "false" }.into())); + } + for (key, value) in [ + ("DocumentBleedTopOffset", self.bleed[0]), + ("DocumentBleedBottomOffset", self.bleed[1]), + ("DocumentBleedInsideOrLeftOffset", self.bleed[2]), + ("DocumentBleedOutsideOrRightOffset", self.bleed[3]), + ] { + if let Some(value) = value { + attrs.push((key.into(), crate::value::num(value))); + } + } + if self.bleed.iter().all(Option::is_some) { + attrs.push(( + "DocumentBleedUniformSize".into(), + bool_string(self.bleed.iter().flatten().all(|value| *value == self.bleed[0].unwrap_or_default())), + )); + } + for (key, value) in [ + ("SlugTopOffset", self.slug[0]), + ("SlugBottomOffset", self.slug[1]), + ("SlugInsideOrLeftOffset", self.slug[2]), + ("SlugRightOrOutsideOffset", self.slug[3]), + ] { + if let Some(value) = value { + attrs.push((key.into(), crate::value::num(value))); + } + } + if self.slug.iter().all(Option::is_some) { + attrs.push(( + "DocumentSlugUniformSize".into(), + bool_string(self.slug.iter().flatten().all(|value| *value == self.slug[0].unwrap_or_default())), + )); + } + attrs.push(("PreserveLayoutWhenShuffling".into(), "true".into())); + attrs.push(("AllowPageShuffle".into(), "true".into())); + if let Some(value) = self.overprint_black { + attrs.push(("OverprintBlack".into(), bool_string(value))); + } + if let Some(value) = &self.page_binding { + attrs.push(("PageBinding".into(), value.clone())); + } + attrs.push(("ColumnDirection".into(), "Horizontal".into())); + if let Some(value) = &self.intent { + attrs.push(("Intent".into(), value.clone())); + } + if let Some(value) = self.primary_text_frame { + attrs.push(("CreatePrimaryTextFrame".into(), bool_string(value))); + } + if let Some(value) = self.column_guides_locked { + attrs.push(("ColumnGuideLocked".into(), bool_string(value))); + } + if let Some(value) = self.primary_text_frame { + attrs.push(("MasterTextFrame".into(), bool_string(value))); + } + attrs.push(("SnippetImportUsesOriginalLocation".into(), "false".into())); + attrs + } +} + +/// Parsed document and baseline-grid preference values. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct GridPreferences { + pub baseline_start: Option, + pub baseline_division: Option, + pub baseline_view_threshold: Option, + pub baseline_relative_option: Option, + pub horizontal_division: Option, + pub vertical_division: Option, + pub horizontal_subdivision: Option, + pub vertical_subdivision: Option, + pub grids_in_back: Option, +} + +/// Parsed values from IDML `FootnoteOption` elements. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FootnotePreferences { + pub start_at: Option, + pub prefix: Option, + pub suffix: Option, + pub paragraph_style: Option, + pub marker_style: Option, + pub separator: Option, + pub space_between: Option, + pub space_before: Option, + pub first_baseline: Option, + pub first_baseline_minimum: Option, + pub span_columns: Option, + pub rule_on: Option, + pub rule_weight: Option, + pub rule_tint: Option, + pub rule_left_indent: Option, + pub rule_width: Option, + pub rule_offset: Option, + pub rule_color: Option, + pub numbering_style: Option, + pub restart_numbering: Option, + pub show_prefix_suffix: Option, + pub marker_positioning: Option, +} + +impl FootnotePreferences { + /// Reads footnote preference attributes and properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + start_at: values.num("StartAt"), + prefix: values.get("Prefix").map(str::to_owned), + suffix: values.get("Suffix").map(str::to_owned), + paragraph_style: values.get("FootnoteTextStyle").map(str::to_owned), + marker_style: values.get("FootnoteMarkerStyle").map(str::to_owned), + separator: values.get("SeparatorText").map(str::to_owned), + space_between: values.num("SpaceBetween"), + space_before: values.num("Spacer"), + first_baseline: values.prop("FootnoteFirstBaselineOffset"), + first_baseline_minimum: values.num("FootnoteMinimumFirstBaselineOffset"), + span_columns: values.boolean("EnableStraddling"), + rule_on: values.boolean("RuleOn"), + rule_weight: values.num("RuleLineWeight"), + rule_tint: values.num("RuleTint"), + rule_left_indent: values.num("RuleLeftIndent"), + rule_width: values.num("RuleWidth"), + rule_offset: values.num("RuleOffset"), + rule_color: values.prop("RuleColor"), + numbering_style: values.prop("FootnoteNumberingStyle"), + restart_numbering: values.prop("RestartNumbering"), + show_prefix_suffix: values.prop("ShowPrefixSuffix"), + marker_positioning: values.prop("MarkerPositioning"), + } + } + + /// Writes one canonical IDML `FootnoteOption` using caller-resolved style, colour, and enum + /// references. + pub fn to_el(&self) -> El { + let mut el = El::new("FootnoteOption") + .with_attr("StartAt", crate::value::num(self.start_at.unwrap_or(1.0))) + .with_attr("Prefix", self.prefix.as_deref().unwrap_or("")) + .with_attr("Suffix", self.suffix.as_deref().unwrap_or("")) + .with_attr("FootnoteTextStyle", self.paragraph_style.as_deref().unwrap_or("$ID/NormalParagraphStyle")) + .with_attr("FootnoteMarkerStyle", self.marker_style.as_deref().unwrap_or("$ID/[None]")) + .with_attr("SeparatorText", self.separator.as_deref().unwrap_or("")) + .with_attr("SpaceBetween", crate::value::num(self.space_between.unwrap_or(0.0))) + .with_attr("Spacer", crate::value::num(self.space_before.unwrap_or(0.0))) + .with_attr("FootnoteFirstBaselineOffset", self.first_baseline.as_deref().unwrap_or("Ascent")) + .with_attr("FootnoteMinimumFirstBaselineOffset", crate::value::num(self.first_baseline_minimum.unwrap_or(0.0))) + .with_attr("EnableStraddling", bool_text(self.span_columns.unwrap_or(false))) + .with_attr("RuleOn", bool_text(self.rule_on.unwrap_or(true))) + .with_attr("RuleLineWeight", crate::value::num(self.rule_weight.unwrap_or(1.0))) + .with_attr("RuleTint", crate::value::num(self.rule_tint.unwrap_or(1.0))) + .with_attr("RuleLeftIndent", crate::value::num(self.rule_left_indent.unwrap_or(0.0))) + .with_attr("RuleWidth", crate::value::num(self.rule_width.unwrap_or(72.0))) + .with_attr("RuleOffset", crate::value::num(self.rule_offset.unwrap_or(0.0))); + let mut properties = El::new("Properties"); + for (name, value) in [ + ("FootnoteNumberingStyle", self.numbering_style.as_deref().unwrap_or("Arabic")), + ("RestartNumbering", self.restart_numbering.as_deref().unwrap_or("DontRestart")), + ("ShowPrefixSuffix", self.show_prefix_suffix.as_deref().unwrap_or("NoPrefixSuffix")), + ("MarkerPositioning", self.marker_positioning.as_deref().unwrap_or("Superscript")), + ] { + properties.push(El::new(name).with_attr("type", "enumeration").with_text(value)); + } + properties.push(El::new("RuleColor").with_attr("type", "object").with_text(self.rule_color.as_deref().unwrap_or("Swatch/Black"))); + el.push(properties); + el + } +} + +impl GridPreferences { + /// Reads baseline and document-grid values. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + baseline_start: values.num("BaselineStart"), + baseline_division: values.num("BaselineDivision"), + baseline_view_threshold: values.num("BaselineViewThreshold"), + baseline_relative_option: values.prop("BaselineGridRelativeOption"), + horizontal_division: values.num("HorizontalGridlineDivision"), + vertical_division: values.num("VerticalGridlineDivision"), + horizontal_subdivision: values.num("HorizontalGridSubdivision"), + vertical_subdivision: values.num("VerticalGridSubdivision"), + grids_in_back: values.boolean("GridsInBack"), + } + } + + /// IDML attributes represented by this grid preference record. + pub fn to_attrs(&self) -> Vec<(String, String)> { + let mut attrs = Vec::new(); + for (key, value) in [ + ("HorizontalGridlineDivision", self.horizontal_division), + ("VerticalGridlineDivision", self.vertical_division), + ("HorizontalGridSubdivision", self.horizontal_subdivision), + ("VerticalGridSubdivision", self.vertical_subdivision), + ] { + if let Some(value) = value { + attrs.push((key.into(), crate::value::num(value))); + } + } + if let Some(value) = self.grids_in_back { + attrs.push(("GridsInBack".into(), if value { "true" } else { "false" }.into())); + } + for (key, value) in [ + ("BaselineStart", self.baseline_start), + ("BaselineDivision", self.baseline_division), + ("BaselineViewThreshold", self.baseline_view_threshold), + ] { + if let Some(value) = value { + attrs.push((key.into(), crate::value::num(value))); + } + } + if let Some(value) = self.baseline_relative_option.as_deref() { + attrs.push(("BaselineGridRelativeOption".into(), value.into())); + } + attrs + } +} + +fn bool_string(value: bool) -> String { + if value { "true" } else { "false" }.into() +} + +/// Parsed `TextFramePreference` values in nearest-to-farthest precedence order. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TextFramePreferences { + pub column_count: Option, + pub column_gutter: Option, + pub fixed_column_width: Option, + pub fixed_width: bool, + pub flexible_width: bool, + pub balance_columns: bool, + pub inset: Option<[f64; 4]>, + pub vertical_justification: Option, + pub vertical_threshold: Option, + pub first_baseline: Option, + pub minimum_first_baseline: Option, + pub ignore_wrap: bool, + pub auto_sizing_type: Option, + pub auto_sizing_reference: Option, + pub use_minimum_height: bool, + pub minimum_height: Option, + pub use_minimum_width: bool, + pub minimum_width: Option, + pub no_line_breaks: bool, + pub column_rule_override: bool, + pub column_rule_width: Option, + pub column_rule_tint: Option, + pub column_rule_offset: Option, + pub column_rule_top_inset: Option, + pub column_rule_bottom_inset: Option, +} + +impl TextFramePreferences { + /// Reads preference levels nearest first. A malformed explicit value still masks an inherited + /// one, matching IDML's item-over-object-style precedence. + pub fn from_elements(elements: &[&El]) -> Self { + let prop = |key: &str| elements.iter().find_map(|el| Values::of(el).prop(key)); + let num = |key: &str| prop(key).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()); + let boolean = |key: &str| matches!(prop(key).as_deref().map(str::trim), Some("true")); + Self { + column_count: num("TextColumnCount"), + column_gutter: num("TextColumnGutter"), + fixed_column_width: num("TextColumnFixedWidth"), + fixed_width: boolean("UseFixedColumnWidth"), + flexible_width: boolean("UseFlexibleColumnWidth"), + balance_columns: boolean("VerticalBalanceColumns"), + inset: inset(elements), + vertical_justification: prop("VerticalJustification"), + vertical_threshold: num("VerticalThreshold"), + first_baseline: prop("FirstBaselineOffset"), + minimum_first_baseline: num("MinimumFirstBaselineOffset"), + ignore_wrap: boolean("IgnoreWrap"), + auto_sizing_type: prop("AutoSizingType"), + auto_sizing_reference: prop("AutoSizingReferencePoint"), + use_minimum_height: boolean("UseMinimumHeightForAutoSizing"), + minimum_height: num("MinimumHeightForAutoSizing"), + use_minimum_width: boolean("UseMinimumWidthForAutoSizing"), + minimum_width: num("MinimumWidthForAutoSizing"), + no_line_breaks: boolean("UseNoLineBreaksForAutoSizing"), + column_rule_override: boolean("ColumnRuleOverride"), + column_rule_width: num("ColumnRuleStrokeWidth"), + column_rule_tint: num("ColumnRuleStrokeTint"), + column_rule_offset: num("ColumnRuleOffset"), + column_rule_top_inset: num("ColumnRuleTopInset"), + column_rule_bottom_inset: num("ColumnRuleBottomInset"), + } + } + + /// Writes one IDML `TextFramePreference`, including its inset list and column-rule + /// properties. Enumeration strings are supplied by the caller because they are model policy. + pub fn to_el(&self, column_rule_color: &str) -> El { + use crate::value::num; + + let mut inset = El::new("InsetSpacing").with_attr("type", "list"); + for value in self.inset.unwrap_or([0.0; 4]) { + inset.push(El::new("ListItem").with_attr("type", "unit").with_text(num(value))); + } + let el = El::new("TextFramePreference") + .with_attr("TextColumnCount", num(self.column_count.unwrap_or(1.0).max(1.0))) + .with_attr("TextColumnGutter", num(self.column_gutter.unwrap_or(0.0))) + .with_attr("UseFixedColumnWidth", bool_text(self.fixed_width)) + .with_attr("UseFlexibleColumnWidth", bool_text(self.flexible_width)) + .with_attr("VerticalBalanceColumns", bool_text(self.balance_columns)) + .with_attr("FirstBaselineOffset", self.first_baseline.as_deref().unwrap_or("Ascent")) + .with_attr("MinimumFirstBaselineOffset", num(self.minimum_first_baseline.unwrap_or(0.0))) + .with_attr("VerticalJustification", self.vertical_justification.as_deref().unwrap_or("TopAlign")) + .with_attr("VerticalThreshold", num(self.vertical_threshold.unwrap_or(0.0))) + .with_attr("IgnoreWrap", bool_text(self.ignore_wrap)) + .with_attr("AutoSizingType", self.auto_sizing_type.as_deref().unwrap_or("Off")) + .with_attr("AutoSizingReferencePoint", self.auto_sizing_reference.as_deref().unwrap_or("CenterPoint")) + .with_attr("UseMinimumHeightForAutoSizing", bool_text(self.use_minimum_height)) + .with_attr("MinimumHeightForAutoSizing", num(self.minimum_height.unwrap_or(0.0))) + .with_attr("UseMinimumWidthForAutoSizing", bool_text(self.use_minimum_width)) + .with_attr("MinimumWidthForAutoSizing", num(self.minimum_width.unwrap_or(0.0))) + .with_attr("UseNoLineBreaksForAutoSizing", bool_text(self.no_line_breaks)); + let el = if let Some(width) = self.fixed_column_width.filter(|width| *width > 0.0) { + el.with_attr("TextColumnFixedWidth", num(width)) + } else { + el + }; + let el = el + .with_attr("ColumnRuleOverride", bool_text(self.column_rule_override)) + .with_attr("ColumnRuleStrokeWidth", num(self.column_rule_width.unwrap_or(0.0))) + .with_attr("ColumnRuleStrokeColor", column_rule_color) + .with_attr("ColumnRuleStrokeTint", num(self.column_rule_tint.unwrap_or(0.0))) + .with_attr("ColumnRuleOffset", num(self.column_rule_offset.unwrap_or(0.0))) + .with_attr("ColumnRuleTopInset", num(self.column_rule_top_inset.unwrap_or(0.0))) + .with_attr("ColumnRuleBottomInset", num(self.column_rule_bottom_inset.unwrap_or(0.0))) + .with_attr("ColumnRuleInsetChainOverride", bool_text(self.column_rule_top_inset == self.column_rule_bottom_inset)); + el.with_child(El::new("Properties").with_child(inset)) + } +} + +fn bool_text(value: bool) -> &'static str { + if value { "true" } else { "false" } +} + +fn inset(elements: &[&El]) -> Option<[f64; 4]> { + let element = elements.iter().find(|el| Values::of(el).prop("InsetSpacing").is_some())?; + let values = Values::of(element); + let number = |s: &str| s.trim().parse::().ok().filter(|v| v.is_finite()); + let Some(property) = values.prop_el("InsetSpacing") else { + return values.get("InsetSpacing").and_then(number).map(|v| [v; 4]); + }; + let items: Vec<_> = property.elements().collect(); + if property.attr("type") == Some("list") || items.iter().any(|item| item.local() == "ListItem") { + if items.len() != 4 { + return None; + } + let mut result = [0.0; 4]; + for (slot, item) in result.iter_mut().zip(items) { + if item.local() != "ListItem" || item.elements().next().is_some() { + return None; + } + *slot = number(&item.deep_text())?; + } + Some(result) + } else if items.is_empty() { + number(&property.deep_text()).map(|v| [v; 4]) + } else { + None + } +} diff --git a/crates/idml/src/model/resources.rs b/crates/idml/src/model/resources.rs index 6a66f6f91..11a76b186 100644 --- a/crates/idml/src/model/resources.rs +++ b/crates/idml/src/model/resources.rs @@ -11,6 +11,1193 @@ fn others(el: &El) -> impl Iterator { el.elements().filter(|e| !e.is(Local("Properties"))) } +/// Raw bullet and numbering properties on an IDML paragraph style or range. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParagraphListValues { + pub applied_list: Option, + pub list_type: Option, + pub numbering_format: Option, + pub expression: Option, + pub separator: Option, + pub bullet_type: Option, + pub bullet_value: Option, + pub balance_ragged: Option, + pub level: Option, + pub bullet_character_style: Option, + pub numbering_character_style: Option, + pub bullet_alignment: Option, + pub numbering_alignment: Option, + pub restart_numbers: Option, + pub restart_after_level: Option, + pub restart_after_specific_level: bool, + pub numbering_continue: Option, + pub numbering_start_at: Option, + pub bullet_font: Option, + pub bullet_font_style: Option, +} + +/// Paragraph border and shading values after the caller resolves model colours and enums. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParagraphBoxValues { + pub shading_on: Option, + pub shading_color: Option, + pub shading_tint: Option, + pub shading_offsets: Option<[f64; 4]>, + pub shading_overprint: Option, + pub border_on: Option, + pub border_color: Option, + pub border_tint: Option, + pub border_weights: Option<[f64; 4]>, + pub border_offsets: Option<[f64; 4]>, + pub border_type: Option, + pub border_cap: Option, + pub border_join: Option, + pub border_corners: Option<[(String, f64); 4]>, + pub border_width: Option, + pub border_top: Option, + pub border_bottom: Option, + pub border_display_if_splits: Option, + pub border_merge: Option, + pub border_gap_color: Option, + pub border_gap_tint: Option, + pub border_overprint: Option, + pub border_gap_overprint: Option, + pub shading_width: Option, + pub shading_top: Option, + pub shading_bottom: Option, + pub shading_clip: Option, + pub shading_nonprinting: Option, + pub shading_corners: Option<[(String, f64); 4]>, +} + +/// CJK paragraph composition settings read from an IDML style or text range. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CjkParagraphValues { + pub kinsoku_hang: Option, + pub mojikumi: Option, + pub kinsoku_type: Option, + pub bunri_kinshi: Option, + pub rensuuji: Option, + pub treat_ideographic_space_as_space: Option, + pub kinsoku_set: Option, + pub auto_tcy: Option, + pub auto_tcy_include_roman: Option, + pub rotate_single_byte_characters: Option, + pub allow_arbitrary_hyphenation: Option, + pub grid_gyoudori: Option, + pub paragraph_gyoudori: Option, +} + +impl CjkParagraphValues { + /// Reads CJK paragraph composition properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let bounded_count = |key: &str| values.num(key).map(|value| value.clamp(0.0, 1000.0)); + Self { + kinsoku_hang: values.prop("KinsokuHangType"), + mojikumi: values.prop("Mojikumi"), + kinsoku_type: values.prop("KinsokuType"), + bunri_kinshi: values.boolean("BunriKinshi"), + rensuuji: values.boolean("Rensuuji"), + treat_ideographic_space_as_space: values.boolean("TreatIdeographicSpaceAsSpace"), + kinsoku_set: values.prop("KinsokuSet"), + auto_tcy: bounded_count("AutoTcy"), + auto_tcy_include_roman: values.boolean("AutoTcyIncludeRoman"), + rotate_single_byte_characters: values.boolean("RotateSingleByteCharacters"), + allow_arbitrary_hyphenation: values.boolean("AllowArbitraryHyphenation"), + grid_gyoudori: bounded_count("GridGyoudori"), + paragraph_gyoudori: values.boolean("ParagraphGyoudori"), + } + } + + /// Encodes a semantic kinsoku-set name as its IDML property value. + pub fn kinsoku_reference(name: &str) -> String { + if name.is_empty() { "Nothing".into() } else { format!("KinsokuTable/{}", crate::value::escape_id(name)) } + } + + /// Writes CJK paragraph attributes and properties. + pub fn to_parts(&self) -> (Vec<(String, String)>, Vec) { + let mut attrs = Vec::new(); + let mut properties = Vec::new(); + for (key, value) in [("KinsokuHangType", &self.kinsoku_hang), ("KinsokuType", &self.kinsoku_type)] { + if let Some(value) = value { + attrs.push((key.into(), value.clone())); + } + } + if let Some(value) = &self.mojikumi { + let kind = if value.starts_with("MojikumiTable/") { "object" } else { "enumeration" }; + properties.push(property("Mojikumi", kind, value.clone())); + } + for (key, value) in [ + ("BunriKinshi", self.bunri_kinshi), + ("Rensuuji", self.rensuuji), + ("TreatIdeographicSpaceAsSpace", self.treat_ideographic_space_as_space), + ("AutoTcyIncludeRoman", self.auto_tcy_include_roman), + ("RotateSingleByteCharacters", self.rotate_single_byte_characters), + ("AllowArbitraryHyphenation", self.allow_arbitrary_hyphenation), + ("ParagraphGyoudori", self.paragraph_gyoudori), + ] { + push_boolean(&mut attrs, key, value); + } + push_number(&mut attrs, "AutoTcy", self.auto_tcy); + push_number(&mut attrs, "GridGyoudori", self.grid_gyoudori); + if let Some(value) = &self.kinsoku_set { + properties.push(property("KinsokuSet", if value == "Nothing" { "enumeration" } else { "object" }, value.clone())); + } + (attrs, properties) + } +} + +/// Paragraph span and split-column properties read from IDML. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParagraphSpanValues { + pub kind: Option, + pub split_column_count: Option, + pub inside_gutter: Option, + pub outside_gutter: Option, + pub space_before: Option, + pub space_after: Option, +} + +impl ParagraphSpanValues { + /// Reads paragraph span and split-column properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + kind: values.prop("SpanColumnType"), + split_column_count: values.prop("SpanSplitColumnCount").and_then(|value| value.trim().parse().ok()), + inside_gutter: values.num("SplitColumnInsideGutter"), + outside_gutter: values.num("SplitColumnOutsideGutter"), + space_before: values.num("SpanColumnMinSpaceBefore"), + space_after: values.num("SpanColumnMinSpaceAfter"), + } + } + + /// Writes paragraph span and split-column attributes and properties. + pub fn to_parts(&self) -> (Vec<(String, String)>, Vec) { + let mut attrs = Vec::new(); + let mut properties = Vec::new(); + if let Some(kind) = &self.kind { + attrs.push(("SpanColumnType".into(), kind.clone())); + } + if let Some(count) = self.split_column_count { + properties.push(if count == 0 { + property("SpanSplitColumnCount", "enumeration", "All") + } else { + property("SpanSplitColumnCount", "long", count.to_string()) + }); + } + for (key, value) in [ + ("SplitColumnInsideGutter", self.inside_gutter), + ("SplitColumnOutsideGutter", self.outside_gutter), + ("SpanColumnMinSpaceBefore", self.space_before), + ("SpanColumnMinSpaceAfter", self.space_after), + ] { + push_number(&mut attrs, key, value); + } + (attrs, properties) + } +} + +/// Paragraph alignment, spacing, drop cap, baseline grid and composer values after the caller +/// maps application semantics to IDML enumerations. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParagraphAlignmentValues { + pub justification: Option, + pub direction: Option, + pub kashidas: Option, + pub paragraph_justification: Option, + pub paragraph_kashida_width: Option, + pub left_indent: Option, + pub right_indent: Option, + pub first_line_indent: Option, + pub last_line_indent: Option, + pub space_before: Option, + pub space_after: Option, + pub same_para_style_spacing: Option>, + pub drop_cap_lines: Option, + pub drop_cap_chars: Option, + pub dropcap_detail: Option, + pub grid_alignment: Option, + pub grid_align_first_line_only: Option, + pub composer: Option, +} + +/// Paragraph hyphenation, justification spacing and keep options after caller enum mapping. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParagraphFlowValues { + pub hyphenate: Option, + pub hyphenate_min_word: Option, + pub hyphenate_after_first: Option, + pub hyphenate_before_last: Option, + pub hyphenate_ladder_limit: Option, + pub hyphenation_zone: Option, + pub hyphenate_capitalized: Option, + pub hyphenate_last_word: Option, + pub hyphenate_across_columns: Option, + pub hyphen_weight: Option, + pub word_spacing: [Option; 3], + pub letter_spacing: [Option; 3], + pub glyph_scaling: [Option; 3], + pub auto_leading: Option, + pub single_word_justification: Option, + pub keep_with_next: Option, + pub keep_lines_together: Option, + pub ignore_edge_alignment: Option, + pub keep_all_lines_together: Option, + pub keep_first_lines: Option, + pub keep_last_lines: Option, + pub start_paragraph: Option, +} + +/// Raw IDML character typography values before the caller resolves fonts and semantic enums. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CharacterTypographyValues { + pub applied_font: Option, + pub font_style: Option, + pub point_size: Option, + pub leading: Option, + pub kerning_method: Option, + pub kerning_value: Option, + pub tracking: Option, + pub leading_aki: Option, + pub trailing_aki: Option, + pub tsume: Option, + pub jidori: Option, + pub leading_model: Option, + pub character_alignment: Option, + pub horizontal_scale: Option, + pub vertical_scale: Option, + pub baseline_shift: Option, + pub skew: Option, +} + +/// One underline or strikethrough style as written in IDML. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TextDecorationValues { + pub weight: Option, + pub offset: Option, + pub color: Option, + pub tint: Option, +} + +/// Character fill/stroke, decoration and toggle values before caller swatch resolution. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CharacterAppearanceValues { + pub fill_color: Option, + pub fill_tint: Option, + pub stroke_color: Option, + pub stroke_tint: Option, + pub stroke_weight: Option, + pub stroke_alignment: Option, + pub underline: Option, + pub strikethrough: Option, + pub ligatures: Option, + pub underline_options: TextDecorationValues, + pub strikethrough_options: TextDecorationValues, +} + +/// Raw Ruby attributes and properties on an IDML character range or style. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RubyValues { + pub flag: Option, + pub text: Option, + pub kind: Option, + pub alignment: Option, + pub position: Option, + pub x_offset: Option, + pub y_offset: Option, + pub font: Option, + pub font_style: Option, + pub font_size: Option, + pub x_scale: Option, + pub y_scale: Option, + pub open_type_pro: Option, + pub auto_tcy_digits: Option, + pub auto_tcy_include_roman: Option, + pub auto_tcy_auto_scale: Option, + pub overhang: Option, + pub parent_overhang: Option, + pub parent_spacing: Option, + pub auto_align: Option, + pub auto_scaling: Option, + pub parent_scaling: Option, + pub fill: Option, + pub stroke: Option, + pub fill_tint: Option, + pub stroke_tint: Option, + pub stroke_weight: Option, + pub overprint_fill: Option, + pub overprint_stroke: Option, +} + +/// Raw remaining character attributes and properties before semantic enum and condition mapping. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CharacterSpecialValues { + pub capitalization: Option, + pub position: Option, + pub glyph_form: Option, + pub no_break: Option, + pub tate_chu_yoko: Option, + pub tate_chu_yoko_x_offset: Option, + pub tate_chu_yoko_y_offset: Option, + pub warichu: Option, + pub warichu_lines: Option, + pub warichu_size: Option, + pub warichu_line_spacing: Option, + pub warichu_alignment: Option, + pub warichu_chars_before_break: Option, + pub warichu_chars_after_break: Option, + pub digits: Option, + pub character_direction: Option, + pub allow_kashidas: Option, + pub diacritic_position: Option, + pub diacritic_x_offset: Option, + pub diacritic_y_offset: Option, + pub positional_form: Option, + pub applied_conditions: Option, + pub applied_language: Option, +} + +impl CharacterSpecialValues { + /// Reads remaining character ranges/style fields from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + capitalization: values.prop("Capitalization"), + position: values.prop("Position"), + glyph_form: values.prop("GlyphForm"), + no_break: values.boolean("NoBreak"), + tate_chu_yoko: values.boolean("Tatechuyoko"), + tate_chu_yoko_x_offset: values.num("TatechuyokoXOffset"), + tate_chu_yoko_y_offset: values.num("TatechuyokoYOffset"), + warichu: values.boolean("Warichu"), + warichu_lines: values.num("WarichuLines"), + warichu_size: values.num("WarichuSize"), + warichu_line_spacing: values.num("WarichuLineSpacing"), + warichu_alignment: values.prop("WarichuAlignment"), + warichu_chars_before_break: values.num("WarichuCharsBeforeBreak"), + warichu_chars_after_break: values.num("WarichuCharsAfterBreak"), + digits: values.prop("DigitsType"), + character_direction: values.prop("CharacterDirection"), + allow_kashidas: values.prop("Kashidas"), + diacritic_position: values.prop("DiacriticPosition"), + diacritic_x_offset: values.num("XOffsetDiacritic"), + diacritic_y_offset: values.num("YOffsetDiacritic"), + positional_form: values.prop("PositionalForm"), + applied_conditions: values.prop("AppliedConditions"), + applied_language: values.prop("AppliedLanguage"), + } + } +} + +impl RubyValues { + /// Reads Ruby text and formatting values from an IDML character range/style. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + flag: values.boolean("RubyFlag").or_else(|| values.num("RubyFlag").map(|value| value != 0.0)), + text: values.prop("RubyString"), + kind: values.prop("RubyType"), + alignment: values.prop("RubyAlignment"), + position: values.prop("RubyPosition"), + x_offset: values.num("RubyXOffset"), + y_offset: values.num("RubyYOffset"), + font: values.prop("RubyFont"), + font_style: values.prop("RubyFontStyle"), + font_size: values.num("RubyFontSize"), + x_scale: values.num("RubyXScale"), + y_scale: values.num("RubyYScale"), + open_type_pro: values.boolean("RubyOpenTypePro"), + auto_tcy_digits: values.num("RubyAutoTcyDigits"), + auto_tcy_include_roman: values.boolean("RubyAutoTcyIncludeRoman"), + auto_tcy_auto_scale: values.boolean("RubyAutoTcyAutoScale"), + overhang: values.boolean("RubyOverhang"), + parent_overhang: values.prop("RubyParentOverhangAmount"), + parent_spacing: values.prop("RubyParentSpacing"), + auto_align: values.boolean("RubyAutoAlign"), + auto_scaling: values.boolean("RubyAutoScaling"), + parent_scaling: values.num("RubyParentScalingPercent"), + fill: values.prop("RubyFill"), + stroke: values.prop("RubyStroke"), + fill_tint: values.num("RubyTint"), + stroke_tint: values.num("RubyStrokeTint"), + stroke_weight: values.num("RubyWeight"), + overprint_fill: values.prop("RubyOverprintFill"), + overprint_stroke: values.prop("RubyOverprintStroke"), + } + } +} + +impl CharacterAppearanceValues { + /// Reads common character fill, stroke and decoration properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let decoration = |prefix: &str| { + let number = |suffix: &str| values.num(&format!("{prefix}{suffix}")).filter(|value| *value > -9000.0); + TextDecorationValues { + weight: number("Weight"), + offset: number("Offset"), + color: values.prop(&format!("{prefix}Color")), + tint: values.num(&format!("{prefix}Tint")), + } + }; + Self { + fill_color: values.prop("FillColor"), + fill_tint: values.num("FillTint"), + stroke_color: values.prop("StrokeColor"), + stroke_tint: values.num("StrokeTint"), + stroke_weight: values.num("StrokeWeight"), + stroke_alignment: values.prop("StrokeAlignment"), + underline: values.boolean("Underline"), + strikethrough: values.boolean("StrikeThru"), + ligatures: values.boolean("Ligatures"), + underline_options: decoration("Underline"), + strikethrough_options: decoration("StrikeThru"), + } + } +} + +impl CharacterTypographyValues { + /// Reads the common typography attributes and properties from an IDML character range/style. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + applied_font: values.prop("AppliedFont"), + font_style: values.prop("FontStyle"), + point_size: values.num("PointSize"), + leading: values.prop("Leading"), + kerning_method: values.prop("KerningMethod"), + kerning_value: values.num("KerningValue"), + tracking: values.num("Tracking"), + leading_aki: values.num("LeadingAki"), + trailing_aki: values.num("TrailingAki"), + tsume: values.num("Tsume"), + jidori: values.num("Jidori"), + leading_model: values.prop("LeadingModel"), + character_alignment: values.prop("CharacterAlignment"), + horizontal_scale: values.num("HorizontalScale"), + vertical_scale: values.num("VerticalScale"), + baseline_shift: values.num("BaselineShift"), + skew: values.num("Skew"), + } + } +} + +impl ParagraphFlowValues { + /// Reads paragraph hyphenation and flow properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + hyphenate: values.boolean("Hyphenation"), + hyphenate_min_word: values.num("HyphenateWordsLongerThan"), + hyphenate_after_first: values.num("HyphenateAfterFirst"), + hyphenate_before_last: values.num("HyphenateBeforeLast"), + hyphenate_ladder_limit: values.num("HyphenateLadderLimit"), + hyphenation_zone: values.num("HyphenationZone"), + hyphenate_capitalized: values.boolean("HyphenateCapitalizedWords"), + hyphenate_last_word: values.boolean("HyphenateLastWord"), + hyphenate_across_columns: values.boolean("HyphenateAcrossColumns"), + hyphen_weight: values.num("HyphenWeight"), + word_spacing: [values.num("MinimumWordSpacing"), values.num("DesiredWordSpacing"), values.num("MaximumWordSpacing")], + letter_spacing: [values.num("MinimumLetterSpacing"), values.num("DesiredLetterSpacing"), values.num("MaximumLetterSpacing")], + glyph_scaling: [values.num("MinimumGlyphScaling"), values.num("DesiredGlyphScaling"), values.num("MaximumGlyphScaling")], + auto_leading: values.num("AutoLeading"), + single_word_justification: values.prop("SingleWordJustification"), + keep_with_next: values.num("KeepWithNext"), + keep_lines_together: values.boolean("KeepLinesTogether"), + ignore_edge_alignment: values.boolean("IgnoreEdgeAlignment"), + keep_all_lines_together: values.boolean("KeepAllLinesTogether"), + keep_first_lines: values.num("KeepFirstLines"), + keep_last_lines: values.num("KeepLastLines"), + start_paragraph: values.prop("StartParagraph"), + } + } + + /// Writes IDML attributes for paragraph hyphenation and flow. + pub fn to_attrs(&self) -> Vec<(String, String)> { + let mut attrs = Vec::new(); + for (key, value) in [ + ("Hyphenation", self.hyphenate), + ("HyphenateCapitalizedWords", self.hyphenate_capitalized), + ("HyphenateLastWord", self.hyphenate_last_word), + ("HyphenateAcrossColumns", self.hyphenate_across_columns), + ("KeepLinesTogether", self.keep_lines_together), + ("IgnoreEdgeAlignment", self.ignore_edge_alignment), + ("KeepAllLinesTogether", self.keep_all_lines_together), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), if value { "true" } else { "false" }.to_string())); + } + } + for (key, value) in [ + ("HyphenateWordsLongerThan", self.hyphenate_min_word), + ("HyphenateAfterFirst", self.hyphenate_after_first), + ("HyphenateBeforeLast", self.hyphenate_before_last), + ("HyphenateLadderLimit", self.hyphenate_ladder_limit), + ("HyphenationZone", self.hyphenation_zone), + ("HyphenWeight", self.hyphen_weight), + ("MinimumWordSpacing", self.word_spacing[0]), + ("DesiredWordSpacing", self.word_spacing[1]), + ("MaximumWordSpacing", self.word_spacing[2]), + ("MinimumLetterSpacing", self.letter_spacing[0]), + ("DesiredLetterSpacing", self.letter_spacing[1]), + ("MaximumLetterSpacing", self.letter_spacing[2]), + ("MinimumGlyphScaling", self.glyph_scaling[0]), + ("DesiredGlyphScaling", self.glyph_scaling[1]), + ("MaximumGlyphScaling", self.glyph_scaling[2]), + ("AutoLeading", self.auto_leading), + ("KeepWithNext", self.keep_with_next), + ("KeepFirstLines", self.keep_first_lines), + ("KeepLastLines", self.keep_last_lines), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), crate::value::num(value))); + } + } + for (key, value) in [("SingleWordJustification", &self.single_word_justification), ("StartParagraph", &self.start_paragraph)] { + if let Some(value) = value { + attrs.push((key.to_string(), value.clone())); + } + } + attrs + } +} + +impl ParagraphAlignmentValues { + /// Reads paragraph alignment and spacing properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + justification: values.prop("Justification"), + direction: values.prop("ParagraphDirection"), + kashidas: values.prop("Kashidas"), + paragraph_justification: values.prop("ParagraphJustification"), + paragraph_kashida_width: values.num("ParagraphKashidaWidth"), + left_indent: values.num("LeftIndent"), + right_indent: values.num("RightIndent"), + first_line_indent: values.num("FirstLineIndent"), + last_line_indent: values.num("LastLineIndent"), + space_before: values.num("SpaceBefore"), + space_after: values.num("SpaceAfter"), + same_para_style_spacing: values.prop("SameParaStyleSpacing").map(|value| value.trim().parse::().ok().filter(|v| v.is_finite())), + drop_cap_lines: values.num("DropCapLines"), + drop_cap_chars: values.num("DropCapCharacters"), + dropcap_detail: values.num("DropcapDetail").filter(|value| *value >= 0.0).map(|value| value as u32), + grid_alignment: values.prop("GridAlignment"), + grid_align_first_line_only: values.boolean("GridAlignFirstLineOnly"), + composer: values.prop("Composer"), + } + } + + /// Writes the IDML attributes for paragraph alignment and spacing. + pub fn to_attrs(&self) -> Vec<(String, String)> { + let mut attrs = Vec::new(); + for (key, value) in [ + ("Justification", &self.justification), + ("ParagraphDirection", &self.direction), + ("Kashidas", &self.kashidas), + ("ParagraphJustification", &self.paragraph_justification), + ("GridAlignment", &self.grid_alignment), + ("Composer", &self.composer), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), value.clone())); + } + } + for (key, value) in [ + ("ParagraphKashidaWidth", self.paragraph_kashida_width), + ("LeftIndent", self.left_indent), + ("RightIndent", self.right_indent), + ("FirstLineIndent", self.first_line_indent), + ("LastLineIndent", self.last_line_indent), + ("SpaceBefore", self.space_before), + ("SpaceAfter", self.space_after), + ("DropCapLines", self.drop_cap_lines), + ("DropCapCharacters", self.drop_cap_chars), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), crate::value::num(value))); + } + } + if let Some(value) = self.same_para_style_spacing { + attrs.push(("SameParaStyleSpacing".to_string(), value.map(crate::value::num).unwrap_or_else(|| "Nothing".to_string()))); + } + if let Some(value) = self.dropcap_detail { + attrs.push(("DropcapDetail".to_string(), value.to_string())); + } + if let Some(value) = self.grid_align_first_line_only { + attrs.push(("GridAlignFirstLineOnly".to_string(), if value { "true" } else { "false" }.to_string())); + } + attrs + } +} + +impl ParagraphBoxValues { + /// Reads paragraph border and shading values from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let sides = |prefix: &str, suffix: &str| { + let values = ["Top", "Left", "Bottom", "Right"].map(|side| values.num(&format!("{prefix}{side}{suffix}"))); + values.iter().any(Option::is_some).then(|| values.map(|value| value.unwrap_or(0.0))) + }; + let corners = |prefix: &str| { + let names = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"]; + let shapes = names.map(|corner| values.prop(&format!("{prefix}{corner}CornerOption"))); + let sizes = names.map(|corner| values.num(&format!("{prefix}{corner}CornerRadius"))); + if shapes.iter().all(Option::is_none) && sizes.iter().all(Option::is_none) { + None + } else { + Some(std::array::from_fn(|index| { + (shapes[index].clone().unwrap_or_else(|| "None".to_string()), sizes[index].map_or(12.0, |value| value.max(0.0))) + })) + } + }; + Self { + shading_on: values.boolean("ParagraphShadingOn"), + shading_color: values.prop("ParagraphShadingColor"), + shading_tint: values.num("ParagraphShadingTint"), + shading_offsets: sides("ParagraphShading", "Offset"), + shading_overprint: values.boolean("ParagraphShadingOverprint"), + border_on: values.boolean("ParagraphBorderOn"), + border_color: values.prop("ParagraphBorderColor"), + border_tint: values.num("ParagraphBorderTint"), + border_weights: sides("ParagraphBorder", "LineWeight"), + border_offsets: sides("ParagraphBorder", "Offset"), + border_type: values.prop("ParagraphBorderType"), + border_cap: values.prop("ParagraphBorderStrokeEndCap"), + border_join: values.prop("ParagraphBorderStrokeEndJoin"), + border_corners: corners("ParagraphBorder"), + border_width: values.prop("ParagraphBorderWidth"), + border_top: values.prop("ParagraphBorderTopOrigin"), + border_bottom: values.prop("ParagraphBorderBottomOrigin"), + border_display_if_splits: values.boolean("ParagraphBorderDisplayIfSplits"), + border_merge: values.boolean("MergeConsecutiveParaBorders"), + border_gap_color: values.prop("ParagraphBorderGapColor"), + border_gap_tint: values.num("ParagraphBorderGapTint"), + border_overprint: values.boolean("ParagraphBorderOverprint"), + border_gap_overprint: values.boolean("ParagraphBorderGapOverprint"), + shading_width: values.prop("ParagraphShadingWidth"), + shading_top: values.prop("ParagraphShadingTopOrigin"), + shading_bottom: values.prop("ParagraphShadingBottomOrigin"), + shading_clip: values.boolean("ParagraphShadingClipToFrame"), + shading_nonprinting: values.boolean("ParagraphShadingSuppressPrinting"), + shading_corners: corners("ParagraphShading"), + } + } + + /// Writes IDML attributes and properties for paragraph borders and shading. + pub fn to_parts(&self) -> (Vec<(String, String)>, Vec) { + use crate::value::num; + + let mut attrs = Vec::new(); + let mut props = Vec::new(); + push_boolean(&mut attrs, "ParagraphShadingOn", self.shading_on); + if let Some(color) = &self.shading_color { + props.push(property("ParagraphShadingColor", "object", color.clone())); + } + push_number(&mut attrs, "ParagraphShadingTint", self.shading_tint); + push_boolean(&mut attrs, "ParagraphShadingOverprint", self.shading_overprint); + const SIDES: [&str; 4] = ["Top", "Left", "Bottom", "Right"]; + if let Some(offsets) = self.shading_offsets { + for (side, value) in SIDES.iter().zip(offsets) { + push_number(&mut attrs, &format!("ParagraphShading{side}Offset"), Some(value)); + } + } + push_boolean(&mut attrs, "ParagraphBorderOn", self.border_on); + if let Some(color) = &self.border_color { + props.push(property("ParagraphBorderColor", "object", color.clone())); + } + push_number(&mut attrs, "ParagraphBorderTint", self.border_tint); + push_boolean(&mut attrs, "ParagraphBorderOverprint", self.border_overprint); + if let Some(weights) = self.border_weights { + for (side, value) in SIDES.iter().zip(weights) { + push_number(&mut attrs, &format!("ParagraphBorder{side}LineWeight"), Some(value)); + } + } + if let Some(offsets) = self.border_offsets { + for (side, value) in SIDES.iter().zip(offsets) { + push_number(&mut attrs, &format!("ParagraphBorder{side}Offset"), Some(value)); + } + } + if let Some(kind) = &self.border_type { + props.push(property("ParagraphBorderType", "object", kind.clone())); + } + if let Some(cap) = &self.border_cap { + attrs.push(("ParagraphBorderStrokeEndCap".into(), cap.clone())); + } + if let Some(join) = &self.border_join { + attrs.push(("ParagraphBorderStrokeEndJoin".into(), join.clone())); + } + for (prefix, corners) in [("ParagraphBorder", &self.border_corners), ("ParagraphShading", &self.shading_corners)] { + if let Some(corners) = corners { + const CORNERS: [&str; 4] = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"]; + for ((shape, radius), corner) in corners.iter().zip(CORNERS) { + attrs.push((format!("{prefix}{corner}CornerOption"), shape.clone())); + attrs.push((format!("{prefix}{corner}CornerRadius"), num(*radius))); + } + } + } + for (key, value) in [ + ("ParagraphBorderWidth", &self.border_width), + ("ParagraphBorderTopOrigin", &self.border_top), + ("ParagraphBorderBottomOrigin", &self.border_bottom), + ("ParagraphShadingWidth", &self.shading_width), + ("ParagraphShadingTopOrigin", &self.shading_top), + ("ParagraphShadingBottomOrigin", &self.shading_bottom), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), value.clone())); + } + } + push_boolean(&mut attrs, "ParagraphBorderDisplayIfSplits", self.border_display_if_splits); + push_boolean(&mut attrs, "MergeConsecutiveParaBorders", self.border_merge); + if let Some(color) = &self.border_gap_color { + props.push(property("ParagraphBorderGapColor", "object", color.clone())); + } + push_number(&mut attrs, "ParagraphBorderGapTint", self.border_gap_tint); + push_boolean(&mut attrs, "ParagraphBorderGapOverprint", self.border_gap_overprint); + push_boolean(&mut attrs, "ParagraphShadingClipToFrame", self.shading_clip); + push_boolean(&mut attrs, "ParagraphShadingSuppressPrinting", self.shading_nonprinting); + (attrs, props) + } +} + +fn push_boolean(attrs: &mut Vec<(String, String)>, key: &str, value: Option) { + if let Some(value) = value { + attrs.push((key.to_string(), if value { "true" } else { "false" }.to_string())); + } +} + +fn push_number(attrs: &mut Vec<(String, String)>, key: &str, value: Option) { + if let Some(value) = value { + attrs.push((key.to_string(), crate::value::num(value))); + } +} + +impl ParagraphListValues { + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let restart = values.prop_el("NumberingRestartPolicies"); + let restart_after_level = restart.map(|policy| policy.attr("LowerLevel").and_then(|value| value.trim().parse::().ok()).unwrap_or(0)); + let restart_after_specific_level = restart.is_some_and(|policy| policy.attr("RestartPolicy").map(str::trim) == Some("SpecificPreviousLevel")); + let bullet = values.prop_el("BulletChar"); + Self { + applied_list: values.prop("AppliedNumberingList"), + list_type: values.prop("BulletsAndNumberingListType"), + numbering_format: values.prop("NumberingFormat"), + expression: values.prop("NumberingExpression"), + separator: values.prop("BulletsTextAfter"), + bullet_type: bullet.and_then(|value| value.attr("BulletCharacterType")).map(str::to_owned), + bullet_value: bullet.and_then(|value| value.attr("BulletCharacterValue")).map(str::to_owned), + balance_ragged: values.prop("BalanceRaggedLines"), + level: values.num("NumberingLevel"), + bullet_character_style: values.prop("BulletsCharacterStyle"), + numbering_character_style: values.prop("NumberingCharacterStyle"), + bullet_alignment: values.prop("BulletsAlignment"), + numbering_alignment: values.prop("NumberingAlignment"), + restart_numbers: values.boolean("NumberingApplyRestartPolicy"), + restart_after_level, + restart_after_specific_level, + numbering_continue: values.boolean("NumberingContinue"), + numbering_start_at: values.num("NumberingStartAt"), + bullet_font: values.prop("BulletsFont"), + bullet_font_style: values.prop("BulletsFontStyle"), + } + } + + /// Encodes a semantic paragraph-list name as its IDML object reference. + pub fn numbering_list_reference(name: &str) -> String { + if name.is_empty() { "NumberingList/$ID/[Default]".into() } else { format!("NumberingList/{}", crate::value::escape_id(name)) } + } + + /// IDML attributes represented by a paragraph's list settings. + pub fn to_attrs(&self) -> Vec<(String, String)> { + let mut attrs = Vec::new(); + if let Some(value) = &self.applied_list { + attrs.push(("AppliedNumberingList".into(), value.clone())); + } + if let Some(value) = self.numbering_continue { + attrs.push(("NumberingContinue".into(), if value { "true" } else { "false" }.into())); + } + push_number(&mut attrs, "NumberingStartAt", self.numbering_start_at); + for (key, value) in [ + ("BulletsAndNumberingListType", &self.list_type), + ("NumberingExpression", &self.expression), + ("BulletsTextAfter", &self.separator), + ("NumberingLevel", &self.level.map(crate::value::num)), + ("BulletsAlignment", &self.bullet_alignment), + ("NumberingAlignment", &self.numbering_alignment), + ("NumberingApplyRestartPolicy", &self.restart_numbers.map(|value| if value { "true".to_string() } else { "false".to_string() })), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), value.clone())); + } + } + attrs + } + + /// IDML property elements represented by a paragraph's list settings. + pub fn to_els(&self) -> Vec { + let mut properties = Vec::new(); + if let Some(format) = &self.numbering_format { + properties.push(property("NumberingFormat", "string", format.clone())); + } + if let (Some(kind), Some(value)) = (&self.bullet_type, &self.bullet_value) { + properties.push(El::new("BulletChar").with_attr("BulletCharacterType", kind).with_attr("BulletCharacterValue", value)); + } + if let Some(balance) = &self.balance_ragged { + properties.push(property("BalanceRaggedLines", "enumeration", balance.clone())); + } + for (name, style) in [("BulletsCharacterStyle", &self.bullet_character_style), ("NumberingCharacterStyle", &self.numbering_character_style)] { + if let Some(style) = style { + properties.push(property(name, "object", style.clone())); + } + } + if let Some(level) = self.restart_after_level { + let mut restart = El::new("NumberingRestartPolicies") + .with_attr("RestartPolicy", if self.restart_after_specific_level { "SpecificPreviousLevel" } else { "AnyPreviousLevel" }) + .with_attr("LowerLevel", level.to_string()); + restart.set_attr("UpperLevel", level.to_string()); + properties.push(restart); + } + if let Some(font) = &self.bullet_font { + properties.push(property("BulletsFont", "string", if font.is_empty() { "$ID/".into() } else { font.clone() })); + } + if let Some(style) = self.bullet_font_style.as_ref().filter(|style| !style.is_empty()) { + properties.push(property("BulletsFontStyle", "string", style.clone())); + } + properties + } +} + +/// One IDML nested paragraph style entry, before the caller resolves its character style. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NestedStyleValue { + pub character_style: String, + pub inclusive: bool, + pub repetition: u32, + pub delimiter_type: String, + pub delimiter: String, +} + +/// One IDML nested line style entry. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NestedLineStyleValue { + pub character_style: String, + pub line_count: u32, +} + +/// One IDML GREP style entry. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct GrepStyleValue { + pub character_style: String, + pub expression: String, +} + +/// Nested style lists stored on an IDML paragraph style or text range. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NestedStyleValues { + pub nested: Option>, + pub lines: Option>, + pub grep: Option>, +} + +impl NestedStyleValues { + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let text = |item: &El, name: &str| item.find(name).map(El::deep_text).unwrap_or_default(); + let nested = values.prop_el("AllNestedStyles").map(|list| { + list.find_all("ListItem") + .map(|item| { + let delimiter = item.find("Delimiter"); + NestedStyleValue { + character_style: text(item, "AppliedCharacterStyle"), + inclusive: text(item, "Inclusive").trim() != "false", + repetition: text(item, "Repetition").trim().parse().unwrap_or(1), + delimiter_type: delimiter.and_then(|el| el.attr("type")).unwrap_or("enumeration").to_owned(), + delimiter: text(item, "Delimiter"), + } + }) + .collect() + }); + let lines = values.prop_el("AllNestedLineStyles").map(|list| { + list.find_all("ListItem") + .map(|item| NestedLineStyleValue { + character_style: text(item, "AppliedCharacterStyle"), + line_count: text(item, "LineCount").trim().parse().unwrap_or(1), + }) + .collect() + }); + let grep = values.prop_el("AllGREPStyles").map(|list| { + list.find_all("ListItem") + .map(|item| GrepStyleValue { character_style: text(item, "AppliedCharacterStyle"), expression: text(item, "GrepExpression") }) + .collect() + }); + Self { nested, lines, grep } + } + + /// Writes the nested style property lists. The caller resolves semantic style references and + /// delimiter enums into the IDML values held in this model. + pub fn to_els(&self) -> Vec { + let mut properties = Vec::new(); + if let Some(entries) = &self.nested { + let mut list = El::new("AllNestedStyles").with_attr("type", "list"); + for entry in entries { + list.push( + El::new("ListItem") + .with_attr("type", "record") + .with_child(property("AppliedCharacterStyle", "object", entry.character_style.clone())) + .with_child(property("Delimiter", &entry.delimiter_type, entry.delimiter.clone())) + .with_child(property("Repetition", "long", entry.repetition.to_string())) + .with_child(property("Inclusive", "boolean", if entry.inclusive { "true" } else { "false" })), + ); + } + properties.push(list); + } + if let Some(entries) = &self.lines { + let mut list = El::new("AllNestedLineStyles").with_attr("type", "list"); + for entry in entries { + list.push( + El::new("ListItem") + .with_attr("type", "record") + .with_child(property("AppliedCharacterStyle", "object", entry.character_style.clone())) + .with_child(property("LineCount", "long", entry.line_count.to_string())), + ); + } + properties.push(list); + } + if let Some(entries) = &self.grep { + let mut list = El::new("AllGREPStyles").with_attr("type", "list"); + for entry in entries { + list.push( + El::new("ListItem") + .with_attr("type", "record") + .with_child(property("AppliedCharacterStyle", "object", entry.character_style.clone())) + .with_child(property("GrepExpression", "string", entry.expression.clone())), + ); + } + properties.push(list); + } + properties + } +} + +fn property(name: &str, kind: &str, value: impl Into) -> El { + El::new(name).with_attr("type", kind).with_text(value) +} + +/// OpenType feature tags represented by IDML character attributes. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct OpenTypeFeatureValues { + pub features: Vec, + pub present: bool, +} + +impl OpenTypeFeatureValues { + /// Reads IDML OTF toggle, figure style and stylistic-set attributes into feature tags. + pub fn from_el(el: &El) -> Self { + const TOGGLES: &[(&str, &str)] = &[ + ("dlig", "OTFDiscretionaryLigature"), + ("frac", "OTFFraction"), + ("ordn", "OTFOrdinal"), + ("swsh", "OTFSwash"), + ("titl", "OTFTitling"), + ("calt", "OTFContextualAlternate"), + ("zero", "OTFSlashedZero"), + ("palt", "OTFProportionalMetrics"), + ("hkna", "OTFHVKana"), + ("locl", "OTFLocale"), + ("mark", "OTFMark"), + ("hist", "OTFHistorical"), + ("salt", "OTFStylisticAlternate"), + ("jalt", "OTFJustificationAlternate"), + ("ital", "OTFRomanItalics"), + ]; + let values = Values::of(el); + let mut result = Self::default(); + for (tag, attribute) in TOGGLES { + let Some(on) = values.boolean(attribute) else { continue }; + let default_on = matches!(*tag, "calt" | "liga" | "locl" | "mark"); + result.features.retain(|feature| feature != tag && feature.strip_prefix('-') != Some(*tag)); + if on != default_on { + result.features.push(if on { (*tag).to_owned() } else { format!("-{tag}") }); + } + result.present = true; + } + if let Some(style) = values.value("OTFFigureStyle") { + let tags: &[&str] = match style.as_str() { + "TabularLining" => &["tnum", "lnum"], + "ProportionalOldstyle" => &["pnum", "onum"], + "ProportionalLining" => &["pnum", "lnum"], + "TabularOldstyle" => &["tnum", "onum"], + "Default" => &[], + _ => &[], + }; + if matches!(style.as_str(), "TabularLining" | "ProportionalOldstyle" | "ProportionalLining" | "TabularOldstyle" | "Default") { + result.features.retain(|feature| !matches!(feature.as_str(), "tnum" | "pnum" | "lnum" | "onum")); + result.features.extend(tags.iter().map(|tag| (*tag).to_owned())); + result.present = true; + } + } + if let Some(mask) = values.num("OTFStylisticSets") { + let mask = mask.max(0.0) as u32; + result.features.retain(|feature| !(feature.len() == 4 && feature.starts_with("ss") && feature[2..].parse::().is_ok())); + result.features.extend((1..=20).filter(|number| mask & (1 << (number - 1)) != 0).map(|number| format!("ss{number:02}"))); + result.present = true; + } + result + } +} + +/// Raw character-level Japanese composition and emphasis properties from an IDML text range. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CjkCharacterValues { + pub kenten_kind: Option, + pub kenten_custom_character: Option, + pub kenten_font: Option, + pub kenten_font_style: Option, + pub kenten_size: Option, + pub kenten_x_scale: Option, + pub kenten_y_scale: Option, + pub kenten_distance: Option, + pub kenten_position: Option, + pub kenten_alignment: Option, + pub kenten_character_set: Option, + pub kenten_fill_color: Option, + pub kenten_stroke_color: Option, + pub kenten_fill_tint: Option, + pub kenten_stroke_tint: Option, + pub kenten_stroke_weight: Option, + pub kenten_overprint_fill: Option, + pub kenten_overprint_stroke: Option, + pub shatai_magnification: Option, + pub shatai_angle: Option, + pub shatai_adjust_rotation: Option, + pub shatai_adjust_tsume: Option, +} + +impl CjkCharacterValues { + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + kenten_kind: values.get("KentenKind").map(str::to_owned), + kenten_custom_character: values.prop("KentenCustomCharacter"), + kenten_font: values.prop("KentenFont"), + kenten_font_style: values.prop("KentenFontStyle"), + kenten_size: values.num("KentenFontSize"), + kenten_x_scale: values.num("KentenXScale"), + kenten_y_scale: values.num("KentenYScale"), + kenten_distance: values.num("KentenPlacement"), + kenten_position: values.prop("KentenPosition"), + kenten_alignment: values.prop("KentenAlignment"), + kenten_character_set: values.prop("KentenCharacterSet"), + kenten_fill_color: values.prop("KentenFillColor"), + kenten_stroke_color: values.prop("KentenStrokeColor"), + kenten_fill_tint: values.num("KentenTint"), + kenten_stroke_tint: values.num("KentenStrokeTint"), + kenten_stroke_weight: values.num("KentenWeight"), + kenten_overprint_fill: values.prop("KentenOverprintFill"), + kenten_overprint_stroke: values.prop("KentenOverprintStroke"), + shatai_magnification: values.num("ShataiMagnification"), + shatai_angle: values.num("ShataiDegreeAngle"), + shatai_adjust_rotation: values.boolean("ShataiAdjustRotation"), + shatai_adjust_tsume: values.boolean("ShataiAdjustTsume"), + } + } +} + +/// Numeric and boolean values in an IDML `MojikumiTable` row. +#[derive(Clone, Debug, PartialEq)] +pub struct MojikumiRow { + pub target_class: i16, + pub side_class: i16, + pub after: bool, + pub minimum: f64, + pub desired: f64, + pub maximum: f64, + pub priority: i16, + pub does_not_float: bool, +} + +impl MojikumiRow { + /// Parses the IDML mojikumi row attributes with bounded integer and finite-number checks. + pub fn from_el(el: &El) -> Result { + let values = Values::of(el); + let number = |key: &str| -> Result { + let Some(raw) = values.get(key) else { return Ok(0.0) }; + raw.trim().parse::().ok().filter(|value| value.is_finite()).ok_or_else(|| format!("Mojikumi row has invalid {key}")) + }; + let integer = |key: &str| -> Result { + let value = number(key)?; + if value.fract() != 0.0 || value < f64::from(i16::MIN) || value > f64::from(i16::MAX) { + return Err(format!("Mojikumi {key} must be an in-range integer")); + } + Ok(value as i16) + }; + let boolean = |key: &str| -> Result { + match values.get(key).map(str::trim) { + None | Some("false") => Ok(false), + Some("true") => Ok(true), + _ => Err(format!("Mojikumi row has invalid {key}")), + } + }; + Ok(Self { + target_class: integer("TargetMojikumiClass")?, + side_class: integer("SideMojikumiClass")?, + after: boolean("SideIsAfterTarget")?, + minimum: number("Minimum")?, + desired: number("Desired")?, + maximum: number("Maximum")?, + priority: integer("CompressionPriority")?, + does_not_float: boolean("AkiDoesNotFloat")?, + }) + } +} + +/// One IDML tab stop, before the caller maps alignment names into its text model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TabStopValues { + pub position: f64, + pub alignment: String, + pub leader: String, + pub alignment_character: String, +} + +impl TabStopValues { + /// Reads `ListItem` records in a `TabList` property. Invalid or non-finite positions use 0, + /// matching IDML import fallback behavior; semantic sanitization belongs to the caller. + pub fn from_list(list: &El) -> Vec { + list.children("ListItem") + .map(|item| { + let text = |name: &str| item.child_text(name).map(|value| value.into_owned()); + Self { + position: text("Position").and_then(|value| value.trim().parse::().ok()).filter(|value| value.is_finite()).unwrap_or(0.0), + alignment: text("Alignment").unwrap_or_default(), + leader: text("Leader").unwrap_or_default(), + alignment_character: text("AlignmentCharacter").unwrap_or_default(), + } + }) + .collect() + } + + /// Writes tab-stop records in a `TabList` property. + pub fn to_list(stops: &[Self]) -> El { + let mut list = El::new("TabList").with_attr("type", "list"); + for stop in stops { + list.push( + El::new("ListItem") + .with_attr("type", "record") + .with_child(property("Alignment", "enumeration", stop.alignment.clone())) + .with_child(property("AlignmentCharacter", "string", stop.alignment_character.clone())) + .with_child(property("Leader", "string", stop.leader.clone())) + .with_child(property("Position", "unit", crate::value::num(stop.position))), + ); + } + list + } +} + /// What a style styles. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StyleKind { @@ -73,6 +1260,65 @@ pub struct StyleGroup { pub children: Vec, } +/// Builds the nested style-folder tree written under an IDML root style group. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StyleGroupWriter { + kind: Option, + root_self_id: String, + styles: Vec, + groups: Vec<(String, StyleGroupWriter)>, +} + +impl StyleGroupWriter { + pub fn new(kind: StyleKind, root_self_id: impl Into) -> Self { + Self { kind: Some(kind), root_self_id: root_self_id.into(), ..Self::default() } + } + + /// Adds a style at its slash-separated folder path. Built-in names in brackets remain at + /// the root, and folder nesting is capped at 32 levels. + pub fn insert(&mut self, name: &str, style: El) { + let builtin = name.starts_with('['); + let mut segments: Vec<&str> = if builtin { vec![name] } else { name.split('/').collect() }; + segments.pop(); + let mut group = self; + for segment in segments.into_iter().take(32) { + let index = match group.groups.iter().position(|(name, _)| name == segment) { + Some(index) => index, + None => { + group.groups.push((segment.to_string(), StyleGroupWriter { kind: group.kind, ..Self::default() })); + group.groups.len() - 1 + } + }; + group = &mut group.groups[index].1; + } + group.styles.push(style); + } + + /// The complete root style group and its nested groups. + pub fn to_el(self) -> El { + let Some(kind) = self.kind else { + return El::new("RootStyleGroup"); + }; + let root_self_id = self.root_self_id.clone(); + self.emit(kind.root(), &root_self_id, kind.group(), "") + } + + fn emit(self, root_name: &str, self_id: &str, group_name: &str, path: &str) -> El { + let mut element = El::new(root_name).with_attr("Self", self_id); + for style in self.styles { + element.push(style); + } + for (name, group) in self.groups { + let full = if path.is_empty() { name.clone() } else { format!("{path}:{name}") }; + let nested = group.emit(group_name, &format!("{group_name}/{}", crate::value::escape_id(&full)), group_name, &full); + let mut nested = nested; + nested.set_attr("Name", name); + element.push(nested); + } + element + } +} + /// A child of a style group, in document order. #[derive(Clone, Debug, PartialEq)] pub enum StyleNode { @@ -81,6 +1327,38 @@ pub enum StyleNode { Other(El), } +/// EPUB export tagging stored on a style in IDML. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EpubExportTagMap { + pub tag: String, + pub class: String, + pub split_document: bool, +} + +impl EpubExportTagMap { + /// Reads an EPUB `StyleExportTagMap`; other export types are not this record. + pub fn from_el(el: &El) -> Option { + let values = Values::of(el); + (el.local() == "StyleExportTagMap" && values.get("ExportType") == Some("EPUB")).then(|| Self { + tag: values.get("ExportTag").unwrap_or("").to_owned(), + class: values.get("ExportClass").unwrap_or("").to_owned(), + split_document: values.get("SplitDocument") == Some("true"), + }) + } + + /// Writes the EPUB tag map with its caller-assigned IDML `Self` identifier. + pub fn to_el(&self, self_id: &str) -> El { + El::new("StyleExportTagMap") + .with_attr("Self", self_id) + .with_attr("ExportType", "EPUB") + .with_attr("ExportTag", &self.tag) + .with_attr("ExportClass", &self.class) + .with_attr("ExportAttributes", "") + .with_attr("SplitDocument", if self.split_document { "true" } else { "false" }) + .with_attr("EmitCss", "true") + } +} + /// A style, its values as written: `Name`, `Self`, `Properties/BasedOn`, its attributes; and its /// other children (an object style's `TextFramePreference`, effect settings, …). #[derive(Clone, Debug, PartialEq)] @@ -90,6 +1368,44 @@ pub struct Style { pub rest: Vec, } +/// Parsed assignments on an IDML object style before application style-reference resolution. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ObjectStyleValues { + pub name: Option, + pub based_on: Option, + pub fill_enabled: bool, + pub fill_color: Option, + pub fill_tint: Option, + pub stroke_enabled: bool, + pub paragraph_style_enabled: bool, + pub paragraph_style: Option, + pub text_frame_general_options: bool, + pub text_frame_preference: Option, +} + +impl ObjectStyleValues { + /// Reads object-style enable flags and the values controlled by those flags. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let enabled = |flag: &str, attribute: &str| match values.get(flag) { + Some(value) => value == "true", + None => values.get(attribute).is_some(), + }; + Self { + name: values.name().map(str::to_owned), + based_on: values.prop("BasedOn"), + fill_enabled: enabled("EnableFill", "FillColor"), + fill_color: values.get("FillColor").map(str::to_owned), + fill_tint: values.num("FillTint"), + stroke_enabled: enabled("EnableStroke", "StrokeColor"), + paragraph_style_enabled: enabled("EnableParagraphStyle", "AppliedParagraphStyle"), + paragraph_style: values.get("AppliedParagraphStyle").map(str::to_owned), + text_frame_general_options: values.get("EnableTextFrameGeneralOptions") == Some("true"), + text_frame_preference: el.child(Local("TextFramePreference")).cloned(), + } + } +} + impl StyleGroup { /// The root group `el`; `None` when `el` is no root style group. pub fn from_el(el: &El) -> Option { @@ -238,6 +1554,14 @@ pub struct GradientStop { pub midpoint: f64, } +/// A `GradientStop` in source order, including optional values as written. +#[derive(Clone, Debug, PartialEq)] +pub struct GradientStopValue { + pub color: Option, + pub location: Option, + pub midpoint: Option, +} + impl Swatch { pub fn to_el(&self) -> El { let mut el = self.values.element(self.kind.name()); @@ -296,6 +1620,22 @@ impl Swatch { }) .collect() } + + /// Every gradient stop in source order, retaining absent or malformed optional values. + pub fn stops_in_order(&self) -> Vec { + self.rest + .iter() + .filter(|e| e.local() == "GradientStop") + .map(|e| { + let values = Values::of(e); + GradientStopValue { + color: values.get("StopColor").map(str::to_string), + location: values.num("Location"), + midpoint: values.num("Midpoint"), + } + }) + .collect() + } } /// The swatches among `top`, in order. @@ -364,6 +1704,360 @@ pub struct ColorGroup { pub rest: Vec, } +/// An Ink Manager entry, preserving its source values. +#[derive(Clone, Debug, PartialEq)] +pub struct Ink { + pub values: Values, +} + +/// A neutral colour definition for writing `Graphic.xml`. +/// +/// The caller supplies colour-space values as IDML's serialized value list; this type owns the +/// element and attribute grammar so applications do not need to emit `Color` XML themselves. +#[derive(Clone, Debug, PartialEq)] +pub struct ColorDefinition { + pub self_id: String, + pub name: String, + pub model: String, + pub space: String, + pub value: String, + pub override_kind: String, + pub editable: bool, + pub removable: bool, + pub visible: bool, +} + +impl ColorDefinition { + pub fn to_el(&self) -> El { + El::new("Color") + .with_attr("Self", &self.self_id) + .with_attr("Model", &self.model) + .with_attr("Space", &self.space) + .with_attr("ColorValue", &self.value) + .with_attr("ColorOverride", &self.override_kind) + .with_attr("AlternateSpace", "NoAlternateColor") + .with_attr("AlternateColorValue", "") + .with_attr("Name", &self.name) + .with_attr("ColorEditable", self.editable) + .with_attr("ColorRemovable", self.removable) + .with_attr("Visible", self.visible) + .with_attr("SwatchCreatorID", "7937") + } +} + +/// A neutral `Ink` definition in `Graphic.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct InkDefinition { + pub self_id: String, + pub name: String, + pub alias: Option, + pub angle: String, + pub convert_to_process: bool, + pub frequency: String, + pub neutral_density: String, + pub trap_order: usize, + pub ink_type: String, +} + +impl InkDefinition { + fn to_el(&self) -> El { + let mut el = El::new("Ink") + .with_attr("Self", &self.self_id) + .with_attr("Name", &self.name) + .with_attr("Angle", &self.angle) + .with_attr("ConvertToProcess", self.convert_to_process) + .with_attr("Frequency", &self.frequency) + .with_attr("NeutralDensity", &self.neutral_density) + .with_attr("PrintInk", "true") + .with_attr("TrapOrder", self.trap_order) + .with_attr("InkType", &self.ink_type); + if let Some(alias) = &self.alias { + el.set_attr("AliasInkName", alias); + } + el + } +} + +/// A neutral `Tint` definition in `Graphic.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct TintDefinition { + pub self_id: String, + pub value: String, + pub base_color: String, + pub name: String, +} + +impl TintDefinition { + fn to_el(&self) -> El { + El::new("Tint") + .with_attr("Self", &self.self_id) + .with_attr("TintValue", &self.value) + .with_attr("BaseColor", &self.base_color) + .with_attr("Name", &self.name) + .with_attr("ColorOverride", "Normal") + .with_attr("AlternateSpace", "NoAlternateColor") + .with_attr("AlternateColorValue", "") + .with_attr("ColorEditable", "true") + .with_attr("ColorRemovable", "true") + .with_attr("Visible", "true") + .with_attr("SwatchCreatorID", "7937") + } +} + +/// A stop in a neutral `Gradient` definition. +#[derive(Clone, Debug, PartialEq)] +pub struct GradientStopDefinition { + pub self_id: String, + pub color_id: String, + pub location: String, + pub midpoint: Option, +} + +/// A neutral `Gradient` definition in `Graphic.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct GradientDefinition { + pub self_id: String, + pub name: String, + pub radial: bool, + pub stops: Vec, +} + +impl GradientDefinition { + fn to_el(&self) -> El { + let mut el = El::new("Gradient") + .with_attr("Self", &self.self_id) + .with_attr("Type", if self.radial { "Radial" } else { "Linear" }) + .with_attr("Name", &self.name) + .with_attr("ColorEditable", "true") + .with_attr("ColorRemovable", "true") + .with_attr("Visible", "true") + .with_attr("SwatchCreatorID", "7937"); + for stop in &self.stops { + let mut child = + El::new("GradientStop").with_attr("Self", &stop.self_id).with_attr("StopColor", &stop.color_id).with_attr("Location", &stop.location); + if let Some(midpoint) = &stop.midpoint { + child.set_attr("Midpoint", midpoint); + } + el.push(child); + } + el + } +} + +/// A member reference in a neutral `ColorGroup` definition. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ColorGroupMember { + pub self_id: String, + pub swatch_id: String, +} + +/// A neutral `ColorGroup` definition in `Graphic.xml`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ColorGroupDefinition { + pub self_id: String, + pub name: String, + pub members: Vec, +} + +impl ColorGroupDefinition { + fn to_el(&self) -> El { + let mut el = El::new("ColorGroup").with_attr("Self", &self.self_id).with_attr("Name", &self.name).with_attr("IsRootColorGroup", "false"); + for member in &self.members { + el.push(El::new("ColorGroupSwatch").with_attr("Self", &member.self_id).with_attr("SwatchItemRef", &member.swatch_id)); + } + el + } +} + +/// A custom stroke style in `Graphic.xml`. +#[derive(Clone, Debug, PartialEq)] +pub enum StrokeDefinition { + Striped { self_id: String, name: String, array: String }, + Dashed { self_id: String, name: String, array: String }, + Dotted { self_id: String, name: String, array: String }, + Named { self_id: String, name: String }, +} + +impl StrokeDefinition { + fn to_el(&self) -> El { + match self { + Self::Striped { self_id, name, array } => { + El::new("StripedStrokeStyle").with_attr("StripeArray", array).with_attr("Self", self_id).with_attr("Name", name) + } + Self::Dashed { self_id, name, array } => { + El::new("DashedStrokeStyle").with_attr("DashArray", array).with_attr("Self", self_id).with_attr("Name", name) + } + Self::Dotted { self_id, name, array } => { + El::new("DottedStrokeStyle").with_attr("DotArray", array).with_attr("Self", self_id).with_attr("Name", name) + } + Self::Named { self_id, name } => El::new("StrokeStyle").with_attr("Self", self_id).with_attr("Name", name), + } + } +} + +/// Semantic values needed to write the `Graphic.xml` part. This type owns element names, +/// attributes, child ordering and the required None swatch; callers supply their mapped values. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct GraphicPart { + pub colors: Vec, + pub inks: Vec, + pub tints: Vec, + pub gradients: Vec, + pub color_groups: Vec, + pub stroke_styles: Vec, +} + +impl GraphicPart { + pub fn to_el(&self) -> El { + let mut root = crate::part_root("Graphic"); + for color in &self.colors { + root.push(color.to_el()); + } + for ink in &self.inks { + root.push(ink.to_el()); + } + for tint in &self.tints { + root.push(tint.to_el()); + } + root.push( + El::new("Swatch") + .with_attr("Self", "Swatch/None") + .with_attr("Name", "None") + .with_attr("ColorEditable", "false") + .with_attr("ColorRemovable", "false") + .with_attr("Visible", "true") + .with_attr("SwatchCreatorID", "7937"), + ); + for gradient in &self.gradients { + root.push(gradient.to_el()); + } + for group in &self.color_groups { + root.push(group.to_el()); + } + for style in &self.stroke_styles { + root.push(style.to_el()); + } + root + } +} + +/// A composite-font entry, including the applied font family stored in `Properties`. +#[derive(Clone, Debug, PartialEq)] +pub struct CompositeFontEntryDefinition { + pub self_id: String, + pub name: String, + pub characters: String, + pub font_style: String, + pub relative_size: String, + pub horizontal_scale: String, + pub vertical_scale: String, + pub baseline_shift: String, + pub scale_option: bool, + pub applied_font: String, +} + +/// A composite font in `Fonts.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct CompositeFontDefinition { + pub self_id: String, + pub name: String, + pub entries: Vec, +} + +/// A font face in a family in `Fonts.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct FontDefinition { + pub self_id: String, + pub family: String, + pub name: String, + pub postscript_name: String, + pub style: String, +} + +/// A family of font faces in `Fonts.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct FontFamilyDefinition { + pub self_id: String, + pub name: String, + pub fonts: Vec, +} + +/// Neutral data for writing the complete `Fonts.xml` part. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FontsPart { + pub composites: Vec, + pub families: Vec, +} + +impl FontsPart { + pub fn to_el(&self) -> El { + let mut root = crate::part_root("Fonts"); + for composite in &self.composites { + let mut element = El::new("CompositeFont").with_attr("Self", &composite.self_id).with_attr("Name", &composite.name); + for entry in &composite.entries { + let mut node = El::new("CompositeFontEntry") + .with_attr("Self", &entry.self_id) + .with_attr("Name", &entry.name) + .with_attr("CustomCharacters", &entry.characters) + .with_attr("FontStyle", &entry.font_style) + .with_attr("RelativeSize", &entry.relative_size) + .with_attr("HorizontalScale", &entry.horizontal_scale) + .with_attr("VerticalScale", &entry.vertical_scale) + .with_attr("BaselineShift", &entry.baseline_shift) + .with_attr("ScaleOption", entry.scale_option); + let mut properties = El::new("Properties"); + properties.push(crate::prop("AppliedFont", "string", &entry.applied_font)); + node.push(properties); + element.push(node); + } + root.push(element); + } + for family in &self.families { + let mut element = El::new("FontFamily").with_attr("Self", &family.self_id).with_attr("Name", &family.name); + for font in &family.fonts { + element.push( + El::new("Font") + .with_attr("Self", &font.self_id) + .with_attr("FontFamily", &font.family) + .with_attr("Name", &font.name) + .with_attr("PostScriptName", &font.postscript_name) + .with_attr("Status", "NotAvailable") + .with_attr("FontStyleName", &font.style) + .with_attr("FontType", "OpenTypeTT") + .with_attr("WritingScript", "0") + .with_attr("FullName", &font.name) + .with_attr("FullNameNative", &font.name) + .with_attr("FontStyleNameNative", &font.style) + .with_attr("PlatformName", "$ID/") + .with_attr("Version", "$ID/") + .with_attr("TypekitID", "$ID/"), + ); + } + root.push(element); + } + root + } +} + +impl Ink { + pub fn name(&self) -> Option<&str> { + self.values.name() + } + + pub fn convert_to_process(&self) -> bool { + self.values.get("ConvertToProcess") == Some("true") + } + + pub fn alias(&self) -> Option<&str> { + self.values.get("AliasInkName") + } +} + +/// Ink Manager entries among the document's top-level elements. +pub fn inks(top: &[El]) -> Vec { + top.iter().filter(|el| el.local() == "Ink").map(|el| Ink { values: Values::of(el) }).collect() +} + impl ColorGroup { pub fn to_el(&self) -> El { let mut el = self.values.element("ColorGroup"); diff --git a/crates/idml/src/model/spread.rs b/crates/idml/src/model/spread.rs index c4d535f89..e3f317c07 100644 --- a/crates/idml/src/model/spread.rs +++ b/crates/idml/src/model/spread.rs @@ -17,6 +17,60 @@ fn with_children(mut el: El, children: impl IntoIterator) -> El { el } +/// Raw clip-path settings attached to a placed graphic, before the caller maps type and +/// coordinates into its scene model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ClippingPathValues { + pub clipping_type: Option, + pub geometry: PathGeometry, + pub invert: Option, + pub include_inside_edges: Option, + pub restrict_to_frame: Option, + pub use_high_resolution: Option, + pub threshold: Option, + pub tolerance: Option, + pub inset: Option, + pub source_name: Option, + pub index: Option, +} + +impl ClippingPathValues { + /// Reads a graphic's `ClippingPathSettings` and saved geometry, with the caller's point cap. + pub fn from_graphic(graphic: &El, max_points: usize) -> Option { + let settings = graphic.find("ClippingPathSettings")?; + let settings_values = Values::of(settings); + let graphic_values = Values::of(graphic); + let clipping_type = settings_values.get("ClippingType").map(str::to_owned); + let invert = settings_values.boolean("InvertPath"); + let include_inside_edges = settings_values.boolean("IncludeInsideEdges"); + let restrict_to_frame = settings_values.boolean("RestrictToFrame"); + let use_high_resolution = settings_values.boolean("UseHighResolutionImage"); + let threshold = settings_values.num("Threshold"); + let tolerance = settings_values.num("Tolerance"); + let inset = settings_values.num("InsetFrame"); + let source_name = settings_values.get("AppliedPathName").map(str::to_owned); + let index = settings_values.num("Index"); + let geometry = settings_values + .prop_el("ClippingPathGeometry") + .or_else(|| settings.find("ClippingPathGeometry")) + .or_else(|| graphic_values.prop_el("ClippingPathGeometry"))?; + let geometry = PathGeometry::from_el_capped(geometry, max_points); + Some(Self { + clipping_type, + geometry, + invert, + include_inside_edges, + restrict_to_frame, + use_high_resolution, + threshold, + tolerance, + inset, + source_name, + index, + }) + } +} + /// A spread (`Spread`) or a parent spread (`MasterSpread`). #[derive(Clone, Debug, Default, PartialEq)] pub struct Spread { @@ -86,6 +140,52 @@ impl Spread { pub fn parent_name(&self) -> Option<(&str, &str)> { Some((self.values.get("NamePrefix")?, self.values.get("BaseName")?)) } + + /// Parent spread's prefix, using the prefix of `Name` or `A` when absent. + pub fn parent_prefix(&self) -> String { + self.values.get("NamePrefix").map(str::to_string).unwrap_or_else(|| self.name().split('-').next().unwrap_or("A").to_string()) + } + + /// Parent spread's base name, using the suffix of `Name` or `Parent` when absent. + pub fn base_name(&self) -> String { + self.values + .get("BaseName") + .map(str::to_string) + .unwrap_or_else(|| self.name().split_once('-').map(|(_, b)| b.to_string()).unwrap_or_else(|| self.name().to_string())) + } + + pub fn name(&self) -> &str { + self.values.name().unwrap_or("Parent") + } + + /// Whether master page items are shown. + pub fn show_master_items(&self) -> bool { + self.values.boolean("ShowMasterItems") != Some(false) + } + + /// Whether page shuffle is allowed. + pub fn allow_shuffle(&self) -> bool { + self.values.boolean("AllowPageShuffle") != Some(false) + } + + /// Exact quarter-turn view rotation encoded by the spread transform, clockwise on screen. + pub fn view_rotation(&self) -> u8 { + if self.master { + return 0; + } + let [a, b, c, d, _, _] = self.values.item_transform(); + let is = |x: f64, y: f64| (x - y).abs() < 1e-6; + let quarter = |m: [f64; 4]| is(a, m[0]) && is(b, m[1]) && is(c, m[2]) && is(d, m[3]); + if quarter([0.0, 1.0, -1.0, 0.0]) { + 1 + } else if quarter([-1.0, 0.0, 0.0, -1.0]) { + 2 + } else if quarter([0.0, -1.0, 1.0, 0.0]) { + 3 + } else { + 0 + } + } } /// The spreads and parent spreads of a document, in its order. @@ -100,6 +200,44 @@ pub struct Page { pub children: Vec, } +/// Parsed layout values of an IDML `MarginPreference`. +#[derive(Clone, Debug, PartialEq)] +pub struct MarginPreference { + pub values: Values, +} + +impl MarginPreference { + pub fn from_el(el: &El) -> Self { + Self { values: Values::of(el) } + } + pub fn top(&self) -> Option { + self.values.num("Top") + } + pub fn left(&self) -> Option { + self.values.num("Left") + } + pub fn bottom(&self) -> Option { + self.values.num("Bottom") + } + pub fn right(&self) -> Option { + self.values.num("Right") + } + pub fn column_count(&self) -> Option { + self.values.num("ColumnCount") + } + pub fn column_gutter(&self) -> Option { + self.values.num("ColumnGutter") + } + + /// Parse at most `limit` whitespace-separated `ColumnsPositions` values; malformed or + /// non-finite values invalidate the list. + pub fn column_positions(&self, limit: usize) -> Option> { + let source = self.values.get("ColumnsPositions")?; + let values: Option> = source.split_whitespace().take(limit).map(|v| v.parse::().ok().filter(|v| v.is_finite())).collect(); + values.filter(|values| !values.is_empty()) + } +} + /// A child of a page, in document order. #[derive(Clone, Debug, PartialEq)] pub enum PageChild { @@ -142,6 +280,20 @@ impl Page { self.values.get("AppliedMaster").filter(|m| *m != "n") } + pub fn self_id(&self) -> Option<&str> { + self.values.self_id() + } + + /// `ItemTransform`; the identity when absent or malformed. + pub fn item_transform(&self) -> Matrix { + self.values.item_transform() + } + + /// `LayoutRule`, defaulting to `Off`. + pub fn layout_rule(&self) -> &str { + self.values.get("LayoutRule").unwrap_or("Off") + } + /// `OverrideList`: the `Self`s of the parent items overridden on this page. pub fn override_list(&self) -> Vec<&str> { self.values.get("OverrideList").map(|l| l.split_whitespace().collect()).unwrap_or_default() @@ -155,6 +307,10 @@ impl Page { }) } + pub fn margin_settings(&self) -> Option { + self.margin_preference().map(|values| MarginPreference { values }) + } + pub fn guides(&self) -> impl DoubleEndedIterator { self.children.iter().filter_map(|c| if let PageChild::Guide(g) = c { Some(g) } else { None }) } @@ -188,6 +344,16 @@ impl Guide { pub fn liquid(&self) -> bool { self.values.get("GuideType") == Some("Liquid") } + + /// `Locked` is true. + pub fn locked(&self) -> bool { + self.values.boolean("Locked") == Some(true) + } + + /// `ItemLayer`: the identifier of the layer the guide belongs to. + pub fn item_layer(&self) -> Option<&str> { + self.values.item_layer() + } } /// What a page item is. @@ -297,6 +463,61 @@ impl PageItem { self.values.prop_el("PathGeometry").map(PathGeometry::from_el).unwrap_or_default() } + pub fn self_id(&self) -> Option<&str> { + self.values.self_id() + } + + pub fn item_layer(&self) -> Option<&str> { + self.values.item_layer() + } + + pub fn item_transform(&self) -> Matrix { + self.values.item_transform() + } + + pub fn name(&self) -> Option<&str> { + self.values.name() + } + + pub fn locked(&self) -> bool { + self.values.locked() + } + + pub fn hidden(&self) -> bool { + !self.values.visible() + } + + pub fn nonprinting(&self) -> bool { + self.values.boolean("Nonprinting") == Some(true) + } + + pub fn gradient_fill_angle(&self) -> Option { + self.values.num("GradientFillAngle") + } + pub fn gradient_fill_start(&self) -> Option<[f64; 2]> { + self.values.pair("GradientFillStart") + } + pub fn gradient_fill_length(&self) -> Option { + self.values.num("GradientFillLength") + } + pub fn gradient_stroke_angle(&self) -> Option { + self.values.num("GradientStrokeAngle") + } + pub fn gradient_stroke_start(&self) -> Option<[f64; 2]> { + self.values.pair("GradientStrokeStart") + } + pub fn gradient_stroke_length(&self) -> Option { + self.values.num("GradientStrokeLength") + } + + pub fn text_path(&self) -> Option { + self.other("TextPath").map(|el| TextPath { values: Values::of(el) }) + } + + pub fn text_wrap(&self) -> Option { + self.other("TextWrapPreference").map(TextWrapPreference::from_el) + } + /// Replaces the outline. pub fn set_geometry(&mut self, g: &PathGeometry) { self.values.set_prop_el("PathGeometry", Some(g.to_el())); @@ -346,6 +567,169 @@ impl PageItem { } } +/// Parsed IDML `TextWrapPreference` values, including the nested offset and contour elements. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TextWrapPreference { + values: Values, + contour_type: Option, + offsets: Option<[f64; 4]>, +} + +/// Parsed IDML frame fitting options. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FrameFittingOption { + pub crop: [Option; 4], + pub alignment: Option, + pub auto_fit: bool, + pub fitting_on_empty_frame: Option, +} + +impl FrameFittingOption { + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + crop: [values.num("TopCrop"), values.num("LeftCrop"), values.num("BottomCrop"), values.num("RightCrop")], + alignment: values.get("FittingAlignment").map(str::to_owned), + auto_fit: values.boolean("AutoFit") == Some(true), + fitting_on_empty_frame: values.get("FittingOnEmptyFrame").map(str::to_owned), + } + } +} + +/// IDML baseline-grid position relative to a page, frame, or inset. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum BaselineFrameGridRelative { + TopMargin, + TopOfFrame, + TopInset, + #[default] + TopOfPage, +} + +/// Parsed IDML custom baseline-grid options on an item or object style. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct BaselineFrameGridOption { + pub use_custom: bool, + pub start: f64, + pub increment: f64, + pub relative_to: BaselineFrameGridRelative, +} + +impl BaselineFrameGridOption { + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let relative = values.get("BaselineFrameGridRelativeOption").unwrap_or(""); + let relative = relative.strip_suffix("OfBaselineFrameGridRelativeOption").unwrap_or(relative); + let relative_to = match relative { + "TopOfMargin" | "TopMargin" => BaselineFrameGridRelative::TopMargin, + "TopOfFrame" => BaselineFrameGridRelative::TopOfFrame, + "TopOfInset" | "TopInset" => BaselineFrameGridRelative::TopInset, + _ => BaselineFrameGridRelative::TopOfPage, + }; + Self { + use_custom: values.boolean("UseCustomBaselineFrameGrid") == Some(true), + start: values.num("StartingOffsetForBaselineFrameGrid").unwrap_or(0.0), + increment: values.num("BaselineFrameGridIncrement").unwrap_or(12.0), + relative_to, + } + } +} + +impl TextWrapPreference { + pub fn from_el(el: &El) -> Self { + let contour_type = el.child(Local("ContourOption")).and_then(|c| Values::of(c).get("ContourType").map(str::to_string)); + let offsets = el.child(Local("Properties")).and_then(|p| p.child(Local("TextWrapOffset"))).map(|o| { + let values = Values::of(o); + [ + values.num("Top").unwrap_or(0.0), + values.num("Left").unwrap_or(0.0), + values.num("Bottom").unwrap_or(0.0), + values.num("Right").unwrap_or(0.0), + ] + }); + Self { values: Values::of(el), contour_type, offsets } + } + + pub fn mode(&self) -> Option<&str> { + self.values.get("TextWrapMode") + } + pub fn inverse(&self) -> bool { + self.values.boolean("Inverse") == Some(true) + } + pub fn side(&self) -> Option<&str> { + self.values.get("TextWrapSide") + } + pub fn contour_type(&self) -> Option<&str> { + self.contour_type.as_deref() + } + pub fn offsets(&self) -> Option<[f64; 4]> { + self.offsets + } + + /// Writes the IDML preference structure around caller-supplied enum values and path geometry. + pub fn to_el(mode: &str, inverse: bool, side: &str, contour: &str, offsets: [f64; 4], paths: &[PathGeometry]) -> El { + use crate::value::num; + + let mut properties = El::new("Properties"); + for path in paths { + properties.push(path.to_el()); + } + properties.push( + El::new("TextWrapOffset") + .with_attr("Top", num(offsets[0])) + .with_attr("Left", num(offsets[1])) + .with_attr("Bottom", num(offsets[2])) + .with_attr("Right", num(offsets[3])), + ); + El::new("TextWrapPreference") + .with_attr("Inverse", if inverse { "true" } else { "false" }) + .with_attr("ApplyToMasterPageOnly", "false") + .with_attr("TextWrapSide", side) + .with_attr("TextWrapMode", mode) + .with_child(properties) + .with_child(El::new("ContourOption").with_attr("ContourType", contour).with_attr("IncludeInsideEdges", "false")) + } +} + +/// Type-on-a-path settings. +#[derive(Clone, Debug, PartialEq)] +pub struct TextPath { + pub values: Values, +} + +impl TextPath { + /// Writes IDML type-on-a-path settings for a frame and its story. + pub fn to_el(frame_self: &str, parent_story: &str, alignment: &str, flipped: bool, start: f64, end: f64) -> El { + El::new("TextPath") + .with_attr("Self", format!("{frame_self}tp")) + .with_attr("ParentStory", parent_story) + .with_attr("PreviousTextFrame", "n") + .with_attr("NextTextFrame", "n") + .with_attr("PathEffect", "RainbowPathEffect") + .with_attr("PathAlignment", "CenterPathAlignment") + .with_attr("TextAlignment", alignment) + .with_attr("FlipPathEffect", if flipped { "Flipped" } else { "NotFlipped" }) + .with_attr("StartBracket", crate::value::num(start)) + .with_attr("EndBracket", crate::value::num(end)) + } + + pub fn parent_story(&self) -> Option<&str> { + self.values.get("ParentStory").filter(|s| *s != "n") + } + pub fn start_bracket(&self) -> Option { + self.values.num("StartBracket") + } + pub fn end_bracket(&self) -> Option { + self.values.num("EndBracket") + } + pub fn flipped(&self) -> bool { + self.values.get("FlipPathEffect") == Some("Flipped") + } + pub fn alignment(&self) -> Option<&str> { + self.values.get("TextAlignment") + } +} + /// What a placed graphic is. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum GraphicKind { @@ -420,6 +804,119 @@ impl Link { } } +/// A placed graphic's layer choices, independent of the document model that stores them. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct GraphicLayerOptions { + pub attributes: Vec<(String, String)>, + pub layers: Vec>, + /// Parent indices in pre-order. Missing entries and invalid parents are treated as top-level. + pub parents: Vec>, +} + +impl GraphicLayerOptions { + /// Reads a `GraphicLayerOption` subtree while preserving layer order and hierarchy. + pub fn from_el(option: &El) -> Self { + let attributes = option.attrs.iter().filter(|(key, _)| key != "Self").cloned().collect(); + let mut roots: Vec<_> = option.elements().collect(); + roots.reverse(); + let mut pending: Vec<_> = roots.into_iter().map(|element| (element, None)).collect(); + let mut layers = Vec::new(); + let mut parents = Vec::new(); + while let Some((element, parent)) = pending.pop() { + let layer_parent = if element.local() == "GraphicLayer" { + let index = layers.len(); + layers.push(element.attrs.iter().filter(|(key, _)| key != "Self").cloned().collect()); + parents.push(parent); + Some(index) + } else { + parent + }; + let mut children: Vec<_> = element.elements().collect(); + children.reverse(); + pending.extend(children.into_iter().map(|child| (child, layer_parent))); + } + Self { attributes, layers, parents } + } + + /// Serializes this layer tree, generating fresh IDs for the option and each layer. + pub fn to_el(&self, self_id: &str, mut fresh: impl FnMut() -> String) -> El { + let mut option = El::new("GraphicLayerOption").with_attr("Self", self_id); + for (key, value) in &self.attributes { + if valid_layer_attribute(key) { + option.set_attr(key, value); + } + } + // A parent must still be open in the pre-order walk. IDML layer groups have a depth cap. + let mut open = Vec::new(); + let mut parents = Vec::with_capacity(self.layers.len()); + for index in 0..self.layers.len() { + let parent = self.parents.get(index).copied().flatten(); + if let Some(at) = parent.and_then(|parent| open.iter().position(|id| *id == parent)).filter(|at| *at < 239) { + open.truncate(at + 1); + parents.push(parent); + } else { + open.clear(); + parents.push(None); + } + open.push(index); + } + let mut children: Vec> = (0..self.layers.len()).map(|_| Vec::new()).collect(); + let mut roots = Vec::new(); + for (index, attributes) in self.layers.iter().enumerate().rev() { + let mut layer = El::new("GraphicLayer").with_attr("Self", fresh()); + for (key, value) in attributes { + if valid_layer_attribute(key) { + layer.set_attr(key, value); + } + } + if let Some(nested) = children.get_mut(index) { + for child in std::mem::take(nested).into_iter().rev() { + layer.push(child); + } + } + if let Some(nested) = parents.get(index).copied().flatten().and_then(|parent| children.get_mut(parent)) { + nested.push(layer); + } else { + roots.push(layer); + } + } + for layer in roots.into_iter().rev() { + option.push(layer); + } + option + } +} + +fn valid_layer_attribute(key: &str) -> bool { + !key.is_empty() + && key != "Self" + && key != "xmlns" + && key + .bytes() + .enumerate() + .all(|(index, byte)| byte.is_ascii_alphabetic() || byte == b'_' || (index > 0 && (byte.is_ascii_digit() || matches!(byte, b'.' | b'-')))) +} + +/// A placed PDF's import options. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PdfAttribute { + values: Values, +} + +impl PdfAttribute { + pub fn page_index(&self) -> u32 { + self.values + .get("PageNumber") + .and_then(|value| value.trim().parse::().ok()) + .and_then(|page| u32::try_from(page.saturating_sub(1)).ok()) + .unwrap_or(0) + } + + pub fn crop(&self) -> Option<&str> { + self.values.get("PDFCrop") + } +} + impl Graphic { pub fn from_el(el: &El) -> Option { let kind = GraphicKind::of(el.local())?; @@ -449,6 +946,83 @@ impl Graphic { self.children.iter().find_map(|c| if let GraphicChild::Link(l) = c { Some(l) } else { None }) } + pub fn self_id(&self) -> Option<&str> { + self.values.self_id() + } + + pub fn applied_object_style(&self) -> Option<&str> { + self.values.get("AppliedObjectStyle") + } + + pub fn item_transform(&self) -> Matrix { + self.values.item_transform() + } + + /// GraphicBounds in IDML's `Left`, `Top`, `Right`, `Bottom` order. + pub fn bounds(&self) -> [f64; 4] { + self.values + .prop_el("GraphicBounds") + .map(Values::of) + .map(|values| ["Left", "Top", "Right", "Bottom"].map(|key| values.num(key).unwrap_or(0.0))) + .unwrap_or([0.0; 4]) + } + + /// Two finite values from InDesign's `ActualPpi` field. + pub fn actual_ppi(&self) -> Option<[f64; 2]> { + let source = self.values.get("ActualPpi")?; + let numbers: Vec = source.split_whitespace().take(3).filter_map(|value| value.parse().ok()).collect(); + <[f64; 2]>::try_from(numbers).ok().filter(|values| values.iter().all(|value| value.is_finite())) + } + + pub fn fill_color(&self) -> Option<&str> { + self.values.get("FillColor") + } + + pub fn fill_tint(&self) -> Option { + self.values.num("FillTint") + } + + /// The MIME fallback when a linked graphic's bytes cannot be sniffed. + pub fn fallback_mime(&self) -> &'static str { + let format = self.link().and_then(Link::format).unwrap_or(""); + match format { + value if value.contains("EPS") || self.kind == GraphicKind::EPS => "application/postscript", + value if value.contains("JPEG") => "image/jpeg", + value if value.contains("TIFF") => "image/tiff", + value if value.contains("PDF") || self.kind == GraphicKind::PDF => "application/pdf", + value if value.contains("GIF") => "image/gif", + _ => "image/png", + } + } + + pub fn layer_options(&self) -> Option { + self.children + .iter() + .find_map(|child| match child { + GraphicChild::Other(el) if el.local() == "GraphicLayerOption" => Some(el), + GraphicChild::Other(el) => el.find("GraphicLayerOption"), + GraphicChild::Link(link) => { + link.rest.iter().find_map(|el| if el.local() == "GraphicLayerOption" { Some(el) } else { el.find("GraphicLayerOption") }) + } + }) + .or_else(|| self.values.prop_el("GraphicLayerOption")) + .map(GraphicLayerOptions::from_el) + } + + pub fn pdf_attribute(&self) -> Option { + self.children + .iter() + .find_map(|child| match child { + GraphicChild::Other(el) if el.local() == "PDFAttribute" => Some(el), + GraphicChild::Other(el) => el.find("PDFAttribute"), + GraphicChild::Link(link) => { + link.rest.iter().find_map(|el| if el.local() == "PDFAttribute" { Some(el) } else { el.find("PDFAttribute") }) + } + }) + .or_else(|| self.values.prop_el("PDFAttribute")) + .map(|el| PdfAttribute { values: Values::of(el) }) + } + /// `Properties/GraphicBounds`: `top left bottom right` in the graphic's inner coordinates. pub fn graphic_bounds(&self) -> Option<[f64; 4]> { let b = self.values.prop_el("GraphicBounds")?; diff --git a/crates/idml/src/model/story.rs b/crates/idml/src/model/story.rs index 889c7b350..38839b0d3 100644 --- a/crates/idml/src/model/story.rs +++ b/crates/idml/src/model/story.rs @@ -2,9 +2,116 @@ //! anchored page items, hyperlink and change containers). use craft_xml::{El, Local, Node}; +use std::collections::{BTreeMap, HashMap}; use super::{PageItem, Values, tidy}; +/// Resolved IDML anchored-object options from an item and its inherited style levels. +#[derive(Clone, Debug, PartialEq)] +pub struct AnchoredObjectValues { + pub position: String, + pub anchor_point: String, + pub horizontal_alignment: String, + pub horizontal_reference: String, + pub vertical_alignment: String, + pub vertical_reference: String, + pub pin_position: bool, + pub spine_relative: bool, + pub space_above: f64, + pub x_offset: f64, + pub y_offset: f64, +} + +/// An IDML `AnchoredObjectSetting` element. +#[derive(Clone, Debug, PartialEq)] +pub struct AnchoredObjectSetting { + attributes: Vec<(String, String)>, +} + +impl AnchoredObjectSetting { + pub fn inline_position(y_offset: f64) -> Self { + Self { attributes: vec![("AnchoredPosition".into(), "InlinePosition".into()), ("AnchorYoffset".into(), crate::value::num(y_offset))] } + } + + pub fn above_line(horizontal_alignment: &str, space_above: f64, y_offset: f64) -> Self { + Self { + attributes: vec![ + ("AnchoredPosition".into(), "AboveLine".into()), + ("HorizontalAlignment".into(), horizontal_alignment.into()), + ("AnchorSpaceAbove".into(), crate::value::num(space_above)), + ("AnchorYoffset".into(), crate::value::num(y_offset)), + ], + } + } + + #[allow(clippy::too_many_arguments)] + pub fn anchored( + anchor_point: &str, + horizontal_reference: &str, + vertical_reference: &str, + horizontal_alignment: &str, + vertical_alignment: &str, + x_offset: f64, + y_offset: f64, + pin_position: bool, + spine_relative: bool, + ) -> Self { + Self { + attributes: vec![ + ("AnchoredPosition".into(), "Anchored".into()), + ("AnchorPoint".into(), anchor_point.into()), + ("HorizontalReferencePoint".into(), horizontal_reference.into()), + ("VerticalReferencePoint".into(), vertical_reference.into()), + ("HorizontalAlignment".into(), horizontal_alignment.into()), + ("VerticalAlignment".into(), vertical_alignment.into()), + ("AnchorXoffset".into(), crate::value::num(x_offset)), + ("AnchorYoffset".into(), crate::value::num(y_offset)), + ("PinPosition".into(), bool_string(pin_position)), + ("SpineRelative".into(), bool_string(spine_relative)), + ], + } + } + + pub fn to_el(&self) -> El { + let mut element = El::new("AnchoredObjectSetting"); + for (key, value) in &self.attributes { + element.set_attr(key, value); + } + element + } +} + +fn bool_string(value: bool) -> String { + if value { "true" } else { "false" }.into() +} + +impl AnchoredObjectValues { + /// Resolves attributes item-first from `AnchoredObjectSetting` children. + pub fn from_elements(elements: &[&El]) -> Self { + let get = |key: &str, default: &str| { + elements + .iter() + .filter_map(|element| element.child(Local("AnchoredObjectSetting"))) + .find_map(|setting| Values::of(setting).get(key).map(str::to_owned)) + .unwrap_or_else(|| default.to_owned()) + }; + let number = |key: &str| get(key, "0").parse::().ok().filter(|value| value.is_finite()).unwrap_or(0.0); + Self { + position: get("AnchoredPosition", "InlinePosition"), + anchor_point: get("AnchorPoint", "BottomRightAnchor"), + horizontal_alignment: get("HorizontalAlignment", "LeftAlign"), + horizontal_reference: get("HorizontalReferencePoint", "TextFrame"), + vertical_alignment: get("VerticalAlignment", "BottomAlign"), + vertical_reference: get("VerticalReferencePoint", "LineBaseline"), + pin_position: get("PinPosition", "true") == "true", + spine_relative: get("SpineRelative", "false") == "true", + space_above: number("AnchorSpaceAbove"), + x_offset: number("AnchorXoffset"), + y_offset: number("AnchorYoffset"), + } + } +} + /// A `Story`. #[derive(Clone, Debug, Default, PartialEq)] pub struct Story { @@ -12,6 +119,26 @@ pub struct Story { pub children: Vec, } +/// The IDML `StoryPreference` element written for a story. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StoryPreference { + pub optical_margin_alignment: bool, + pub optical_margin_size: f64, + pub vertical: bool, + pub right_to_left: bool, +} + +impl StoryPreference { + pub fn to_el(self) -> El { + El::new("StoryPreference") + .with_attr("OpticalMarginAlignment", self.optical_margin_alignment) + .with_attr("OpticalMarginSize", self.optical_margin_size) + .with_attr("FrameType", "TextFrameType") + .with_attr("StoryOrientation", if self.vertical { "Vertical" } else { "Horizontal" }) + .with_attr("StoryDirection", if self.right_to_left { "RightToLeftDirection" } else { "LeftToRightDirection" }) + } +} + /// One node of a story's text, in document order. IDML nests freely (an `XMLElement` or a /// `HyperlinkTextSource` can hold paragraph ranges or content), so every container holds these. #[derive(Clone, Debug, PartialEq)] @@ -24,10 +151,19 @@ pub enum TextNode { Content(Vec), /// `Br`: the end of a paragraph. Break, + /// A processing instruction at a structural story position. The parent serializer preserves + /// it in place; `to_el` represents it as a one-instruction `Content` fragment. + ProcessingInstruction { + target: String, + data: String, + }, /// Text inside another element ([`CONTAINERS`]): a hyperlink's source, a tracked change, an /// XML element, a cross-reference's source, a footnote, a note. Container(Container), Table(Table), + Anchor(StoryAnchor), + PageReference(PageReference), + TextVariable(Values), /// A page item anchored in the text. Item(PageItem), /// Anything else (`StoryPreference`, `HyperlinkTextDestination`, `TextVariableInstance`, …), @@ -35,6 +171,264 @@ pub enum TextNode { Other(El), } +#[derive(Clone, Debug, PartialEq)] +pub struct StoryAnchor { + pub name: String, + pub values: Values, +} + +impl StoryAnchor { + /// Builds the IDML `Self` value for a hyperlink text destination. + pub fn destination_self(id: u64) -> String { + format!("HyperlinkTextDestination/a{id}") + } + + /// Writes an IDML `HyperlinkTextDestination` from a DesignCraft-independent anchor identity. + pub fn destination_el(id: u64, name: &str) -> El { + El::new("HyperlinkTextDestination") + .with_attr("Self", Self::destination_self(id)) + .with_attr("Name", name) + .with_attr("Hidden", "false") + .with_attr("DestinationUniqueKey", id & 0xFFFF_FFFF) + } + + pub fn self_id(&self) -> Option<&str> { + self.values.self_id() + } + pub fn label(&self) -> Option<&str> { + self.values.name() + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PageReference { + pub values: Values, +} + +/// Nested index topics and their See / See also references for one IDML `Index`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct IndexValues { + pub topics: BTreeMap, String>, + pub cross_references: Vec, +} + +/// An index cross-reference attached to a topic path. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IndexCrossReferenceValues { + pub from: Vec, + pub reference_type: String, + pub target: String, +} + +/// A topic path and its sort keys, as they are saved on nested IDML `Topic` elements. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct IndexTopicPath { + pub path: Vec, + pub sort: Vec, +} + +/// An IDML index cross-reference as stored under an index topic. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct IndexReference { + pub from: IndexTopicPath, + pub referenced_topic: Option, + pub reference_type: Option, +} + +/// Parsed IDML index topics and cross-references. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct IndexDocument { + pub topics: HashMap, + pub cross_references: Vec, +} + +impl IndexDocument { + pub fn from_el(element: &El) -> Self { + let mut result = Self::default(); + let mut stack: Vec<(&El, IndexTopicPath)> = + element.elements().filter(|child| child.local() == "Topic").map(|topic| (topic, IndexTopicPath::default())).collect(); + while let Some((topic, prefix)) = stack.pop() { + let name = topic.attr("Name").unwrap_or_default().to_string(); + let mut current = prefix.clone(); + current.path.push(name); + if let Some(key) = topic.attr("SortOrder").filter(|key| !key.is_empty()) { + current.sort.resize(prefix.path.len(), String::new()); + current.sort.push(key.to_string()); + } + if let Some(self_id) = topic.attr("Self") { + result.topics.insert(self_id.to_string(), current.clone()); + } + for child in topic.elements() { + if child.local() == "CrossReference" { + result.cross_references.push(IndexReference { + from: current.clone(), + referenced_topic: child.attr("ReferencedTopic").map(str::to_string), + reference_type: child.attr("CrossReferenceType").map(str::to_string), + }); + } else if child.local() == "Topic" { + stack.push((child, current.clone())); + } + } + } + result + } +} + +impl IndexValues { + /// Builds the IDML `Self` value for a topic path. + pub fn topic_self(path: &[String]) -> String { + let mut id = String::from("ix"); + for part in path { + id.push_str("Topicn"); + id.push_str(&crate::value::escape_id(part)); + } + id + } + + /// Writes the nested IDML index grammar, assigning a fresh ID to each cross-reference. + pub fn to_el(&self, mut fresh: impl FnMut() -> String) -> El { + let mut topics = self.topics.clone(); + for reference in &self.cross_references { + topics.entry(vec![reference.target.clone()]).or_default(); + } + + fn build( + topics: &BTreeMap, String>, + references: &[IndexCrossReferenceValues], + prefix: &[String], + fresh: &mut impl FnMut() -> String, + ) -> Vec { + let mut out = Vec::new(); + for (path, sort_order) in topics.iter().filter(|(path, _)| path.len() == prefix.len() + 1 && path.starts_with(prefix)) { + let mut element = El::new("Topic") + .with_attr("Self", IndexValues::topic_self(path)) + .with_attr("SortOrder", sort_order) + .with_attr("Name", path.last().map_or("", String::as_str)); + for reference in references.iter().filter(|reference| reference.from == *path) { + element.push( + El::new("CrossReference") + .with_attr("Self", fresh()) + .with_attr("ReferencedTopic", IndexValues::topic_self(std::slice::from_ref(&reference.target))) + .with_attr("CrossReferenceType", &reference.reference_type) + .with_attr("CustomTypeString", ""), + ); + } + element.children.extend(build(topics, references, path, fresh).into_iter().map(Node::El)); + out.push(element); + } + out + } + + let mut element = El::new("Index").with_attr("Self", "ix"); + element.children = build(&topics, &self.cross_references, &[], &mut fresh).into_iter().map(Node::El).collect(); + element + } +} + +/// Text saved inside an IDML `CrossReferenceSource` before the application regenerates it from +/// the cross-reference format. Page-number variables are separate segments so callers can retain +/// the last displayed page while mapping to their own text model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SavedCrossReference { + pub self_id: Option, + pub applied_format: Option, + pub parts: Vec, + /// The first directly nested character range, which supplies the marker's formatting. + pub character_range: Option, +} + +/// The IDML cross-reference source wrapper around its saved character range. +pub struct CrossReferenceSource; + +impl CrossReferenceSource { + pub fn to_el(self_id: &str, applied_format: &str, name: &str, character_range: El) -> El { + El::new("CrossReferenceSource") + .with_attr("Self", self_id) + .with_attr("AppliedFormat", applied_format) + .with_attr("Name", name) + .with_attr("Hidden", "false") + .with_child(character_range) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum SavedCrossReferencePart { + Text(String), + PageNumber { result_text: Option }, +} + +impl SavedCrossReference { + /// Reads the bounded saved-text grammar. `page_variables` contains IDs whose variable type is + /// the cross-reference page number; when the document omits variable definitions, InDesign's + /// conventional `TV XRefPageNumber` suffix is recognized. + pub fn from_el(el: &El, page_variables: &[String]) -> SavedCrossReference { + let mut parsed = SavedCrossReference { + self_id: el.attr("Self").map(str::to_string), + applied_format: el.attr("AppliedFormat").map(str::to_string), + parts: Vec::new(), + character_range: el.find(Local("CharacterStyleRange")).and_then(|range| match TextNode::from_el(range) { + TextNode::Character(range) => Some(range), + _ => None, + }), + }; + saved_xref_parts(el, page_variables, &mut parsed.parts, 0); + parsed + } + + pub fn from_container(container: &Container, page_variables: &[String]) -> SavedCrossReference { + Self::from_el(&container.to_el(), page_variables) + } +} + +fn saved_xref_parts(el: &El, page_variables: &[String], parts: &mut Vec, depth: usize) { + if depth > 16 { + return; + } + for child in el.elements() { + match child.local() { + "Content" => parts.push(SavedCrossReferencePart::Text(child.deep_text())), + "TextVariableInstance" => { + let id = child.attr("AssociatedTextVariable").unwrap_or_default(); + let page_number = + page_variables.iter().any(|variable| variable == id) || (page_variables.is_empty() && id.ends_with("TV XRefPageNumber")); + if page_number { + parts.push(SavedCrossReferencePart::PageNumber { result_text: child.attr("ResultText").map(str::to_string) }); + } else { + parts.push(SavedCrossReferencePart::Text(child.attr("ResultText").unwrap_or_default().to_string())); + } + } + "Change" if child.attr("ChangeType") == Some("DeletedText") => {} + "CharacterStyleRange" | "Change" => saved_xref_parts(child, page_variables, parts, depth + 1), + _ => {} + } + } +} + +impl PageReference { + pub fn referenced_topic(&self) -> Option<&str> { + self.values.get("ReferencedTopic") + } + pub fn reference_type(&self) -> Option<&str> { + self.values.get("PageReferenceType") + } + pub fn limit(&self) -> Option { + self.values.num("PageReferenceLimit") + } + + /// Writes a page-reference record from the shared index model's type and target. + pub fn to_el(self_id: &str, reference_type: &str, topic: &str, id: usize, limit: Option) -> El { + let mut el = El::new("PageReference") + .with_attr("Self", self_id) + .with_attr("PageReferenceType", reference_type) + .with_attr("ReferencedTopic", topic) + .with_attr("Id", id); + if let Some(limit) = limit { + el.set_attr("PageReferenceLimit", limit); + } + el + } +} + /// The elements read as [`TextNode::Container`]. pub const CONTAINERS: [&str; 7] = ["HyperlinkTextSource", "Change", "XMLElement", "CrossReferenceSource", "Footnote", "Note", "EndnoteRange"]; @@ -54,6 +448,54 @@ pub struct Container { pub children: Vec, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ContainerKind { + HyperlinkTextSource, + Change, + XMLElement, + CrossReferenceSource, + Footnote, + Note, + EndnoteRange, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TrackedChangeKind { + Deleted, + Inserted, + Other, +} + +impl Container { + pub fn to_el(&self) -> El { + with_children(self.values.element(&self.name), &self.children) + } + + pub fn kind(&self) -> ContainerKind { + match self.name.as_str() { + "HyperlinkTextSource" => ContainerKind::HyperlinkTextSource, + "Change" => ContainerKind::Change, + "XMLElement" => ContainerKind::XMLElement, + "CrossReferenceSource" => ContainerKind::CrossReferenceSource, + "Footnote" => ContainerKind::Footnote, + "Note" => ContainerKind::Note, + _ => ContainerKind::EndnoteRange, + } + } + + pub fn self_id(&self) -> Option<&str> { + self.values.self_id() + } + + pub fn change_kind(&self) -> Option { + (self.kind() == ContainerKind::Change).then(|| match self.values.get("ChangeType") { + Some("DeletedText") => TrackedChangeKind::Deleted, + Some("InsertedText" | "MovedText") => TrackedChangeKind::Inserted, + _ => TrackedChangeKind::Other, + }) + } +} + /// A piece of a `Content` element. #[derive(Clone, Debug, PartialEq)] pub enum ContentPart { @@ -85,6 +527,11 @@ pub enum Ace { } impl Ace { + /// Parses an IDML ACE instruction's decimal code. + pub fn from_decimal(value: &str) -> Option { + value.trim().parse::().ok().map(Ace::from_code) + } + pub fn from_code(code: u32) -> Ace { match code { 4 => Ace::FootnoteNumber, @@ -115,6 +562,63 @@ pub struct Table { pub children: Vec, } +/// The row and column grid of an IDML table, read without allocating cell models. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableLayout { + pub rows: Vec, + pub columns: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableRow { + pub values: Values, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableColumn { + pub values: Values, +} + +impl TableLayout { + pub fn from_el(el: &El) -> TableLayout { + Self::from_table(&Table::from_el(el)) + } + + pub fn from_table(table: &Table) -> TableLayout { + let mut layout = TableLayout::default(); + for child in &table.children { + if let TableChild::Other(element) = child { + match element.local() { + "Row" => layout.rows.push(TableRow { values: Values::of(element) }), + "Column" => layout.columns.push(TableColumn { values: Values::of(element) }), + _ => {} + } + } + } + layout + } +} + +impl TableRow { + pub fn auto_grow(&self) -> Option { + self.values.boolean("AutoGrow") + } + + pub fn minimum_height(&self) -> Option { + self.values.num("MinimumHeight") + } + + pub fn single_row_height(&self) -> Option { + self.values.num("SingleRowHeight") + } +} + +impl TableColumn { + pub fn single_column_width(&self) -> Option { + self.values.num("SingleColumnWidth") + } +} + /// A child of a table, in document order. #[derive(Clone, Debug, PartialEq)] pub enum TableChild { @@ -130,13 +634,34 @@ pub struct Cell { pub children: Vec, } +/// Format-level options on an IDML table cell, before DesignCraft maps them into its model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CellOptions { + pub fill_color: Option, + pub fill_tint: Option, + pub insets: [Option; 4], + pub vertical_justification: Option, + pub first_baseline_offset: Option, + pub minimum_first_baseline_offset: Option, + pub rotation_angle: Option, + pub edge_stroke_priorities: [i32; 4], + pub edge_strokes: [super::StrokeValues; 4], +} + /// The children of `el` other than ``, as text nodes. fn nodes(el: &El) -> Vec { - el.elements().filter(|e| !e.is(Local("Properties"))).map(TextNode::from_el).collect() + el.children + .iter() + .filter_map(|node| match node { + Node::El(e) if !e.is(Local("Properties")) => Some(TextNode::from_el(e)), + Node::Pi { target, data } => Some(TextNode::ProcessingInstruction { target: target.clone(), data: data.clone() }), + _ => None, + }) + .collect() } fn with_children(mut el: El, children: &[TextNode]) -> El { - el.children.extend(children.iter().map(|c| Node::El(c.to_el()))); + el.children.extend(children.iter().map(TextNode::to_node)); el } @@ -148,6 +673,11 @@ impl TextNode { "Content" => TextNode::Content(content_parts(el)), "Br" => TextNode::Break, "Table" => TextNode::Table(Table::from_el(el)), + "HyperlinkTextDestination" | "ParagraphDestination" => { + TextNode::Anchor(StoryAnchor { name: el.local().to_string(), values: Values::of(el) }) + } + "PageReference" => TextNode::PageReference(PageReference { values: Values::of(el) }), + "TextVariableInstance" => TextNode::TextVariable(Values::of(el)), n if CONTAINERS.contains(&n) => TextNode::Container(Container { name: n.to_string(), values: Values::of(el), children: nodes(el) }), _ => PageItem::from_el(el).map_or_else(|| TextNode::Other(tidy(el)), TextNode::Item), } @@ -170,13 +700,30 @@ impl TextNode { c } TextNode::Break => El::new("Br"), + TextNode::ProcessingInstruction { target, data } => { + let mut content = El::new("Content"); + content.children.push(Node::Pi { target: target.clone(), data: data.clone() }); + content + } TextNode::Container(c) => with_children(c.values.element(&c.name), &c.children), TextNode::Table(t) => t.to_el(), + TextNode::Anchor(a) => a.values.element(&a.name), + TextNode::PageReference(r) => r.values.element("PageReference"), + TextNode::TextVariable(v) => v.element("TextVariableInstance"), TextNode::Item(i) => i.to_el(), TextNode::Other(e) => e.clone(), } } + /// Serializes this node in its parent position, preserving processing instructions as XML + /// instructions rather than wrapping them in an element. + pub fn to_node(&self) -> Node { + match self { + TextNode::ProcessingInstruction { target, data } => Node::Pi { target: target.clone(), data: data.clone() }, + _ => Node::El(self.to_el()), + } + } + /// The nodes this one holds; none for content, breaks, page items and others. pub fn children(&self) -> &[TextNode] { match self { @@ -226,6 +773,26 @@ impl Story { }) } + /// Whether `StoryDirection` selects right-to-left order. + pub fn right_to_left(&self) -> bool { + self.preference().and_then(|values| values.get("StoryDirection").map(str::to_string)).as_deref() == Some("RightToLeftDirection") + } + + /// Whether `StoryOrientation` selects vertical composition. + pub fn vertical(&self) -> bool { + self.preference().and_then(|values| values.get("StoryOrientation").map(str::to_string)).as_deref() == Some("Vertical") + } + + /// Whether optical margin alignment is enabled; false when absent. + pub fn optical_margin_enabled(&self) -> bool { + self.preference().and_then(|values| values.boolean("OpticalMarginAlignment")) == Some(true) + } + + /// The `OpticalMarginSize`, if finite. + pub fn optical_margin_size(&self) -> Option { + self.preference().and_then(|values| values.num("OpticalMarginSize")) + } + /// The story's paragraph ranges in reading order, those inside containers included, but not /// those of its tables, footnotes or notes (which are text of their own). pub fn paragraphs(&self) -> Vec<&Range> { @@ -275,6 +842,11 @@ fn text(nodes: &[TextNode], ace: &dyn Fn(Ace) -> Option) -> String { } } TextNode::Break => out.push('\n'), + TextNode::ProcessingInstruction { target, data } if target == "ACE" => { + if let Ok(code) = data.trim().parse::() { + out.extend(ace(Ace::from_code(code))); + } + } TextNode::Paragraph(r) | TextNode::Character(r) => stack.extend(r.children.iter().rev()), TextNode::Container(c) if inline_container(&c.name) => stack.extend(c.children.iter().rev()), _ => {} @@ -284,6 +856,11 @@ fn text(nodes: &[TextNode], ace: &dyn Fn(Ace) -> Option) -> String { } impl Range { + /// `ParagraphBreakType`, except `Anywhere` which means no forced break. + pub fn paragraph_break_type(&self) -> Option<&str> { + self.values.get("ParagraphBreakType").filter(|kind| *kind != "Anywhere") + } + /// `AppliedParagraphStyle` of a paragraph range. pub fn paragraph_style(&self) -> Option<&str> { self.values.get("AppliedParagraphStyle") @@ -378,6 +955,14 @@ impl Table { } impl Cell { + pub fn from_el(el: &El) -> Cell { + Cell { values: Values::of(el), children: nodes(el) } + } + + pub fn to_el(&self) -> El { + with_children(self.values.element("Cell"), &self.children) + } + /// `Name`: `column:row` of the cell's top left (`2:0`). pub fn position(&self) -> Option<(u32, u32)> { let (c, r) = self.values.name()?.split_once(':')?; @@ -390,6 +975,27 @@ impl Cell { (n("ColumnSpan"), n("RowSpan")) } + pub fn options(&self) -> CellOptions { + let inset = |current: &str, legacy: &str| self.values.num(current).or_else(|| self.values.num(legacy)); + let priority = |side: &str| self.values.prop(&format!("{side}StrokePriority")).and_then(|v| v.trim().parse().ok()).unwrap_or(0); + CellOptions { + fill_color: self.values.value("FillColor"), + fill_tint: self.values.num("FillTint"), + insets: [ + inset("TextTopInset", "TopInset"), + inset("TextLeftInset", "LeftInset"), + inset("TextBottomInset", "BottomInset"), + inset("TextRightInset", "RightInset"), + ], + vertical_justification: self.values.value("VerticalJustification"), + first_baseline_offset: self.values.value("FirstBaselineOffset"), + minimum_first_baseline_offset: self.values.num("MinimumFirstBaselineOffset"), + rotation_angle: self.values.num("RotationAngle"), + edge_stroke_priorities: [priority("TopEdge"), priority("LeftEdge"), priority("BottomEdge"), priority("RightEdge")], + edge_strokes: ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"].map(|side| self.values.stroke_values(side)), + } + } + pub fn paragraphs(&self) -> Vec<&Range> { paragraphs(&self.children) } diff --git a/crates/idml/src/part.rs b/crates/idml/src/part.rs index f55ce4197..d0d3661c3 100644 --- a/crates/idml/src/part.rs +++ b/crates/idml/src/part.rs @@ -4,8 +4,14 @@ use craft_xml::{DECL_STANDALONE, El, Local, Node, Options}; use crate::{DOM_VERSION, PACKAGING_NS}; -pub(crate) const XML_LIMITS: craft_xml::Limits = - craft_xml::Limits { max_input: 512 << 20, max_depth: 256, max_nodes: 8_000_000, max_attrs: 1024, max_attrs_total: 32_000_000 }; +pub(crate) const XML_LIMITS: craft_xml::Limits = craft_xml::Limits { + max_input: 512 << 20, + max_depth: 256, + max_nodes: 8_000_000, + max_elements: 8_000_000, + max_attrs: 1024, + max_attrs_total: 32_000_000, +}; /// The XML limits a part is read with: 512 MiB of input, 256 levels of nesting (InDesign's /// packages stay under a few dozen), 8,000,000 nodes and 32,000,000 attributes in one part. @@ -16,6 +22,25 @@ pub const fn xml_limits() -> craft_xml::Limits { /// `META-INF/container.xml` of a package. pub const CONTAINER_XML: &str = "\n\n\t\n\t\t\n\t\n\n"; +/// The standard root element for `designmap.xml`, including its required namespace and core +/// document identity fields. The caller supplies DesignCraft-independent values; children are +/// appended after construction. +pub fn designmap_root(self_id: &str, story_list: &str, name: &str, zero_point: &str, active_layer: &str) -> El { + El::new("Document") + .with_attr("xmlns:idPkg", PACKAGING_NS) + .with_attr("DOMVersion", DOM_VERSION) + .with_attr("Self", self_id) + .with_attr("StoryList", story_list) + .with_attr("Name", name) + .with_attr("ZeroPoint", zero_point) + .with_attr("ActiveLayer", active_layer) +} + +/// An `idPkg` reference in `designmap.xml` to a part stored at `src`. +pub fn designmap_include(kind: &str, src: &str) -> El { + El::new(format!("idPkg:{kind}")).with_attr("src", src) +} + /// Parses a part into its root element with [`xml_limits`]. /// /// Names are kept as written (`idPkg:Story`), text is kept exactly (it is story content), CDATA @@ -106,10 +131,15 @@ pub fn part_xml(root: &El) -> Vec { /// `designmap.xml` as bytes: [`part_xml`] with the `` instruction that tells InDesign /// what the file is. pub fn designmap_xml(root: &El) -> Vec { + let pi = format!("", DOM_VERSION); + designmap_xml_with_pi(root, &pi) +} + +/// A designmap part with the caller's `` metadata instruction. +pub fn designmap_xml_with_pi(root: &El, pi: &str) -> Vec { let mut s = String::from(DECL_STANDALONE); - s.push_str("\n"); + s.push_str(pi); + s.push('\n'); root.write_xml_pretty(&mut s, "\t"); s.into_bytes() } diff --git a/crates/idml/src/value.rs b/crates/idml/src/value.rs index cb54644db..ab09cbaec 100644 --- a/crates/idml/src/value.rs +++ b/crates/idml/src/value.rs @@ -30,7 +30,15 @@ pub fn nums(s: &str) -> Vec { /// An `ItemTransform`: the six coefficients `a b c d tx ty`, or `None` when the value is not /// six finite numbers. pub fn matrix(s: &str) -> Option<[f64; 6]> { - <[f64; 6]>::try_from(nums(s)).ok() + let mut tokens = s.split_whitespace(); + let mut matrix = [0.0_f64; 6]; + for value in &mut matrix { + *value = tokens.next()?.parse().ok()?; + if !value.is_finite() { + return None; + } + } + tokens.next().is_none().then_some(matrix) } /// A transform as an `ItemTransform` value. diff --git a/crates/idml/tests/model.rs b/crates/idml/tests/model.rs index 98c94df1a..075a77c82 100644 --- a/crates/idml/tests/model.rs +++ b/crates/idml/tests/model.rs @@ -266,3 +266,17 @@ fn deeply_nested_groups_are_read_and_walked() { let again = Spread::from_el(&parse_part(&part_xml(&s.to_el())).unwrap()); assert_eq!(again, s); } + +#[test] +fn text_variable_decoration_uses_preference_and_falls_back_to_legacy_root_values() { + let preferred = parse_part( + br#""#, + ) + .unwrap(); + let variable = craft_idml::model::TextVariableValues::from_el(&preferred); + assert_eq!((variable.before.as_str(), variable.after.as_str()), ("of ", " pages")); + + let legacy = parse_part(br#""#).unwrap(); + let variable = craft_idml::model::TextVariableValues::from_el(&legacy); + assert_eq!((variable.before.as_str(), variable.after.as_str()), ("of ", " pages")); +} diff --git a/crates/idml/tests/story.rs b/crates/idml/tests/story.rs index c21b1f398..fe2642edc 100644 --- a/crates/idml/tests/story.rs +++ b/crates/idml/tests/story.rs @@ -69,6 +69,10 @@ fn a_story_reads_as_ranges_and_content() { // The body paragraph's character range holds every kind of node. let body = paras[1].characters(); assert_eq!(body.len(), 1); + let TextNode::Anchor(destination) = &body[0].children[6] else { panic!() }; + assert_eq!(destination.name, "HyperlinkTextDestination"); + assert_eq!(destination.values.self_id(), Some("ud1")); + assert_eq!(destination.values.value("Name").as_deref(), Some("here")); let kinds: Vec = body[0] .children .iter() @@ -77,13 +81,14 @@ fn a_story_reads_as_ranges_and_content() { TextNode::Content(_) => "Content".into(), TextNode::Table(_) => "Table".into(), TextNode::Item(i) => format!("item {}", i.kind.name()), + TextNode::Anchor(anchor) => format!("anchor {}", anchor.name), TextNode::Other(e) => format!("other {}", e.name), n => format!("{n:?}"), }) .collect(); assert_eq!( kinds, - ["HyperlinkTextSource", "Change", "Content", "Footnote", "Table", "item Rectangle", "other HyperlinkTextDestination", "Content"] + ["HyperlinkTextSource", "Change", "Content", "Footnote", "Table", "item Rectangle", "anchor HyperlinkTextDestination", "Content"] ); } diff --git a/crates/idml/tests/value.rs b/crates/idml/tests/value.rs index 75ef55a08..236c13286 100644 --- a/crates/idml/tests/value.rs +++ b/crates/idml/tests/value.rs @@ -25,6 +25,8 @@ fn transforms_and_points() { assert_eq!(matrix("1 0 0 1 36"), None); assert_eq!(matrix("1 0 0 1 36 72 9"), None); assert_eq!(matrix("1 0 0 1 NaN 0"), None); + assert_eq!(matrix("0 1 x -1 0 0 5"), None, "invalid coefficients cannot shift later values"); + assert_eq!(matrix("1e1000 0 0 1 0 0"), None, "non-finite coefficients are rejected"); assert_eq!(matrix_str(&[1.0, 0.0, 0.0, 1.0, 36.0, -72.5]), "1 0 0 1 36 -72.5"); assert_eq!(point("3 4"), Some((3.0, 4.0))); assert_eq!(point("3 4 5"), Some((3.0, 4.0))); diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index b893c347a..df71d9860 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -13,10 +13,11 @@ workspace = true [features] corpus = [] default = [] -avif = ["image/avif"] +avif = ["image/avif", "dep:ravif", "dep:rav1e", "dep:avif-serialize"] heif = ["dep:craft-heif"] [dependencies] +crc32fast = "1.5" thiserror = { workspace = true } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "gif", "bmp", "tga", "ico", "qoi", "hdr"] } png = "0.18" @@ -33,6 +34,10 @@ craft-jpeg = { workspace = true } craft-metadata = { workspace = true } zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] } craft-heif = { workspace = true, optional = true } +ravif = { version = "0.13", default-features = false, optional = true } +rav1e = { version = "0.8", default-features = false, optional = true } +avif-serialize = { version = "0.8", optional = true } +hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } @@ -41,6 +46,8 @@ exr = { version = "1.73", default-features = false, features = ["rayon"] } [dev-dependencies] proptest = { workspace = true } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff"] } +sha2 = { version = "0.10", default-features = false, features = ["std"] } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +craft-video = { workspace = true, features = ["av1-decode"] } jxl-oxide = { version = "=0.12.6", default-features = false, features = ["rayon"] } diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 0fdcd6ae4..6e9e11617 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -250,8 +250,9 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them the image: when the image fits but its extra samples don't, it opens without them and carries `DecodeWarning::ExtraSamplesDropped`. * Every directory is reachable: `tiff_info` lists the main IFD chain and its SubIFDs (tag 330) - with each page's size, kind (page, reduced-resolution copy, mask) and storage, walked with a - seen-set, a depth limit and a 10 000-directory cap; `decode_tiff_page` opens any of them. + with each page's size, kind (page, reduced-resolution copy, mask), storage, InkSet and + ExtraSamples, walked with a seen-set, a depth limit and a 10 000-directory cap; + `decode_tiff_page` opens any of them. `decode` opens the first full-resolution page, like Photoshop (thumbnails are skipped). * Banded decoding: the image is allocated once at its final size and each strip or row of tiles is decoded straight into it, in parallel on native targets, with at most one @@ -301,9 +302,13 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them `DecodeOptions { limits: Limits { max_width, max_height, max_pixels, max_alloc }, .. }` guards decoding. Header dimensions are checked before the pixel buffer is allocated, and the budget is also passed to the underlying decoders. A violation returns `CodecError::LimitExceeded`. The -defaults are 262144 px per side, 2^30 pixels and 8 GiB (2 GiB on 32-bit targets such as wasm). +defaults are 262144 px per side, 2^30 pixels and 8 GiB (1 GiB on 32-bit targets such as wasm). PNG also bounds the aggregate decoded text and XMP (UTF-8 keywords and values) by `max_alloc`, including chunks after IDAT. This budget is separate from pixels, not a total process-memory cap. +`Image::to_rgba_f32(&limits)` checks its output buffer against the same `Limits` and returns +`CodecError::LimitExceeded` before allocating when the RGBA f32 copy would exceed them. +PNG `cICP` and `cLLI` values are retained as image color metadata. `encode_png_pq` writes linear-light +Rec. 2020 RGB as 16-bit BT.2100 PQ, with measured content-light levels and the required chunks. ## Tests @@ -321,3 +326,16 @@ including chunks after IDAT. This budget is separate from pixels, not a total pr If `corpus/pngsuite/*.png` exists at the repo root, every file in it is compared against the `image` crate's decoder. Without it, that test is skipped. + +With the `corpus` feature, the deep EXR test reads `11.deep.exr`, `42.deep.exr`, `64.deep.exr`, +`multivariate.deep.exr` and `objectid.deep.exr` from `corpus/exr/` at the repo root. These are the +deep test images in `src/test/bin/test_images` of the +[OpenEXR repository at commit `69b2604fc76e370615438bdc8d2cd95b9349c12e`](https://github.com/AcademySoftwareFoundation/openexr/tree/69b2604fc76e370615438bdc8d2cd95b9349c12e/src/test/bin/test_images). +The test checks each file against the SHA-256 pinned in `REAL_FILE_SHA256` in +`tests/it/deep_exr.rs` before decoding it, and fails when a file is missing, is not a regular +file, is larger than 4 MiB or does not match. It reads no other file in the folder. To fill the +folder, copy the five files from that commit into `corpus/exr/`, or run +`cargo xtask corpus --exr` in a checkout of [PhotoCraft](https://github.com/storytold/PhotoCraft) +at commit `74330157cb601573ae4523a95bb9132822fc3918` and copy its `corpus/exr/` here, as CI does. +The images are not committed here; OpenEXR distributes them under its +[license](https://github.com/AcademySoftwareFoundation/openexr/blob/69b2604fc76e370615438bdc8d2cd95b9349c12e/LICENSE.md). diff --git a/crates/image-codecs/src/allocation.rs b/crates/image-codecs/src/allocation.rs index a82f43f8e..fe98122e7 100644 --- a/crates/image-codecs/src/allocation.rs +++ b/crates/image-codecs/src/allocation.rs @@ -124,20 +124,28 @@ fn gif_bounds(bytes: &[u8]) -> Result<(u32, u32), CodecError> { let frame_height = u32::from(u16_le(bytes, at + 7).ok_or_else(bad)?); let descriptor = bytes.get(at..at.checked_add(10).ok_or_else(bad)?).ok_or_else(bad)?; let flags = descriptor[9]; + // The frame rectangle determines its decoded allocation even when the later + // compressed payload is truncated. Report known dimensions so callers can + // refuse an oversized frame before asking a decoder to inspect its pixels. + width = width.max(left.saturating_add(frame_width)); + height = height.max(top.saturating_add(frame_height)); let mut body = at.checked_add(10).ok_or_else(bad)?; if flags & 0x80 != 0 { let table = 3usize.checked_mul(1usize.checked_shl(u32::from((flags & 7) + 1)).ok_or_else(bad)?).ok_or_else(bad)?; body = body.checked_add(table).ok_or_else(bad)?; } body = body.checked_add(1).ok_or_else(bad)?; // LZW minimum code size. - if bytes.get(..body).is_none() || frame_width == 0 || frame_height == 0 { + if frame_width == 0 || frame_height == 0 { return Err(bad()); } - width = width.max(left.saturating_add(frame_width)); - height = height.max(top.saturating_add(frame_height)); + if bytes.get(..body).is_none() { + return Ok((width, height)); + } at = body; + frames = frames.saturating_add(1); loop { - let length = usize::from(*bytes.get(at).ok_or_else(bad)?); + let Some(&length) = bytes.get(at) else { return Ok((width, height)) }; + let length = usize::from(length); at = at.checked_add(1).ok_or_else(bad)?; if length == 0 { break; @@ -147,7 +155,6 @@ fn gif_bounds(bytes: &[u8]) -> Result<(u32, u32), CodecError> { return Err(bad()); } } - frames = frames.saturating_add(1); } _ => return Err(bad()), } diff --git a/crates/image-codecs/src/apng.rs b/crates/image-codecs/src/apng.rs new file mode 100644 index 000000000..30d22efeb --- /dev/null +++ b/crates/image-codecs/src/apng.rs @@ -0,0 +1,201 @@ +//! APNG container assembly for already-compressed RGBA8 frame streams. +//! +//! Extracted from AniCraft's animated export (Tanish Manku, commit a20a488f). +//! Frame selection, timing quantization and pixel compression remain caller policy. +//! Payloads must be complete PNG IDAT zlib streams for non-interlaced RGBA8 images +//! of the declared frame size. They are not decompressed or validated here. + +use crate::CodecError; + +/// One compressed frame. The first must cover the entire canvas. +#[derive(Clone, Copy, Debug)] +pub struct Frame<'a> { + pub width: u32, + pub height: u32, + pub x: u32, + pub y: u32, + /// Exact delay numerator; zero is retained without rounding. + pub delay_num: u16, + /// Exact denominator; zero has the APNG-defined meaning of 100. + pub delay_den: u16, + /// Blend over the previous canvas instead of replacing the rectangle. + pub over: bool, + /// Concatenated IDAT payload, not complete PNG chunks. + pub data: &'a [u8], +} + +fn invalid(message: &str) -> CodecError { + CodecError::InvalidImage(message.into()) +} + +// PNG 3 §7.1 restricts unsigned integers to 31 bits. The last fdAT sequence +// is 2 * count - 2; validate arithmetically without allocating frame headers. +fn animation_count(len: usize, plays: u32) -> Result { + let count = u32::try_from(len).map_err(|_| invalid("too many APNG frames"))?; + if plays > 0x7fff_ffff || count == 0 || count > (0x7fff_ffff / 2) + 1 { + return Err(invalid("APNG play count or sequence exceeds PNG integer range")); + } + Ok(count) +} + +/// Assemble an RGBA8 APNG with dispose-none frames and the first frame as default image. +/// `plays == 0` means infinite looping. `max_bytes` bounds the returned encoded file, +/// not caller-owned inputs or decoded pixels. Checked sizing precedes allocation; +/// malformed geometry, chunk lengths and sequence exhaustion fail before output. +pub fn encode(width: u32, height: u32, plays: u32, frames: &[Frame<'_>], max_bytes: usize) -> Result, CodecError> { + if width == 0 || height == 0 || width > 0x7fff_ffff || height > 0x7fff_ffff || frames.is_empty() { + return Err(invalid("APNG needs a nonempty canvas and frames")); + } + let count = animation_count(frames.len(), plays)?; + let mut size = 8usize + 25 + 20 + 12; // signature, IHDR, acTL, IEND + for (index, f) in frames.iter().enumerate() { + if f.width == 0 + || f.height == 0 + || f.x.checked_add(f.width).is_none_or(|end| end > width) + || f.y.checked_add(f.height).is_none_or(|end| end > height) + || (index == 0 && (f.x != 0 || f.y != 0 || f.width != width || f.height != height)) + { + return Err(invalid("APNG frame is outside canvas or first frame is not full size")); + } + let prefix = if index == 0 { 0 } else { 4 }; + let data_len = f.data.len().checked_add(prefix).ok_or_else(|| invalid("APNG chunk overflow"))?; + if f.data.is_empty() || data_len > 0x7fff_ffff { + return Err(invalid("APNG frame payload is empty or too large")); + } + size = size + .checked_add(38 + 12) + .and_then(|n| n.checked_add(data_len)) + .filter(|n| *n <= max_bytes) + .ok_or_else(|| CodecError::LimitExceeded("APNG output byte budget".into()))?; + } + let mut out = Vec::new(); + out.try_reserve_exact(size).map_err(|_| CodecError::LimitExceeded("APNG output allocation".into()))?; + out.extend_from_slice(b"\x89PNG\r\n\x1a\n"); + let mut ihdr = [0u8; 13]; + ihdr[..4].copy_from_slice(&width.to_be_bytes()); + ihdr[4..8].copy_from_slice(&height.to_be_bytes()); + ihdr[8..].copy_from_slice(&[8, 6, 0, 0, 0]); + chunk(&mut out, b"IHDR", &[], &ihdr); + let mut actl = [0u8; 8]; + actl[..4].copy_from_slice(&count.to_be_bytes()); + actl[4..].copy_from_slice(&plays.to_be_bytes()); + chunk(&mut out, b"acTL", &[], &actl); + let mut sequence = 0u32; + for (index, f) in frames.iter().enumerate() { + let mut control = [0u8; 26]; + for (target, value) in control[..20].as_chunks_mut::<4>().0.iter_mut().zip([sequence, f.width, f.height, f.x, f.y]) { + target.copy_from_slice(&value.to_be_bytes()); + } + control[20..22].copy_from_slice(&f.delay_num.to_be_bytes()); + control[22..24].copy_from_slice(&f.delay_den.to_be_bytes()); + control[25] = u8::from(f.over); + chunk(&mut out, b"fcTL", &[], &control); + if index == 0 { + chunk(&mut out, b"IDAT", &[], f.data); + } else { + chunk(&mut out, b"fdAT", &(sequence + 1).to_be_bytes(), f.data); + } + // The final frame does not need a next sequence number. + if index + 1 < frames.len() { + sequence += if index == 0 { 1 } else { 2 }; + } + } + chunk(&mut out, b"IEND", &[], &[]); + Ok(out) +} + +// Lengths and total capacity were validated before writing. Prefix avoids a frame-sized +// intermediate fdAT allocation. CRC covers the type, prefix and payload, as PNG requires. +#[allow(clippy::cast_possible_truncation)] +fn chunk(out: &mut Vec, kind: &[u8; 4], prefix: &[u8], data: &[u8]) { + out.extend_from_slice(&((prefix.len() + data.len()) as u32).to_be_bytes()); + let start = out.len(); + out.extend_from_slice(kind); + out.extend_from_slice(prefix); + out.extend_from_slice(data); + let crc = crc32fast::hash(&out[start..]); + out.extend_from_slice(&crc.to_be_bytes()); +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn frame(data: &[u8]) -> Frame<'_> { + Frame { width: 1, height: 1, x: 0, y: 0, delay_num: 200, delay_den: 2997, over: false, data } + } + + fn chunks(bytes: &[u8]) -> Vec<([u8; 4], Vec)> { + let mut pos = 8; + let mut result = Vec::new(); + while pos < bytes.len() { + let n = u32::from_be_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize; + let kind = bytes[pos + 4..pos + 8].try_into().unwrap(); + let end = pos + 8 + n; + assert_eq!(crc32fast::hash(&bytes[pos + 4..end]), u32::from_be_bytes(bytes[end..end + 4].try_into().unwrap())); + result.push((kind, bytes[pos + 8..end].to_vec())); + pos = end + 4; + } + result + } + + #[test] + fn png_integer_boundaries_without_giant_allocations() { + assert_eq!(animation_count(1, 0).unwrap(), 1); + assert_eq!(animation_count(0x4000_0000, 0x7fff_ffff).unwrap(), 0x4000_0000); + assert!(animation_count(0x4000_0001, 0).is_err()); + assert!(animation_count(0, 0).is_err()); + assert!(animation_count(1, 0x8000_0000).is_err()); + assert!(animation_count(1, u32::MAX).is_err()); + assert!(encode(1, 1, 0x8000_0000, &[frame(&[1])], 1000).is_err()); + } + + #[test] + fn preserves_rgba_delays_loop_blend_and_sequences() { + let mut png_bytes = Vec::new(); + { + let mut encoder = png::Encoder::new(&mut png_bytes, 1, 1); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(&[12, 34, 56, 128]).unwrap(); + writer.finish().unwrap(); + } + let data: Vec = chunks(&png_bytes).into_iter().filter(|(kind, _)| kind == b"IDAT").flat_map(|(_, data)| data).collect(); + let first = frame(&data); + let second = Frame { over: true, delay_num: 0, delay_den: 0, ..first }; + let encoded = encode(1, 1, 7, &[first, second], 4096).unwrap(); + let parts = chunks(&encoded); + assert_eq!( + parts.iter().map(|(kind, _)| *kind).collect::>(), + vec![*b"IHDR", *b"acTL", *b"fcTL", *b"IDAT", *b"fcTL", *b"fdAT", *b"IEND"] + ); + assert_eq!(parts[1].1, [0, 0, 0, 2, 0, 0, 0, 7]); + assert_eq!(&parts[2].1[20..], &[0, 200, 11, 181, 0, 0]); + assert_eq!(&parts[4].1[..4], &1u32.to_be_bytes()); + assert_eq!(&parts[4].1[20..], &[0, 0, 0, 0, 0, 1]); + assert_eq!(&parts[5].1[..4], &2u32.to_be_bytes()); + assert_eq!(&parts[5].1[4..], data.as_slice()); + let mut reader = png::Decoder::new(std::io::Cursor::new(&encoded)).read_info().unwrap(); + let mut pixels = [0u8; 4]; + reader.next_frame(&mut pixels).unwrap(); + assert_eq!(pixels, [12, 34, 56, 128]); + reader.next_frame(&mut pixels).unwrap(); + assert_eq!(pixels, [12, 34, 56, 128]); + assert!(encode(1, 1, 7, &[first, second], encoded.len() - 1).is_err()); + assert_eq!(encode(1, 1, 7, &[first, second], encoded.len()).unwrap(), encoded); + } + + #[test] + fn rejects_invalid_geometry_empty_payload_and_budget() { + let f = frame(&[1]); + assert!(encode(0, 1, 0, &[f], 1000).is_err()); + assert!(encode(1, 1, 0, &[], 1000).is_err()); + assert!(encode(2, 1, 0, &[f], 1000).is_err()); + assert!(encode(1, 1, 0, &[Frame { data: &[], ..f }], 1000).is_err()); + assert!(encode(1, 1, 0, &[f, Frame { x: u32::MAX, ..f }], 1000).is_err()); + assert!(encode(1, 1, 0, &[f, Frame { height: 0, ..f }], 1000).is_err()); + assert!(encode(1, 1, 0, &[f], 0).is_err()); + } +} diff --git a/crates/image-codecs/src/cicp.rs b/crates/image-codecs/src/cicp.rs index fc148837c..290c82bc3 100644 --- a/crates/image-codecs/src/cicp.rs +++ b/crates/image-codecs/src/cicp.rs @@ -27,6 +27,8 @@ impl Cicp { pub const TRANSFER_PQ: u16 = 16; /// ARIB STD-B67 / BT.2100 hybrid log-gamma. pub const TRANSFER_HLG: u16 = 18; + /// Linear light. + pub const TRANSFER_LINEAR: u16 = 8; /// PQ or HLG: samples that [`linearize`] decodes to linear light. pub fn is_hdr(self) -> bool { @@ -41,6 +43,15 @@ pub const HLG_PEAK_NITS: f32 = 1000.0; /// PQ's absolute peak. pub const PQ_PEAK_NITS: f32 = 10_000.0; +/// HDR content light levels in the units used by PNG `cLLI` (0.0001 cd/m² per unit). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ContentLightLevel { + /// Maximum content light level in 0.0001 cd/m² units. + pub max_content_light_level: u32, + /// Maximum frame-average light level in 0.0001 cd/m² units. + pub max_frame_average_light_level: u32, +} + /// BT.2100 HLG inverse OETF: non-linear signal `E'` (0..1) to normalised scene light `E` (0..1). pub fn hlg_inverse_oetf(e: f32) -> f32 { const A: f32 = 0.178_832_77; @@ -74,6 +85,18 @@ pub fn pq_to_linear(e: f32) -> f32 { y * PQ_PEAK_NITS / REFERENCE_WHITE_NITS } +/// BT.2100 PQ signal for linear light relative to [`REFERENCE_WHITE_NITS`]. +pub fn linear_to_pq(linear: f32) -> f32 { + const M1: f32 = 2610.0 / 16384.0; + const M2: f32 = 2523.0 / 4096.0 * 128.0; + const C1: f32 = 3424.0 / 4096.0; + const C2: f32 = 2413.0 / 4096.0 * 32.0; + const C3: f32 = 2392.0 / 4096.0 * 32.0; + let nits = if linear.is_finite() { linear.max(0.0) * REFERENCE_WHITE_NITS } else { 0.0 }; + let y = (nits / PQ_PEAK_NITS).clamp(0.0, 1.0).powf(M1); + ((C1 + C2 * y) / (1.0 + C3 * y)).powf(M2) +} + /// Relative luminance weights of the RGB primaries `code` (BT.2020's for anything else, the /// space BT.2100 defines HLG in). fn luma_weights(code: u16) -> [f32; 3] { @@ -104,7 +127,8 @@ pub fn linearize(img: Image, cicp: Cicp) -> Result { let mut out = Image::from_raw(w, h, layout, SampleType::F32, v.iter().flat_map(|x| x.to_ne_bytes()).collect())?; out.meta = img.meta; out.warnings = img.warnings; - out.cicp = Some(cicp); + // CICP describes the samples, not their source encoding. These samples are now linear. + out.cicp = Some(Cicp { transfer: Cicp::TRANSFER_LINEAR, matrix: 0, full_range: true, ..cicp }); Ok(out) } @@ -156,7 +180,10 @@ mod tests { assert!(close(pq_to_linear(1.0), 10_000.0 / 203.0, 0.05)); // 203 cd/m² is PQ signal ≈ 0.5807 (BT.2408). assert!(close(pq_to_linear(0.5807), 1.0, 0.005), "{}", pq_to_linear(0.5807)); + assert!(close(linear_to_pq(1.0), 0.5807, 0.0001)); + assert!(close(pq_to_linear(linear_to_pq(4.0)), 4.0, 0.001)); assert!(pq_to_linear(f32::NAN).is_finite()); + assert!(linear_to_pq(f32::NAN).is_finite()); } #[test] @@ -167,7 +194,15 @@ mod tests { .unwrap() .with_icc(Some(b"encoded-profile".to_vec())); let out = linearize(img, hlg).unwrap(); - assert_eq!((out.sample_type(), out.layout(), out.icc.as_deref(), out.cicp), (SampleType::F32, ChannelLayout::Rgba, None, Some(hlg))); + assert_eq!( + (out.sample_type(), out.layout(), out.icc.as_deref(), out.cicp), + ( + SampleType::F32, + ChannelLayout::Rgba, + None, + Some(Cicp { primaries: hlg.primaries, transfer: Cicp::TRANSFER_LINEAR, matrix: 0, full_range: true }) + ) + ); let v = out.to_normalized(); assert!(v[..3].iter().all(|&x| close(x, 1.0, 0.005)), "{v:?}"); assert!(close(v[3], 1.0, 1e-6) && v[4..7] == [0.0; 3] && close(v[7], 0.5, 1e-3), "{v:?}"); diff --git a/crates/image-codecs/src/codecs.rs b/crates/image-codecs/src/codecs.rs index 4c4c22388..0288ae22b 100644 --- a/crates/image-codecs/src/codecs.rs +++ b/crates/image-codecs/src/codecs.rs @@ -1,3 +1,4 @@ +pub(crate) mod avif; pub(crate) mod dds; pub(crate) mod dds_bc; pub(crate) mod deep_exr; @@ -10,6 +11,7 @@ pub(crate) mod gif_frames; pub(crate) mod gif_palette; pub(crate) mod heif; pub(crate) mod iff; +pub(crate) mod jp2; pub(crate) mod jpeg; pub(crate) mod jxl; pub(crate) mod pcx; diff --git a/crates/image-codecs/src/codecs/avif.rs b/crates/image-codecs/src/codecs/avif.rs new file mode 100644 index 000000000..042b5684b --- /dev/null +++ b/crates/image-codecs/src/codecs/avif.rs @@ -0,0 +1,313 @@ +//! AVIF encoding helpers (8/16-bit SDR via `ravif` and 10-bit 4:4:4 BT.2020 HDR via `rav1e` + `avif-serialize`). + +use crate::{CodecError, Format, Image}; + +/// Transfer function for [`encode_avif_hdr`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HdrTransfer { + Pq, + Hlg, +} + +/// Absolute luminance of SDR white in an HDR file (ITU-R BT.2408 reference white), cd/m^2. +pub const HDR_REFERENCE_WHITE_NITS: f32 = 203.0; + +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +fn pq_encode(nits: f32) -> f32 { + const M1: f32 = 2610.0 / 16384.0; + const M2: f32 = 2523.0 / 4096.0 * 128.0; + const C1: f32 = 3424.0 / 4096.0; + const C2: f32 = 2413.0 / 4096.0 * 32.0; + const C3: f32 = 2392.0 / 4096.0 * 32.0; + let y = (nits / 10_000.0).clamp(0.0, 1.0).powf(M1); + ((C1 + C2 * y) / (1.0 + C3 * y)).powf(M2) +} + +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +fn hlg_signal(rgb: [f32; 3]) -> [f32; 3] { + const K: [f32; 3] = [0.2627, 0.6780, 0.0593]; + const GAMMA: f32 = 1.2; + const A: f32 = 0.17883277; + const B: f32 = 0.28466892; + const C: f32 = 0.559_910_7; + let display = rgb.map(|v| (if v.is_finite() { v.max(0.0) } else { 0.0 }) * (HDR_REFERENCE_WHITE_NITS / crate::cicp::HLG_PEAK_NITS)); + let y = K[0] * display[0] + K[1] * display[1] + K[2] * display[2]; + let inverse_ootf = if y > 0.0 { y.powf((1.0 - GAMMA) / GAMMA) } else { 0.0 }; + display.map(|v| { + let scene = (v * inverse_ootf).clamp(0.0, 1.0); + if scene <= 1.0 / 12.0 { (3.0 * scene).sqrt() } else { A * (12.0 * scene - B).ln() + C } + }) +} + +/// Encode an 8-bit or 16-bit SDR `Image` as AVIF (`4:4:4`, 10-bit AV1) with `quality` (`1..=100`) +/// and `speed` (`1..=10`). +pub fn encode_avif_with_speed(img: &Image, quality: u8, speed: u8) -> Result, CodecError> { + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + { + let mut enc = ravif::Encoder::new() + .with_quality(f32::from(quality.clamp(1, 100))) + .with_alpha_quality(f32::from(quality.clamp(1, 100))) + .with_speed(speed.clamp(1, 10)) + .with_bit_depth(ravif::BitDepth::Ten); + if let Some(exif) = img.meta.exif.as_deref() { + enc = enc.with_exif(exif); + } + let alpha_mode = if img.layout().has_alpha() { ravif::AlphaColorMode::UnassociatedClean } else { ravif::AlphaColorMode::UnassociatedDirty }; + enc = enc.with_alpha_color_mode(alpha_mode); + let w = img.width() as usize; + let h = img.height() as usize; + if let Some(s16) = img.to_u16_samples() { + let ch = img.layout().channels(); + let mut planes = Vec::with_capacity(w * h); + let mut a_plane = if img.layout().has_alpha() { Some(Vec::with_capacity(w * h)) } else { None }; + for px in s16.chunks_exact(ch) { + let (r, g, b, a) = match ch { + 1 => (px[0], px[0], px[0], u16::MAX), + 2 => (px[0], px[0], px[0], px[1]), + 3 => (px[0], px[1], px[2], u16::MAX), + _ => (px[0], px[1], px[2], px[3]), + }; + let (rf, gf, bf) = (f32::from(r) / 65535.0, f32::from(g) / 65535.0, f32::from(b) / 65535.0); + let y = 0.299 * rf + 0.587 * gf + 0.114 * bf; + let cb = (bf - y) * (0.5 / (1.0 - 0.114)) + 0.5; + let cr = (rf - y) * (0.5 / (1.0 - 0.299)) + 0.5; + let q10 = |v: f32| (v * 1023.0).round().clamp(0.0, 1023.0) as u16; + planes.push([q10(y), q10(cb), q10(cr)]); + if let Some(ap) = &mut a_plane { + ap.push(q10(f32::from(a) / 65535.0)); + } + } + let alpha = a_plane.map(Vec::into_iter); + let res = enc + .encode_raw_planes_10_bit(w, h, planes, alpha, ravif::PixelRange::Full, ravif::MatrixCoefficients::BT601) + .map_err(|e| CodecError::encode(Format::Avif, e))?; + return Ok(res.avif_file); + } + let rgba = img.to_rgba8(); + let px: Vec = rgba.as_chunks::<4>().0.iter().map(|c| ravif::RGBA8::new(c[0], c[1], c[2], c[3])).collect(); + let res = enc.encode_rgba(ravif::Img::new(&px[..], w, h)).map_err(|e| CodecError::encode(Format::Avif, e))?; + Ok(res.avif_file) + } + #[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))] + { + let _ = (img, quality, speed); + Err(CodecError::unsupported(Format::Avif, "AVIF encoding is not available in this build")) + } +} + +/// Encode linear BT.2020 HDR `rgb` (`width * height * 3` floats, `1.0` = `203` cd/m^2) as +/// 10-bit 4:4:4 BT.2020 PQ or HLG AVIF. +pub fn encode_avif_hdr( + width: u32, + height: u32, + rgb: &[f32], + quality: u8, + speed: u8, + exif: Option<&[u8]>, + transfer: HdrTransfer, +) -> Result, CodecError> { + let (w, h) = (width as usize, height as usize); + let n = w.checked_mul(h).ok_or_else(|| CodecError::encode(Format::Avif, "image too large"))?; + if n == 0 || n.checked_mul(3).is_none_or(|need| rgb.len() < need) { + return Err(CodecError::encode(Format::Avif, "HDR AVIF: sample buffer too short")); + } + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + { + use rav1e::prelude::*; + const K: [f32; 3] = [0.2627, 0.6780, 0.0593]; + let mut max_nits = 0f32; + let mut sum_nits = 0f64; + let planes: Vec<[u16; 3]> = rgb + .as_chunks::<3>() + .0 + .iter() + .take(n) + .map(|c| { + let nits = [c[0], c[1], c[2]].map(|v| (if v.is_finite() { v.max(0.0) } else { 0.0 }) * HDR_REFERENCE_WHITE_NITS); + let y_nits = K[0] * nits[0] + K[1] * nits[1] + K[2] * nits[2]; + max_nits = max_nits.max(nits[0].max(nits[1]).max(nits[2])); + sum_nits += f64::from(y_nits); + let [r, g, b] = match transfer { + HdrTransfer::Pq => nits.map(pq_encode), + HdrTransfer::Hlg => hlg_signal([c[0], c[1], c[2]]), + }; + let y = K[0] * r + K[1] * g + K[2] * b; + let cb = (b - y) / (2.0 * (1.0 - K[2])) + 0.5; + let cr = (r - y) / (2.0 * (1.0 - K[0])) + 0.5; + [y, cb, cr].map(|v| (v * 1023.0).round().clamp(0.0, 1023.0) as u16) + }) + .collect(); + let q = f32::from(quality.clamp(1, 100)) / 100.0; + let x = if q >= 0.82 { + (1.0 - q) * 2.6 + } else if q > 0.25 { + 1.0 - 0.125 - q * 0.5 + } else { + 1.0 - q + }; + let quantizer = (x * 255.0).round() as usize; + let mut ec = EncoderConfig::with_speed_preset(speed.clamp(1, 10)); + ec.width = w; + ec.height = h; + ec.time_base = Rational::new(1, 1); + ec.bit_depth = 10; + ec.chroma_sampling = ChromaSampling::Cs444; + ec.pixel_range = PixelRange::Full; + ec.color_description = Some(ColorDescription { + color_primaries: ColorPrimaries::BT2020, + transfer_characteristics: match transfer { + HdrTransfer::Pq => TransferCharacteristics::SMPTE2084, + HdrTransfer::Hlg => TransferCharacteristics::HLG, + }, + matrix_coefficients: MatrixCoefficients::BT2020NCL, + }); + let cll = (max_nits.ceil().clamp(1.0, 10_000.0) as u16, (sum_nits / n as f64).ceil().clamp(1.0, 10_000.0) as u16); + ec.content_light = + (transfer == HdrTransfer::Pq).then_some(ContentLight { max_content_light_level: cll.0, max_frame_average_light_level: cll.1 }); + ec.still_picture = true; + ec.quantizer = quantizer; + ec.min_quantizer = quantizer.min(255) as u8; + ec.speed_settings.multiref = false; + ec.speed_settings.rdo_lookahead_frames = 1; + ec.speed_settings.scene_detection_mode = SceneDetectionSpeed::None; + let mut ctx: Context = Config::new().with_encoder_config(ec).new_context().map_err(|e| CodecError::encode(Format::Avif, e))?; + let mut frame = ctx.new_frame(); + { + let mut it = planes.iter(); + let mut fp = frame.planes.iter_mut(); + let (Some(py), Some(pu), Some(pv)) = (fp.next(), fp.next(), fp.next()) else { + return Err(CodecError::encode(Format::Avif, "AV1: frame has no planes")); + }; + let (mut sy, mut su, mut sv) = (py.mut_slice(Default::default()), pu.mut_slice(Default::default()), pv.mut_slice(Default::default())); + for ((ry, ru), rv) in sy.rows_iter_mut().zip(su.rows_iter_mut()).zip(sv.rows_iter_mut()).take(h) { + for ((y, u), v) in ry.iter_mut().zip(ru.iter_mut()).zip(rv.iter_mut()).take(w) { + let Some(p) = it.next() else { break }; + (*y, *u, *v) = (p[0], p[1], p[2]); + } + } + } + ctx.send_frame(frame).map_err(|e| CodecError::encode(Format::Avif, e))?; + ctx.flush(); + let mut av1 = Vec::new(); + loop { + match ctx.receive_packet() { + Ok(mut p) if p.frame_type == FrameType::KEY => av1.append(&mut p.data), + Ok(_) => {} + Err(EncoderStatus::Encoded | EncoderStatus::LimitReached) => break, + Err(e) => return Err(CodecError::encode(Format::Avif, e)), + } + } + use avif_serialize::constants as c; + let mut a = avif_serialize::Aviffy::new(); + a.set_matrix_coefficients(c::MatrixCoefficients::Bt2020Ncl) + .set_transfer_characteristics(match transfer { + HdrTransfer::Pq => c::TransferCharacteristics::Smpte2084, + HdrTransfer::Hlg => c::TransferCharacteristics::Hlg, + }) + .set_color_primaries(c::ColorPrimaries::Bt2020) + .set_full_color_range(true); + if transfer == HdrTransfer::Pq { + a.set_content_light_level(cll.0, cll.1); + } + if let Some(exif) = exif { + a.set_exif(exif.to_vec()); + } + Ok(a.to_vec(&av1, None, width, height, 10)) + } + #[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))] + { + let _ = (width, height, rgb, quality, speed, exif, transfer); + Err(CodecError::unsupported(Format::Avif, "AVIF encoding is not available in this build")) + } +} + +#[cfg(test)] +mod tests { + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + #[test] + fn sdr_avif_uses_requested_alpha_quality() { + use crate::{ChannelLayout, Image}; + + let pixels: Vec = (0..1024).map(|i| ravif::RGBA8::new(100, 120, 140, ((i * 37) % 256) as u8)).collect(); + let samples: Vec = pixels.iter().flat_map(|p| [p.r, p.g, p.b, p.a]).collect(); + let image = Image::from_u8(32, 32, ChannelLayout::Rgba, samples).unwrap(); + let actual = super::encode_avif_with_speed(&image, 20, 10).unwrap(); + let expected = ravif::Encoder::new() + .with_quality(20.0) + .with_alpha_quality(20.0) + .with_speed(10) + .with_bit_depth(ravif::BitDepth::Ten) + .with_alpha_color_mode(ravif::AlphaColorMode::UnassociatedClean) + .encode_rgba(ravif::Img::new(&pixels, 32, 32)) + .unwrap() + .avif_file; + assert!(actual == expected, "encoded alpha must use the requested quality"); + } + + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + #[test] + fn sdr_avif_keeps_exif_metadata() { + use crate::{ChannelLayout, Image}; + + let exif = b"II*\0shared-avif-exif".to_vec(); + let mut image = Image::from_u8(2, 1, ChannelLayout::Rgb, vec![20, 40, 60, 80, 100, 120]).unwrap(); + image.meta.exif = Some(exif.clone()); + + let avif = super::encode_avif_with_speed(&image, 80, 8).unwrap(); + assert!(avif.windows(exif.len()).any(|window| window == exif.as_slice())); + } + + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + #[test] + fn hlg_mapping_matches_reference_white_and_peak() { + let white = super::hlg_signal([1.0; 3]); + assert!(white.iter().all(|&value| (value - 0.75).abs() < 0.005), "{white:?}"); + + let peak = super::hlg_signal([crate::cicp::HLG_PEAK_NITS / super::HDR_REFERENCE_WHITE_NITS; 3]); + assert!(peak.iter().all(|&value| (value - 1.0).abs() < 0.005), "{peak:?}"); + + let invalid = super::hlg_signal([f32::NAN, -1.0, f32::INFINITY]); + assert_eq!(invalid, [0.0; 3]); + } + + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + #[test] + fn hlg_encoded_output_signals_bt2020_hlg() { + let avif = super::encode_avif_hdr(1, 1, &[1.0; 3], 100, 10, None, super::HdrTransfer::Hlg).unwrap(); + let nclx = avif.windows(4).position(|window| window == b"nclx").expect("the AVIF has nclx color metadata"); + let color = avif.get(nclx + 4..nclx + 11).expect("complete nclx color metadata"); + assert_eq!(&color[..2], &[0, 9], "BT.2020 primaries"); + assert_eq!(&color[2..4], &[0, 18], "BT.2100 HLG transfer"); + assert_eq!(&color[4..6], &[0, 9], "BT.2020 non-constant luminance matrix"); + assert!(!avif.windows(4).any(|window| window == b"clli"), "HLG does not signal PQ content-light metadata"); + } + + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + #[test] + fn hlg_encoded_pixels_preserve_reference_white_and_peak() { + let mut rgb = Vec::new(); + for _ in 0..32 { + for x in 0..64 { + let level = if x < 32 { 1.0 } else { crate::cicp::HLG_PEAK_NITS / super::HDR_REFERENCE_WHITE_NITS }; + rgb.extend_from_slice(&[level; 3]); + } + } + let avif = super::encode_avif_hdr(64, 32, &rgb, 100, 10, None, super::HdrTransfer::Hlg).unwrap(); + let mut offset = 0; + let payload = loop { + let header = avif.get(offset..offset + 8).expect("complete AVIF box header"); + let size = u32::from_be_bytes(header[..4].try_into().unwrap()) as usize; + assert!(size >= 8 && offset + size <= avif.len(), "valid AVIF box size"); + if &header[4..] == b"mdat" { + break &avif[offset + 8..offset + size]; + } + offset += size; + }; + let mut decoder = craft_video::av1::decode::Decoder::new(); + let mut frames = decoder.decode(payload).unwrap(); + frames.extend(decoder.flush_result().unwrap()); + let luma = &frames.first().expect("encoded AV1 frame").planes[0]; + assert!((i32::from(luma[16 * 64 + 16]) - 767).abs() <= 5, "diffuse white"); + assert!((i32::from(luma[16 * 64 + 48]) - 1023).abs() <= 5, "peak white"); + } +} diff --git a/crates/image-codecs/src/codecs/jp2.rs b/crates/image-codecs/src/codecs/jp2.rs new file mode 100644 index 000000000..763ac9c9c --- /dev/null +++ b/crates/image-codecs/src/codecs/jp2.rs @@ -0,0 +1,242 @@ +//! JPEG 2000 (JP2 container and raw J2K codestream) decoding via `hayro-jpeg2000`. +//! +//! Decodes within `Limits`, rejecting unsupported JPX multi-layer/composition boxes and +//! checking declared SIZ/tile/palette/channel-definition bounds before pixel allocation. + +use hayro_jpeg2000::{ColorSpace, DecodeSettings, DecoderContext, Image as Jp2Image}; + +use crate::Format; +use crate::error::CodecError; +use crate::image::{ChannelLayout, Image, SampleType}; +use crate::options::Limits; + +const F: Format = Format::Jp2; +const JP2_SIGNATURE: &[u8] = b"\0\0\0\x0cjP \r\n\x87\n"; +const MAX_PROFILE: usize = 4 * 1024 * 1024; +const MAX_TILES: u64 = 65_535; +const TILE_COMPONENT_BYTES: u64 = 256; + +/// Boxes at one JP2 nesting level. Invalid lengths stop the walk at that level. +fn boxes(b: &[u8]) -> impl Iterator { + let mut at = 0usize; + std::iter::from_fn(move || { + let header = b.get(at..at.checked_add(8)?)?; + let size = u32::from_be_bytes(header.get(..4)?.try_into().ok()?); + let (length, head) = match size { + 0 => (b.len().checked_sub(at)?, 8usize), + 1 => (usize::try_from(u64::from_be_bytes(b.get(at.checked_add(8)?..at.checked_add(16)?)?.try_into().ok()?)).ok()?, 16usize), + n => (n as usize, 8usize), + }; + if length < head { + return None; + } + let end = at.checked_add(length)?; + let data = b.get(at.checked_add(head)?..end)?; + let ty = header.get(4..8)?; + at = end; + Some((ty, data)) + }) +} + +fn unsupported_jpx_content(bytes: &[u8]) -> bool { + fn association_has_content(data: &[u8], depth: usize) -> bool { + if depth >= 16 { + return true; + } + boxes(data).any(|(ty, child)| { + matches!(ty, b"jp2c" | b"jpch" | b"jplh" | b"comp" | b"ftbl") || (ty == b"asoc" && association_has_content(child, depth + 1)) + }) + } + let mut codestreams = 0u8; + for (ty, data) in boxes(bytes) { + match ty { + b"jp2c" => { + codestreams = codestreams.saturating_add(1); + if codestreams > 1 { + return true; + } + } + b"jpch" | b"jplh" | b"comp" | b"ftbl" => return true, + b"asoc" if association_has_content(data, 0) => return true, + _ => {} + } + } + false +} + +fn codestream_size(bytes: &[u8]) -> Option<(u64, u32, u32, u64)> { + let stream = if bytes.starts_with(b"\xff\x4f") { bytes } else { boxes(bytes).find_map(|(ty, data)| (ty == b"jp2c").then_some(data))? }; + if stream.get(..4)? != b"\xff\x4f\xff\x51" { + return None; + } + let length = u16::from_be_bytes(stream.get(4..6)?.try_into().ok()?) as usize; + let count = u16::from_be_bytes(stream.get(40..42)?.try_into().ok()?) as usize; + if count == 0 || length != 38usize.checked_add(count.checked_mul(3)?)? || stream.get(4..4usize.checked_add(length)?)?.len() != length { + return None; + } + let be32 = |range: std::ops::Range| stream.get(range).and_then(|v| v.try_into().ok()).map(u32::from_be_bytes); + let width = be32(8..12)?.checked_sub(be32(16..20)?)?; + let height = be32(12..16)?.checked_sub(be32(20..24)?)?; + let tiles = |grid: u32, offset: u32, tile: u32| match (grid.checked_sub(offset), tile) { + (Some(span), 1..) => Some(u64::from(span).div_ceil(u64::from(tile))), + _ => None, + }; + let across = tiles(be32(8..12)?, be32(32..36)?, be32(24..28)?)?; + let down = tiles(be32(12..16)?, be32(36..40)?, be32(28..32)?)?; + Some((count as u64, width, height, across.checked_mul(down)?)) +} + +fn single_header_boxes(bytes: &[u8]) -> bool { + let mut headers = boxes(bytes).filter(|(ty, _)| *ty == b"jp2h"); + let (Some((_, header)), None) = (headers.next(), headers.next()) else { + return false; + }; + [b"pclr", b"cmap", b"cdef"].iter().all(|kind| boxes(header).filter(|(ty, _)| ty == kind).count() <= 1) +} + +fn channel_definitions(bytes: &[u8]) -> Option { + if bytes.starts_with(b"\xff\x4f") { + return None; + } + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data))?; + let cdef = boxes(header).find_map(|(ty, data)| (ty == b"cdef").then_some(data))?; + let count = cdef.get(..2).and_then(|n| n.try_into().ok()).map_or(0, |n: [u8; 2]| usize::from(u16::from_be_bytes(n))); + let Some(entries) = cdef.get(2..).filter(|rest| count > 0 && rest.len() == count * 6) else { + return Some(0); + }; + let mut defs: Vec<[u16; 3]> = + entries.as_chunks::<6>().0.iter().map(|&[a, b, c, d, e, f]| [[a, b], [c, d], [e, f]].map(u16::from_be_bytes)).collect(); + defs.sort_unstable(); + let opacity = defs.last().is_some_and(|&[_, kind, association]| kind == 1 && association == 0); + let colors = defs.len() - usize::from(opacity); + let mut seen = vec![false; colors]; + let layout_ok = defs.iter().enumerate().all(|(i, &[channel, kind, association])| { + usize::from(channel) == i + && (i >= colors + || (kind == 0 + && usize::from(association).checked_sub(1).and_then(|slot| seen.get_mut(slot)).is_some_and(|s| !std::mem::replace(s, true)))) + }); + Some(if layout_ok { defs.len() as u64 } else { 0 }) +} + +fn palette_columns(bytes: &[u8], components: u64) -> Result, ()> { + if bytes.starts_with(b"\xff\x4f") { + return Ok(None); + } + let Some(header) = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)) else { + return Ok(None); + }; + let Some(palette) = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then_some(data)) else { + return Ok(None); + }; + let columns = palette.get(2).copied().ok_or(())?; + let depths = palette.get(3..3 + usize::from(columns)).ok_or(())?; + if columns == 0 || depths.iter().any(|&d| d & 0x80 != 0 || (d & 0x7f) + 1 > 31) { + return Err(()); + } + let Some(mapping) = boxes(header).find_map(|(ty, data)| (ty == b"cmap").then_some(data)) else { + return Ok(Some(u64::from(columns))); + }; + if mapping.len() != usize::from(columns) * 4 { + return Err(()); + } + for &[c0, c1, kind, column] in mapping.as_chunks::<4>().0 { + let valid = u64::from(u16::from_be_bytes([c0, c1])) < components + && match kind { + 0 => true, + 1 => column < columns, + _ => false, + }; + if !valid { + return Err(()); + } + } + Ok(Some(u64::from(columns))) +} + +pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { + let malformed = |msg: &str| CodecError::malformed(F, msg); + if bytes.starts_with(JP2_SIGNATURE) && unsupported_jpx_content(bytes) { + return Err(CodecError::unsupported(F, "unsupported color space or JPX content")); + } + if bytes.starts_with(JP2_SIGNATURE) && !single_header_boxes(bytes) { + return Err(malformed("invalid JP2 header boxes")); + } + let (codestream_channels, declared_w, declared_h, tile_count) = codestream_size(bytes).ok_or_else(|| malformed("invalid codestream SIZ"))?; + if tile_count == 0 || tile_count > MAX_TILES { + return Err(malformed("invalid tile count")); + } + let max_alloc = limits.max_alloc; + let declared_pixels = u64::from(declared_w).checked_mul(u64::from(declared_h)); + if declared_w == 0 + || declared_h == 0 + || declared_w > limits.max_width + || declared_h > limits.max_height + || declared_pixels.is_none_or(|n| n > limits.max_pixels) + || declared_pixels.and_then(|n| n.checked_mul(codestream_channels)).and_then(|n| n.checked_mul(4)).is_none_or(|n| n > max_alloc) + || tile_count.checked_mul(codestream_channels).and_then(|n| n.checked_mul(TILE_COMPONENT_BYTES)).is_none_or(|n| n > max_alloc) + { + return Err(CodecError::LimitExceeded(format!("dimensions {declared_w}x{declared_h} exceed decode limits"))); + } + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap_or_default(); + if boxes(header).any(|(ty, data)| ty == b"colr" && data.len() > MAX_PROFILE + 3) { + return Err(CodecError::unsupported(F, "ICC profile exceeds 4 MiB limit")); + } + let palette = palette_columns(bytes, codestream_channels).map_err(|()| malformed("invalid JP2 palette"))?; + let palette_rows = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then(|| data.get(..2)).flatten()); + if let (Some(columns), Some(&[r0, r1])) = (palette, palette_rows) + && u64::from(u16::from_be_bytes([r0, r1])) * (columns * 8 + 24) > max_alloc + { + return Err(CodecError::LimitExceeded("JP2 palette exceeds max_alloc".into())); + } + let image = Jp2Image::new(bytes, &DecodeSettings::default()).map_err(|e| malformed(&format!("{e:?}")))?; + let (w, h) = (image.width(), image.height()); + let color = image.color_space(); + let (channels, icc) = match color { + ColorSpace::Gray => (1u8, None), + ColorSpace::RGB => (3u8, None), + ColorSpace::CMYK => (4u8, None), + ColorSpace::Icc { num_channels: ch @ (1 | 3 | 4), profile } if profile.len() <= MAX_PROFILE => (*ch, Some(profile.to_vec())), + _ => return Err(CodecError::unsupported(F, "unsupported JPEG 2000 color space")), + }; + let has_alpha = image.has_alpha(); + let stride = u64::from(channels) + u64::from(has_alpha); + if palette.is_some_and(|columns| columns != stride) { + return Err(malformed("JP2 palette columns do not match output channels")); + } + if channel_definitions(bytes).is_some_and(|count| count != stride || count != palette.unwrap_or(codestream_channels)) { + return Err(malformed("JP2 channel definitions do not match output channels")); + } + let layout = match (channels, has_alpha) { + (1, false) => ChannelLayout::Gray, + (1, true) => ChannelLayout::GrayA, + (3, false) => ChannelLayout::Rgb, + (3, true) => ChannelLayout::Rgba, + (4, false) => ChannelLayout::Cmyk, + (4, true) => ChannelLayout::CmykA, + _ => return Err(CodecError::unsupported(F, "unsupported channel count")), + }; + limits.check(w, h, layout, SampleType::U8)?; + let plane_channels = codestream_channels.max(stride).max(palette.unwrap_or(0)); + let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(|| CodecError::LimitExceeded("pixel count overflow".into()))?; + let size = pixels.checked_mul(stride).ok_or_else(|| CodecError::LimitExceeded("sample count overflow".into()))?; + let plane_bytes = + pixels.checked_mul(plane_channels).and_then(|n| n.checked_mul(4)).ok_or_else(|| CodecError::LimitExceeded("plane overflow".into()))?; + let scratch_bytes = plane_bytes + .checked_mul(2) + .and_then(|n| n.checked_add(pixels.checked_mul(8)?)) + .ok_or_else(|| CodecError::LimitExceeded("scratch overflow".into()))?; + let working = size + .checked_add(plane_bytes) + .and_then(|n| n.checked_add(scratch_bytes)) + .ok_or_else(|| CodecError::LimitExceeded("memory overflow".into()))?; + if working > max_alloc { + return Err(CodecError::LimitExceeded(format!("working set {working} exceeds max_alloc {max_alloc}"))); + } + let len = usize::try_from(size).map_err(|_| CodecError::LimitExceeded("buffer does not fit in memory".into()))?; + let mut samples = vec![0u8; len]; + image.decode_into(&mut samples, &mut DecoderContext::default()).map_err(|e| malformed(&format!("{e:?}")))?; + let mut out = Image::from_raw(w, h, layout, SampleType::U8, samples)?; + out.icc = icc; + Ok(out) +} diff --git a/crates/image-codecs/src/codecs/jpeg.rs b/crates/image-codecs/src/codecs/jpeg.rs index 3bfdcddb2..bcd86ad5a 100644 --- a/crates/image-codecs/src/codecs/jpeg.rs +++ b/crates/image-codecs/src/codecs/jpeg.rs @@ -37,9 +37,53 @@ pub(crate) struct JpegMeta { pub dpi: Option<(f32, f32)>, /// The APP13 Photoshop image resource blocks (`8BIM` ...), segments joined, without the header. pub photoshop: Option>, + /// Whether an Adobe APP14 marker identifies the four-component samples as inverted CMYK. + pub adobe_marker: bool, pub adobe_transform: Option, /// (width, height, components) from the first SOFn. pub frame: Option<(u32, u32, u8)>, + /// [`crate::JpegInfo::held_coefficients`] of the first SOFn and the first scan. + pub held_coefficients: u64, +} + +/// The first frame of `b` as [`crate::JpegInfo`], from its markers alone (see [`crate::jpeg_info`]). +pub(crate) fn info(b: &[u8]) -> Option { + let m = scan_metadata(b); + let (width, height, components) = m.frame?; + let layout = match components { + 1 => ChannelLayout::Gray, + 3 => ChannelLayout::Rgb, + 4 => ChannelLayout::Cmyk, + _ => return None, + }; + let held_coefficients = m.held_coefficients; + Some(crate::JpegInfo { width, height, layout, whole_coefficients: uses_craft_jpeg(b), held_coefficients }) +} + +/// Bytes of the coefficients `zune-jpeg` holds beside its output for a frame it can't turn into +/// rows as it reads (see [`crate::JpegInfo::held_coefficients`]), from the frame's header +/// segment `seg` and the number of components in its first scan: per component, a 64-value +/// block of `i16`s for each of its H × V blocks in every MCU (A.2), the MCUs covering the frame +/// at the largest sampling factors. 0 for any other frame. +fn held_coefficients(marker: u8, seg: &[u8], scan_components: Option) -> u64 { + let &[8, h0, h1, w0, w1, n, ref comps @ ..] = seg else { return 0 }; + // Progressive scans refine every block in turn; a sequential first scan without every + // component leaves its rows unfinished until the scans that bring the others. + let held = match marker { + 0xC2 => true, + 0xC0 | 0xC1 => scan_components.is_some_and(|s| s < n), + _ => false, + }; + if !held { + return 0; + } + let (h, w) = (u64::from(u16::from_be_bytes([h0, h1])), u64::from(u16::from_be_bytes([w0, w1]))); + let factors: Vec<(u64, u64)> = + comps.as_chunks::<3>().0.iter().take(usize::from(n)).map(|&[_, f, _]| (u64::from(f >> 4), u64::from(f & 15))).collect(); + let hmax = factors.iter().map(|f| f.0).max().unwrap_or(1).max(1); + let vmax = factors.iter().map(|f| f.1).max().unwrap_or(1).max(1); + let mcus = w.div_ceil(8 * hmax) * h.div_ceil(8 * vmax); + factors.iter().map(|&(fh, fv)| mcus * fh * fv * 64 * 2).sum() } /// Walk the marker segments up to SOS and collect metadata. @@ -49,6 +93,9 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { // Photoshop splits a large resource block over consecutive APP13 segments. let mut photoshop: Vec = Vec::new(); let mut jfif_dpi = None; + // The first frame header and the number of components in the first scan. + let mut sof: Option<(u8, &[u8])> = None; + let mut scan_components = None; let mut i = 2; while i + 4 <= b.len() { if b[i] != 0xFF { @@ -64,6 +111,7 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { continue; } if marker == 0xDA || marker == 0xD9 { + scan_components = (marker == 0xDA).then(|| b.get(i + 4).copied()).flatten(); break; } let len = u16::from_be_bytes([b[i + 2], b[i + 3]]) as usize; @@ -100,14 +148,19 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { let h = u16::from_be_bytes([seg[1], seg[2]]) as u32; let w = u16::from_be_bytes([seg[3], seg[4]]) as u32; m.frame = Some((w, h, seg[5])); + sof = Some((marker, seg)); } - 0xEE if seg.len() >= 12 && seg.starts_with(b"Adobe") => { - m.adobe_transform = Some(seg[11]); + 0xEE if seg.starts_with(b"Adobe") => { + m.adobe_marker = true; + if seg.len() >= 12 { + m.adobe_transform = Some(seg[11]); + } } _ => {} } i += 2 + len; } + m.held_coefficients = sof.map_or(0, |(marker, seg)| held_coefficients(marker, seg, scan_components)); m.dpi = photoshop_resolution(&photoshop) .or_else(|| m.xmp.as_deref().and_then(xmp_resolution)) .or_else(|| m.exif.as_deref().and_then(exif_resolution)) @@ -245,9 +298,8 @@ fn without_extended_xmp(b: &[u8]) -> Option> { } /// Whether `craft-jpeg` (rather than `zune-jpeg`) decodes the file: arithmetic coding -/// (SOF9–SOF11) or a DCT frame whose precision isn't 8 bits (#4934, #5003). Lossless (SOF3) and -/// 12-bit progressive Huffman (SOF2) go there too: craft-jpeg reports them unsupported, where -/// zune-jpeg's failure would read as a damaged file. +/// (SOF9–SOF11), lossless (SOF3), or a DCT frame whose precision isn't 8 bits (#4934, #5003). +/// This includes 12-bit progressive Huffman (SOF2), which `craft-jpeg` supports. fn uses_craft_jpeg(bytes: &[u8]) -> bool { match craft_jpeg::frame(bytes) { Some(f) if (0xC9..=0xCB).contains(&f.marker) || f.marker == 0xC3 => true, @@ -265,9 +317,21 @@ fn craft_jpeg_error(e: craft_jpeg::Error) -> CodecError { } } +fn undo_craft_cmyk_inversion_u8(samples: &mut [u8], enabled: bool) { + if enabled { + samples.iter_mut().for_each(|v| *v = 255 - *v); + } +} + +fn undo_craft_cmyk_inversion_u16(samples: &mut [u16], enabled: bool) { + if enabled { + samples.iter_mut().for_each(|v| *v = 65535 - *v); + } +} + /// Decode a file [`uses_craft_jpeg`] routes away from `zune-jpeg`; `damaged` says entropy-coded /// data was cut short or corrupt. -fn decode_craft_jpeg(bytes: &[u8], limits: &Limits, adobe_transform: Option) -> Result<(Image, bool), CodecError> { +fn decode_craft_jpeg(bytes: &[u8], limits: &Limits, adobe_transform: Option, adobe_marker: bool) -> Result<(Image, bool), CodecError> { let mut lim = craft_jpeg::Limits::default(); lim.max_pixels = limits.max_pixels; lim.max_alloc = limits.max_alloc; @@ -278,9 +342,19 @@ fn decode_craft_jpeg(bytes: &[u8], limits: &Limits, adobe_transform: Option) 4 => ChannelLayout::Cmyk, n => return Err(err(format!("{n} components"))), }; + // craft-jpeg returns non-YCC CMYK samples with Adobe's inversion already undone, + // regardless of whether the file actually has an Adobe marker. Unmarked four-component + // streams are also found with direct ink samples, so restore those when using this backend. + let restore_unmarked_cmyk = !adobe_marker && matches!(layout, ChannelLayout::Cmyk); let img = match d.samples { - craft_jpeg::Samples::U8(px) => Image::from_raw(d.width, d.height, layout, SampleType::U8, px)?, - craft_jpeg::Samples::U16(px) => Image::from_u16(d.width, d.height, layout, &px)?, + craft_jpeg::Samples::U8(mut px) => { + undo_craft_cmyk_inversion_u8(&mut px, restore_unmarked_cmyk); + Image::from_raw(d.width, d.height, layout, SampleType::U8, px)? + } + craft_jpeg::Samples::U16(mut px) => { + undo_craft_cmyk_inversion_u16(&mut px, restore_unmarked_cmyk); + Image::from_u16(d.width, d.height, layout, &px)? + } }; Ok((img, d.damaged)) } @@ -312,7 +386,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { return Err(err("the truncated scan is too short for the frame it declares")); } - let (mut img, damaged) = decode_craft_jpeg(bytes, limits, meta.adobe_transform)?; + let (mut img, damaged) = decode_craft_jpeg(bytes, limits, meta.adobe_transform, meta.adobe_marker)?; img.icc = meta.icc; img.meta = Metadata { exif: meta.exif, xmp: meta.xmp, dpi: meta.dpi, photoshop_resources: meta.photoshop, ..Default::default() }; if end == DataEnd::Truncated || damaged { @@ -351,8 +425,9 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result } px.truncate(expected); match input { - // Adobe-style CMYK is stored inverted (255 = no ink). - ColorSpace::CMYK => px.iter_mut().for_each(|v| *v = 255 - *v), + // Adobe-style CMYK is stored inverted (255 = no ink). Four-component JPEGs without + // APP14 are also encountered with their CMYK samples stored as ink values directly. + ColorSpace::CMYK if meta.adobe_marker => px.iter_mut().for_each(|v| *v = 255 - *v), ColorSpace::YCCK => { for p in px.as_chunks_mut::<4>().0 { let (y, cb, cr) = (p[0] as f32, p[1] as f32 - 128.0, p[2] as f32 - 128.0); @@ -404,6 +479,9 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result| { + let mut b = vec![0xFF, 0xD8, 0xFF, marker, 0, 8 + 3 * factors.len() as u8, precision]; + b.extend_from_slice(&34_200u16.to_be_bytes()); + b.extend_from_slice(&48_000u16.to_be_bytes()); + b.push(factors.len() as u8); + for (i, &f) in factors.iter().enumerate() { + b.extend_from_slice(&[i as u8 + 1, f, 0]); + } + if let Some(n) = scan { + b.extend_from_slice(&[0xFF, 0xDA, 0, 6 + 2 * n, n]); + for c in 1..=n { + b.extend_from_slice(&[c, 0]); + } + b.extend_from_slice(&[0, 63, 0]); + } + b.extend_from_slice(&[0xFF, 0xD9]); + b + }; + let held = |b: &[u8]| info(b).map(|i| i.held_coefficients); + let all_444 = 6_000 * 4_275 * 3 * 128; + // 4:4:4: 6,000 × 4,275 MCUs of one block per component. + assert_eq!(held(&frame(0xC2, 8, &[0x11, 0x11, 0x11], Some(1))), Some(all_444)); + // 4:2:0: 3,000 × 2,138 MCUs of 4 + 1 + 1 blocks. + assert_eq!(held(&frame(0xC2, 8, &[0x22, 0x11, 0x11], None)), Some(3_000 * 2_138 * 6 * 128)); + // Sequential frames whose first scan lacks components hold them all too. + assert_eq!(held(&frame(0xC0, 8, &[0x11, 0x11, 0x11], Some(1))), Some(all_444)); + assert_eq!(held(&frame(0xC1, 8, &[0x11, 0x11, 0x11], Some(2))), Some(all_444)); + // A sequential first scan with every component is read a line of MCUs at a time, and a + // 12-bit progressive frame goes to craft-jpeg: they hold none. + assert_eq!(held(&frame(0xC0, 8, &[0x11, 0x11, 0x11], Some(3))), Some(0)); + assert_eq!(held(&frame(0xC0, 8, &[0x11, 0x11, 0x11], None)), Some(0)); + assert_eq!(held(&frame(0xC2, 12, &[0x11, 0x11, 0x11], None)), Some(0)); + } + /// An APP1 Extended XMP fragment (GUID, total size, offset, data). fn extended_xmp(offset: u32) -> Vec { let mut seg = EXTENDED_XMP_HEADER.to_vec(); @@ -800,6 +948,24 @@ mod tests { gray_block(0xC1, 12, Some(&dht), &word.to_be_bytes()) } + /// A valid 12-bit progressive DC-first scan with a one-bit zero-DC Huffman code. + fn twelve_bit_progressive_dc_block() -> Vec { + let mut s = vec![0xFF, 0xD8]; + let mut dqt = vec![0u8]; + dqt.extend([1u8; 64]); + segment(&mut s, 0xDB, &dqt); + segment(&mut s, 0xC2, &[12, 0, 8, 0, 8, 1, 1, 0x11, 0]); + let mut dht = vec![0x00, 1]; + dht.extend([0u8; 15]); + dht.push(0); + segment(&mut s, 0xC4, &dht); + // One component, DC table 0, DC coefficients only, first approximation. + segment(&mut s, 0xDA, &[1, 1, 0, 0, 0, 0]); + s.push(0x7F); // DC category 0 followed by one padding bits. + s.extend([0xFF, 0xD9]); + s + } + fn twelve_bit(v: f32) -> u16 { (v * 65535.0 / 4095.0).round() as u16 } @@ -818,41 +984,26 @@ mod tests { } #[test] - fn lossless_is_unsupported_and_twelve_bit_progressive_decodes() { - for marker in [0xC3, 0xC2] { - let bytes = if marker == 0xC2 { - // Use a valid progressive DC scan so this exercises unsupported - // precision rather than failing on missing tables or scan syntax. - let mut bytes = vec![0xFF, 0xD8]; - let mut dqt = vec![0]; - dqt.extend([1u8; 64]); - segment(&mut bytes, 0xDB, &dqt); - segment(&mut bytes, marker, &[12, 0, 8, 0, 8, 1, 1, 0x11, 0]); - let mut dht = vec![0x00, 1]; - dht.extend([0u8; 15]); - dht.push(0); - dht.extend([0x10, 1]); - dht.extend([0u8; 15]); - dht.push(0); - segment(&mut bytes, 0xC4, &dht); - segment(&mut bytes, 0xDA, &[1, 1, 0, 0, 0, 0]); - bytes.extend([0x7F, 0xFF, 0xD9]); - bytes - } else { - let mut bytes = vec![0xFF, 0xD8, 0xFF, marker, 0, 11, 12, 0, 8, 0, 8, 1, 1, 0x11, 0]; - bytes.extend_from_slice(&[0xFF, 0xDA, 0, 8, 1, 1, 0, 0, 0x3F, 0, 0x12, 0x34, 0xFF, 0xD9]); - bytes - }; - if marker == 0xC2 { - // craft-jpeg supports 12-bit progressive Huffman frames; keep the facade's - // routing contract aligned with the decoder rather than rejecting valid input. - let image = crate::decode(&bytes).unwrap(); - assert_eq!((image.dimensions(), image.sample_type(), image.layout()), ((8, 8), SampleType::U16, ChannelLayout::Gray)); - } else { - let error = crate::decode(&bytes).unwrap_err(); - assert!(matches!(error, CodecError::Unsupported { .. }), "{marker:#x}: {error:?}"); - } - } + fn lossless_is_unsupported_not_damaged() { + let bytes = gray_block(0xC3, 12, None, &[0x12, 0x34]); + let e = crate::decode(&bytes).unwrap_err(); + assert!(matches!(e, CodecError::Unsupported { .. }), "{e:?}"); + } + + #[test] + fn twelve_bit_progressive_dc_scan_decodes() { + let img = crate::decode(&twelve_bit_progressive_dc_block()).unwrap(); + assert_eq!((img.dimensions(), img.sample_type(), img.layout()), ((8, 8), SampleType::U16, ChannelLayout::Gray)); + assert!(img.warnings.is_empty()); + } + + #[test] + fn malformed_twelve_bit_progressive_scan_is_malformed_not_damaged() { + // A DC-first progressive scan must have Se=0, not the sequential scan's Se=63. + let mut bytes = vec![0xFF, 0xD8, 0xFF, 0xC2, 0, 11, 12, 0, 8, 0, 8, 1, 1, 0x11, 0]; + bytes.extend_from_slice(&[0xFF, 0xDA, 0, 8, 1, 1, 0, 0, 0x3F, 0, 0x12, 0x34, 0xFF, 0xD9]); + let e = crate::decode(&bytes).unwrap_err(); + assert!(matches!(e, CodecError::Malformed { .. }), "{e:?}"); } #[test] @@ -889,6 +1040,47 @@ mod tests { assert!(img.warnings.is_empty()); } + #[test] + fn unmarked_cmyk_restores_direct_ink_polarity_on_craft_backend() { + // craft-jpeg always returns non-YCC four-component samples with Adobe inversion undone. + // The adapter restores direct inks only when no APP14 marker identifies Adobe storage. + let mut u8_samples = [0, 32, 200, 255]; + undo_craft_cmyk_inversion_u8(&mut u8_samples, true); + assert_eq!(u8_samples, [255, 223, 55, 0]); + undo_craft_cmyk_inversion_u8(&mut u8_samples, false); + assert_eq!(u8_samples, [255, 223, 55, 0], "marked samples keep craft-jpeg polarity"); + + let mut u16_samples = [0, 8192, 32768, 65535]; + undo_craft_cmyk_inversion_u16(&mut u16_samples, true); + assert_eq!(u16_samples, [65535, 57343, 32767, 0]); + undo_craft_cmyk_inversion_u16(&mut u16_samples, false); + assert_eq!(u16_samples, [65535, 57343, 32767, 0], "marked samples keep craft-jpeg polarity"); + } + + #[test] + fn twelve_bit_cmyk_without_app14_keeps_direct_ink_polarity_on_craft_backend() { + let image = Image::from_u8(16, 16, ChannelLayout::Cmyk, [10u8, 100, 200, 50].repeat(256)).unwrap(); + let mut marked = crate::encode(&image, Format::Jpeg, &EncodeOptions { jpeg_quality: 95, ..Default::default() }).unwrap(); + let sof = marked.windows(2).position(|pair| pair == [0xFF, 0xC0]).expect("baseline SOF0"); + marked[sof + 1] = 0xC1; + marked[sof + 4] = 12; + assert!(uses_craft_jpeg(&marked), "12-bit SOF1 routes through craft-jpeg"); + + let app14 = b"\xFF\xEE\x00\x0EAdobe"; + let start = marked.windows(app14.len()).position(|part| part == app14).expect("Adobe APP14 marker"); + let mut unmarked = Vec::with_capacity(marked.len() - 16); + unmarked.extend_from_slice(&marked[..start]); + unmarked.extend_from_slice(&marked[start + 16..]); + assert!(uses_craft_jpeg(&unmarked)); + + let adobe = crate::decode(&marked).unwrap().to_u16_samples().unwrap(); + let direct_inks = crate::decode(&unmarked).unwrap().to_u16_samples().unwrap(); + assert_eq!(adobe.len(), direct_inks.len()); + for (&stored_adobe, &ink) in adobe.iter().zip(&direct_inks) { + assert_eq!(ink, 65535 - stored_adobe, "unmarked samples remain direct inks"); + } + } + #[test] fn twelve_bit_jpeg_keeps_its_photoshop_resources() { // An APP13 `8BIM` block (paths, Photoshop settings) right after SOI, as on the zune-jpeg path. diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index cf061f49b..4ceb75403 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -581,6 +581,10 @@ impl> PngDecodeRows { let info = self.reader.info(); let icc = info.icc_profile.as_ref().map(|c| c.to_vec()); let mut meta = Metadata { exif: info.exif_metadata.as_ref().map(|c| c.to_vec()), ..Default::default() }; + meta.content_light_level = info.content_light_level.map(|light| crate::cicp::ContentLightLevel { + max_content_light_level: light.max_content_light_level, + max_frame_average_light_level: light.max_frame_average_light_level, + }); if let Some(d) = info.pixel_dims && d.unit == png::Unit::Meter && d.xppu > 0 @@ -597,7 +601,13 @@ impl> PngDecodeRows { warnings.push(DecodeWarning::MoreFrames { total: u32::try_from(self.images).ok() }); } let orientation = meta.exif.as_deref().map_or(1, crate::orientation::exif_orientation); - PngExtras { icc, meta, warnings, orientation } + let cicp = info.coding_independent_code_points.map(|c| crate::cicp::Cicp { + primaries: u16::from(c.color_primaries), + transfer: u16::from(c.transfer_function), + matrix: u16::from(c.matrix_coefficients), + full_range: c.is_video_full_range_image, + }); + PngExtras { icc, cicp, meta, warnings, orientation } } /// The image itself, with what the metadata scan accepted. @@ -606,6 +616,7 @@ impl> PngDecodeRows { let mut img = Image::from_raw(self.width, height, self.layout, self.sample, std::mem::take(&mut self.buf))?; let extras = self.extras(); img.icc = extras.icc; + img.cicp = extras.cicp; img.meta = extras.meta; img.warnings = extras.warnings; Ok(img) @@ -624,6 +635,8 @@ fn to_native_endian(samples: &mut [u8]) { /// they are complete only once the pixels have been read. pub struct PngExtras { pub icc: Option>, + /// The PNG `cICP` colour description, if present. + pub cicp: Option, pub meta: Metadata, pub warnings: Vec, /// The EXIF orientation (1-8) the pixels are stored in; 1 when there is none. @@ -1050,29 +1063,114 @@ impl Write for FallibleOutput<'_> { pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { let img = src.converted(plan.layout, plan.sample); let (w, h) = img.dimensions(); - let bpp = img.layout().channels() * img.sample_type().bytes(); // Big-endian sample bytes. let mut data = std::borrow::Cow::Borrowed(img.data()); if img.sample_type() == SampleType::U16 { to_big_endian(data.to_mut()); } + encode_data( + RawPng { + width: w, + height: h, + layout: img.layout(), + sample: img.sample_type(), + icc: img.icc.as_ref(), + cicp: img.cicp, + meta: &img.meta, + data: &data, + }, + opts, + ) +} + +struct RawPng<'a> { + width: u32, + height: u32, + layout: ChannelLayout, + sample: SampleType, + icc: Option<&'a Vec>, + cicp: Option, + meta: &'a Metadata, + data: &'a [u8], +} + +fn encode_data(raw: RawPng<'_>, opts: &EncodeOptions) -> Result, CodecError> { + let RawPng { width: w, height: h, layout, sample, icc, cicp, meta, data } = raw; + let bpp = layout.channels() * sample.bytes(); let mut out = Vec::new(); { let mut output = FallibleOutput(&mut out); - let mut writer = start(&mut output, (w, h), (img.layout(), img.sample_type()), img.icc.as_ref(), &img.meta, opts)?; + let mut writer = start(&mut output, (w, h), (layout, sample), icc, cicp, meta, opts)?; if opts.png_interlaced { - let idat = adam7_idat(&data, w as usize, h as usize, bpp, opts.png_compression)?; + let idat = adam7_idat(data, w as usize, h as usize, bpp, opts.png_compression)?; write_idat(&mut writer, &idat, MAX_IDAT)?; - } else if let Some(idat) = parallel_idat(&data, w as usize, h as usize, bpp, opts.png_compression) { + } else if let Some(idat) = parallel_idat(data, w as usize, h as usize, bpp, opts.png_compression) { write_idat(&mut writer, &idat, MAX_IDAT)?; } else { - writer.write_image_data(&data).map_err(|e| CodecError::encode(F, e))?; + writer.write_image_data(data).map_err(|e| CodecError::encode(F, e))?; } writer.finish().map_err(|e| CodecError::encode(F, e))?; } Ok(out) } +/// Encodes linear-light Rec. 2020 RGB as 16-bit PNG with BT.2100 PQ (`cICP`) and measured +/// content-light levels (`cLLI`). Input samples are relative to 203 cd/m² diffuse white, as in +/// [`crate::cicp::linearize`]. Negative and non-finite values become black; values above 10,000 +/// cd/m² are clipped to the PQ signal range. EXIF, XMP, and resolution metadata follow `opts`. +pub fn encode_pq(src: &Image, opts: &EncodeOptions) -> Result, CodecError> { + if src.layout() != ChannelLayout::Rgb || src.sample_type() != SampleType::F32 { + return Err(CodecError::encode(F, "PQ PNG input must be linear-light F32 RGB")); + } + let (width, height) = src.dimensions(); + if width == 0 || height == 0 { + return Err(CodecError::InvalidImage("cannot encode an empty image".into())); + } + let pixels = usize::try_from(u64::from(width) * u64::from(height)).map_err(|_| CodecError::encode(F, "image is too large"))?; + let samples = pixels.checked_mul(3).ok_or_else(|| CodecError::encode(F, "image is too large"))?; + let bytes = samples.checked_mul(2).ok_or_else(|| CodecError::encode(F, "image is too large"))?; + if src.data().len() != samples.checked_mul(4).ok_or_else(|| CodecError::encode(F, "image is too large"))? { + return Err(CodecError::encode(F, "RGB buffer length does not match the image dimensions")); + } + let mut output = Vec::new(); + output.try_reserve_exact(bytes).map_err(|_| CodecError::encode(F, "not enough memory for PQ samples"))?; + let mut max_nits = 0.0f32; + let mut sum_luma = 0.0f64; + for rgb in src.data().as_chunks::<12>().0 { + let read = |at| -> Result { + let bytes = rgb.get(at..at + 4).ok_or_else(|| CodecError::encode(F, "RGB buffer is truncated"))?; + let bytes: [u8; 4] = bytes.try_into().map_err(|_| CodecError::encode(F, "RGB sample is truncated"))?; + Ok(f32::from_ne_bytes(bytes)) + }; + let values = [read(0)?, read(4)?, read(8)?]; + let nits = values.map(|v| if v.is_finite() { (v.max(0.0) * crate::cicp::REFERENCE_WHITE_NITS).min(crate::cicp::PQ_PEAK_NITS) } else { 0.0 }); + max_nits = max_nits.max(nits[0]).max(nits[1]).max(nits[2]); + // CTA-861.3-A defines MaxFALL as the average of each pixel's maximum linear RGB channel. + sum_luma += f64::from(nits[0].max(nits[1]).max(nits[2])); + for value in nits { + let encoded = crate::cicp::linear_to_pq(value / crate::cicp::REFERENCE_WHITE_NITS); + output.extend_from_slice(&((encoded * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes()); + } + } + let max_cll = ((max_nits.ceil().clamp(1.0, crate::cicp::PQ_PEAK_NITS)) as u32).saturating_mul(10_000); + let max_fall = (((sum_luma / pixels as f64).ceil().clamp(1.0, f64::from(crate::cicp::PQ_PEAK_NITS))) as u32).saturating_mul(10_000); + let mut meta = src.meta.clone(); + meta.content_light_level = Some(crate::cicp::ContentLightLevel { max_content_light_level: max_cll, max_frame_average_light_level: max_fall }); + encode_data( + RawPng { + width, + height, + layout: ChannelLayout::Rgb, + sample: SampleType::U16, + icc: None, + cicp: Some(crate::cicp::Cicp { primaries: 9, transfer: crate::cicp::Cicp::TRANSFER_PQ, matrix: 0, full_range: true }), + meta: &meta, + data: &output, + }, + opts, + ) +} + /// 16-bit native-endian samples to PNG's big-endian order, in place. fn to_big_endian(data: &mut [u8]) { for c in data.as_chunks_mut::<2>().0 { @@ -1088,6 +1186,7 @@ fn start( (w, h): (u32, u32), (layout, sample): (ChannelLayout, SampleType), icc: Option<&Vec>, + cicp: Option, meta: &Metadata, opts: &EncodeOptions, ) -> Result, CodecError> { @@ -1154,6 +1253,22 @@ fn start( } } let mut writer = encoder.write_header().map_err(|e| CodecError::encode(F, e))?; + if let Some(cicp) = cicp { + let point = |value: u16, name: &str| { + u8::try_from(value).map_err(|_| CodecError::encode(F, format!("CICP {name} value {value} does not fit in a byte"))) + }; + // PNG stores RGB samples, so cICP's matrix coefficients byte is always zero. + let cicp_bytes = [point(cicp.primaries, "primaries")?, point(cicp.transfer, "transfer")?, 0, u8::from(cicp.full_range)]; + writer.write_chunk(png::chunk::cICP, &cicp_bytes).map_err(|e| CodecError::encode(F, e))?; + } + if opts.embed_metadata + && let Some(light) = meta.content_light_level + { + let mut bytes = [0; 8]; + bytes[..4].copy_from_slice(&light.max_content_light_level.to_be_bytes()); + bytes[4..].copy_from_slice(&light.max_frame_average_light_level.to_be_bytes()); + writer.write_chunk(png::chunk::cLLI, &bytes).map_err(|e| CodecError::encode(F, e))?; + } if let Some(stereo) = opts.png_stereo { // Ancillary chunk before IDAT, as the spec recommends for `sTER`. writer.write_chunk(png::chunk::ChunkType(*b"sTER"), &[stereo.mode()]).map_err(|e| CodecError::encode(F, e))?; @@ -1208,7 +1323,7 @@ impl PngRows { return Err(CodecError::InvalidImage("cannot encode an empty image".into())); } let plan = crate::fidelity::plan(first, F, opts); - let writer = start(out, (width, height), (plan.layout, plan.sample), first.icc.as_ref(), &first.meta, opts)?; + let writer = start(out, (width, height), (plan.layout, plan.sample), first.icc.as_ref(), first.cicp, &first.meta, opts)?; Ok(Self { writer, plan, @@ -1599,6 +1714,83 @@ pub fn encode_indexed( Ok(out) } +#[cfg(test)] +mod hdr_tests { + use super::*; + + #[test] + fn generic_png_roundtrip_keeps_cicp_and_content_light_level() { + let mut image = Image::from_raw(1, 1, ChannelLayout::Rgb, SampleType::U16, vec![0, 0, 0, 0, 0, 0]).unwrap(); + image.cicp = Some(crate::cicp::Cicp { primaries: 9, transfer: 16, matrix: 9, full_range: true }); + image.meta.content_light_level = + Some(crate::cicp::ContentLightLevel { max_content_light_level: 2_030_000, max_frame_average_light_level: 1_250_000 }); + + let encoded = encode(&image, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U16 }, &EncodeOptions::default()).unwrap(); + let decoded = decode(&encoded, &Limits::default()).unwrap(); + assert_eq!(decoded.cicp, Some(crate::cicp::Cicp { matrix: 0, ..image.cicp.unwrap() })); + assert_eq!(decoded.meta.content_light_level, image.meta.content_light_level); + } + + #[test] + fn generic_png_keeps_cicp_alongside_icc() { + let mut image = Image::from_raw(1, 1, ChannelLayout::Rgb, SampleType::U16, vec![0, 0, 0, 0, 0, 0]).unwrap(); + image.cicp = Some(crate::cicp::Cicp { primaries: 9, transfer: 16, matrix: 0, full_range: true }); + image.icc = Some(b"synthetic ICC profile".to_vec()); + + let encoded = encode(&image, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U16 }, &EncodeOptions::default()).unwrap(); + let decoded = decode(&encoded, &Limits::default()).unwrap(); + assert_eq!(decoded.cicp, image.cicp); + assert_eq!(decoded.icc, image.icc); + } + + #[test] + fn linearized_pq_pixels_are_tagged_as_linear_in_generic_png() { + let cicp = crate::cicp::Cicp { primaries: 9, transfer: crate::cicp::Cicp::TRANSFER_PQ, matrix: 0, full_range: true }; + let encoded_white = (0.5807f32 * 65535.0).round() as u16; + let mut image = Image::from_u16(1, 1, ChannelLayout::Rgb, &[encoded_white; 3]).unwrap(); + image.cicp = Some(cicp); + let linear = crate::cicp::linearize(image, cicp).unwrap(); + let png = encode(&linear, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U16 }, &EncodeOptions::default()).unwrap(); + let decoded = decode(&png, &Limits::default()).unwrap(); + assert_eq!(decoded.cicp.unwrap().transfer, crate::cicp::Cicp::TRANSFER_LINEAR); + assert!(decoded.to_normalized().iter().all(|&v| (v - 1.0).abs() < 0.001)); + } + + #[test] + fn pq_png_writes_rec2020_codes_and_measured_light_levels() { + let image = Image::from_f32(1, 1, ChannelLayout::Rgb, &[1.0, 1.0, 1.0]).unwrap(); + let encoded = encode_pq(&image, &EncodeOptions::default()).unwrap(); + let mut reader = png::Decoder::new(Cursor::new(&encoded)).read_info().unwrap(); + let info = reader.info(); + let cicp = info.coding_independent_code_points.unwrap(); + assert_eq!((cicp.color_primaries, cicp.transfer_function, cicp.matrix_coefficients, cicp.is_video_full_range_image), (9, 16, 0, true)); + let light = info.content_light_level.unwrap(); + assert_eq!((light.max_content_light_level, light.max_frame_average_light_level), (2_030_000, 2_030_000)); + let mut bytes = vec![0; reader.output_buffer_size().unwrap()]; + let frame = reader.next_frame(&mut bytes).unwrap(); + let rgb = bytes.get(..frame.buffer_size()).unwrap().as_chunks::<2>().0.iter().map(|v| u16::from_be_bytes(*v)).collect::>(); + assert_eq!(rgb.len(), 3); + for sample in rgb { + assert!((f32::from(sample) / 65535.0 - 0.5807).abs() < 0.001); + } + } + + #[test] + fn pq_png_maxfall_uses_highest_channel_for_saturated_pixels() { + let image = Image::from_f32(2, 1, ChannelLayout::Rgb, &[1.0, 0.0, 0.0, 0.0, 0.0, 1.0]).unwrap(); + let encoded = encode_pq(&image, &EncodeOptions::default()).unwrap(); + let reader = png::Decoder::new(Cursor::new(encoded)).read_info().unwrap(); + let light = reader.info().content_light_level.unwrap(); + assert_eq!((light.max_content_light_level, light.max_frame_average_light_level), (2_030_000, 2_030_000)); + } + + #[test] + fn pq_png_rejects_empty_images() { + let image = Image::from_f32(0, 1, ChannelLayout::Rgb, &[]).unwrap(); + assert!(encode_pq(&image, &EncodeOptions::default()).is_err()); + } +} + #[cfg(test)] mod stereo_tests { use super::*; @@ -2030,7 +2222,8 @@ mod streamed_tests { let whole = crate::encode(&img, Format::Png, &EncodeOptions::default()).unwrap(); let (_, zlib, _) = split(&whole); let mut out = Vec::new(); - let mut w = start(&mut out, (64, 40), (ChannelLayout::Rgb, SampleType::U8), None, &Metadata::default(), &EncodeOptions::default()).unwrap(); + let mut w = + start(&mut out, (64, 40), (ChannelLayout::Rgb, SampleType::U8), None, None, &Metadata::default(), &EncodeOptions::default()).unwrap(); write_idat(&mut w, &zlib, 100).unwrap(); w.finish().unwrap(); let (_, joined, count) = split(&out); diff --git a/crates/image-codecs/src/codecs/tiff/bands.rs b/crates/image-codecs/src/codecs/tiff/bands.rs index 117c95ded..093f90efd 100644 --- a/crates/image-codecs/src/codecs/tiff/bands.rs +++ b/crates/image-codecs/src/codecs/tiff/bands.rs @@ -230,7 +230,16 @@ fn decode_band( } continue; } - let buf = chunk_scratch(lay, scratch, pref.len)?; + if pref.len > lay.scratch_cap { + return Err(CodecError::LimitExceeded(format!("a {} byte strip or tile", pref.len))); + } + if scratch.len() < pref.len { + scratch + .try_reserve_exact(pref.len - scratch.len()) + .map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {} bytes for a strip or tile", pref.len)))?; + scratch.resize(pref.len, 0); + } + let buf = scratch.get_mut(..pref.len).ok_or_else(|| err("scratch buffer"))?; match dec.read_chunk_bytes(chunk, buf) { Ok(()) => tally.decoded += 1, Err(e) if is_eof(&e) => { @@ -275,19 +284,6 @@ fn deposit_extras(lay: &Layout, src: &[u8], dst: &mut [u8], n: usize, x0: usize) } } -fn chunk_scratch<'a>(lay: &Layout, scratch: &'a mut Vec, len: usize) -> Result<&'a mut [u8], CodecError> { - if len > lay.scratch_cap { - return Err(CodecError::LimitExceeded(format!("a {} byte strip or tile", len))); - } - if scratch.len() < len { - scratch - .try_reserve_exact(len - scratch.len()) - .map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {} bytes for a strip or tile", len)))?; - scratch.resize(len, 0); - } - scratch.get_mut(..len).ok_or_else(|| err("scratch buffer")) -} - /// Planar files store each extra sample as its own plane. Read those planes into `extra`. fn read_planar_extras( lay: &Layout, @@ -314,7 +310,16 @@ fn read_planar_extras( .ok_or_else(|| err("chunk index out of range"))?; let pref = dec.image_chunk_buffer_layout(chunk).map_err(map_err)?; let stride = pref.row_stride.map(|s| s.get()).ok_or_else(|| err("empty chunk row"))?; - let buf = chunk_scratch(lay, scratch, pref.len)?; + if pref.len > lay.scratch_cap { + return Err(CodecError::LimitExceeded(format!("a {} byte strip or tile", pref.len))); + } + if scratch.len() < pref.len { + scratch + .try_reserve_exact(pref.len - scratch.len()) + .map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {} bytes for a strip or tile", pref.len)))?; + scratch.resize(pref.len, 0); + } + let buf = scratch.get_mut(..pref.len).ok_or_else(|| err("scratch buffer"))?; match dec.read_chunk_bytes(chunk, buf) { Ok(()) => tally.decoded += 1, Err(e) if is_eof(&e) => { diff --git a/crates/image-codecs/src/codecs/tiff_ifd.rs b/crates/image-codecs/src/codecs/tiff_ifd.rs index 8fac8c6b4..0783cbdf3 100644 --- a/crates/image-codecs/src/codecs/tiff_ifd.rs +++ b/crates/image-codecs/src/codecs/tiff_ifd.rs @@ -41,6 +41,7 @@ pub(crate) const TAG_TILE_WIDTH: u16 = 322; pub(crate) const TAG_TILE_LENGTH: u16 = 323; pub(crate) const TAG_TILE_OFFSETS: u16 = 324; pub(crate) const TAG_SUB_IFDS: u16 = 330; +pub(crate) const TAG_INK_SET: u16 = 332; pub(crate) const TAG_EXTRA_SAMPLES: u16 = 338; pub(crate) const TAG_SAMPLE_FORMAT: u16 = 339; @@ -349,6 +350,56 @@ pub struct TiffPage { pub tiled: bool, /// `PlanarConfiguration` 2: each sample in its own plane. pub planar: bool, + /// TIFF `InkSet` (tag 332), when present. Only meaningful for photometric 5 (Separated). + pub ink_set: Option, + /// TIFF `ExtraSamples` (tag 338), one per extra sample. Empty when the tag is absent or + /// unreadable. + pub extra_samples: Vec, +} + +/// The TIFF `InkSet` tag (332) of a separated image. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InkSet { + /// 1: the samples are cyan, magenta, yellow and black. + Cmyk, + /// 2: the samples are the inks listed in the `InkNames` tag. + InkNames, + /// Any other value; TIFF 6.0 defines only 1 and 2. + Invalid(u16), +} + +impl InkSet { + fn from_tag(value: u16) -> Self { + match value { + 1 => Self::Cmyk, + 2 => Self::InkNames, + v => Self::Invalid(v), + } + } +} + +/// What one extra sample of a TIFF holds, from the `ExtraSamples` tag (338). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExtraSampleKind { + /// 0: unspecified data. + Unspecified, + /// 1: associated (premultiplied) alpha. + AssociatedAlpha, + /// 2: unassociated (straight) alpha. + UnassociatedAlpha, + /// Any other value; TIFF 6.0 defines only 0, 1 and 2. + Invalid(u16), +} + +impl ExtraSampleKind { + fn from_tag(value: u16) -> Self { + match value { + 0 => Self::Unspecified, + 1 => Self::AssociatedAlpha, + 2 => Self::UnassociatedAlpha, + v => Self::Invalid(v), + } + } } /// The directory structure of a TIFF file: its byte order, BigTIFF or not, and every image @@ -405,6 +456,14 @@ fn describe(f: &File<'_>, ifd: &Ifd, parent: Option) -> TiffPage { compression: u16_of(TAG_COMPRESSION, 1), tiled: ifd.get(TAG_TILE_OFFSETS).is_some(), planar: f.tag_uint(ifd, TAG_PLANAR) == Some(2), + ink_set: f.tag_uint(ifd, TAG_INK_SET).map(|v| InkSet::from_tag(u16::try_from(v).unwrap_or(u16::MAX))), + // Capped at the sample count: a file cannot have more extra samples than samples. + extra_samples: f + .tag_uints(ifd, TAG_EXTRA_SAMPLES, u64::from(u16_of(TAG_SAMPLES, 1))) + .unwrap_or_default() + .into_iter() + .map(|v| ExtraSampleKind::from_tag(u16::try_from(v).unwrap_or(u16::MAX))) + .collect(), } } diff --git a/crates/image-codecs/src/exif_color.rs b/crates/image-codecs/src/exif_color.rs index 8a35907ff..4259bb15c 100644 --- a/crates/image-codecs/src/exif_color.rs +++ b/crates/image-codecs/src/exif_color.rs @@ -1,16 +1,70 @@ -//! Shared EXIF ColorSpace tag parsing. +//! The EXIF ColorSpace tag (0xA001, in the Exif sub-IFD that IFD0's tag 0x8769 points to): +//! 1 = sRGB, 0xFFFF = uncalibrated (EXIF 2.3, §4.6.5). +//! +//! Cameras write it instead of an ICC profile. Photoshop opens a file with no embedded profile but +//! ColorSpace = sRGB as sRGB, unless Preferences › File Handling › Ignore EXIF Profile Tag is on. +//! Anything malformed, truncated or missing reads as no tag. -pub use craft_metadata::edit::{EXIF_COLOR_SPACE_SRGB, exif_color_space}; +use crate::orientation::{Order, ifd0_entries, tiff_body}; + +/// IFD0's pointer to the Exif sub-IFD. +const TAG_EXIF_IFD: u16 = 0x8769; +/// The ColorSpace tag in the Exif sub-IFD. +const TAG_COLOR_SPACE: u16 = 0xA001; +const TYPE_SHORT: u16 = 3; +const TYPE_LONG: u16 = 4; +/// TIFF type 13: an IFD offset (some writers use it for sub-IFD pointers). +const TYPE_IFD: u16 = 13; +/// Bytes per classic TIFF IFD entry; EXIF is never BigTIFF. +const ENTRY: usize = 12; +/// No IFD can start inside the 8-byte TIFF header. +const HEADER: usize = 8; + +/// The ColorSpace value meaning sRGB. +pub const EXIF_COLOR_SPACE_SRGB: u16 = 1; + +/// The EXIF ColorSpace value of a TIFF-structured block (an EXIF payload with or without the +/// `Exif\0\0` prefix), or `None` when it has none or it is malformed. +pub fn exif_color_space(exif: &[u8]) -> Option { + let b = tiff_body(exif); + let (order, first, count, entry_bytes, big_tiff) = ifd0_entries(b)?; + if big_tiff { + return None; + } + let ptr = find(order, b, first, count, entry_bytes, TAG_EXIF_IFD)?; + if !matches!(order.u16(b, ptr.checked_add(2)?)?, TYPE_LONG | TYPE_IFD) || order.u32(b, ptr.checked_add(4)?)? != 1 { + return None; + } + let ifd = usize::try_from(order.u32(b, ptr.checked_add(8)?)?).ok()?; + if ifd < HEADER { + return None; + } + let n = usize::from(order.u16(b, ifd)?); + let first = ifd.checked_add(2)?; + // The whole table must be present. + if first.checked_add(n.checked_mul(ENTRY)?)? > b.len() { + return None; + } + let e = find(order, b, first, n, ENTRY, TAG_COLOR_SPACE)?; + if order.u32(b, e.checked_add(4)?)? != 1 { + return None; + } + match order.u16(b, e.checked_add(2)?)? { + TYPE_SHORT => order.u16(b, e.checked_add(8)?), + TYPE_LONG => u16::try_from(order.u32(b, e.checked_add(8)?)?).ok(), + _ => None, + } +} + +/// Offset of the first entry tagged `tag` in the IFD whose `count` entries start at `first`. +fn find(order: Order, b: &[u8], first: usize, count: usize, entry_bytes: usize, tag: u16) -> Option { + (0..count).filter_map(|i| first.checked_add(i.checked_mul(entry_bytes)?)).find(|&e| order.u16(b, e) == Some(tag)) +} #[cfg(test)] mod tests { use super::*; - const TAG_EXIF_IFD: u16 = 0x8769; - const TAG_COLOR_SPACE: u16 = 0xA001; - const TYPE_SHORT: u16 = 3; - const TYPE_LONG: u16 = 4; - /// A little- or big-endian EXIF block: IFD0 holding only the Exif pointer, then an Exif IFD /// holding `entries` (tag, type, count, value). fn exif(big_endian: bool, entries: &[(u16, u16, u32, u32)]) -> Vec { diff --git a/crates/image-codecs/src/exr_stream.rs b/crates/image-codecs/src/exr_stream.rs index 936814360..6ffa95c53 100644 --- a/crates/image-codecs/src/exr_stream.rs +++ b/crates/image-codecs/src/exr_stream.rs @@ -199,6 +199,12 @@ impl Decoder { } offsets.push(offset); } + // Check the bounded offset table before rejecting a large declared image. + // A truncated file with an oversized data window is malformed; a complete + // file above the streaming area limit is rejected before any pixel decode. + if (w as u64).saturating_mul(h as u64) > 1 << 30 { + return Err(limit("EXR pixel count exceeds the streaming limit of 1073741824")); + } Ok(Self { source, meta, info, offsets, seen: vec![false; expected], channels, next: 0, file_len, chunks_start, raw_limit, rows }) } diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index c77f9a09f..ecaf945cd 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -42,6 +42,8 @@ pub enum Format { Dicom, /// Amiga IFF/ILBM (`FORM ... ILBM`): planar bitplanes with a palette or 24-bit RGB. Iff, + /// JPEG 2000 (JP2 container or raw J2K codestream): read-only; see [`ASYMMETRIC_EXCEPTIONS`]. + Jp2, } /// What a format can hold **and** what this crate reads/writes for it. @@ -98,6 +100,7 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[ writing needs an HEVC encoder, and the mature ones (x265, libheif) are C, so write stays \ unsupported. Without the feature HEIF is detected but neither read nor written.", ), + (Format::Jp2, "JPEG 2000 decode uses hayro-jpeg2000 (pure Rust); writing JPEG 2000 is not provided."), ]; use ChannelLayout as L; @@ -110,9 +113,10 @@ const TIFF_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L:: impl Format { /// Every format known to the crate (enabled or not). - pub const ALL: [Format; 23] = [ + pub const ALL: [Format; 24] = [ Format::Png, Format::Jpeg, + Format::Jp2, Format::Jxl, Format::Tiff, Format::WebP, @@ -171,6 +175,7 @@ impl Format { Format::Cineon => "Cineon", Format::Dicom => "DICOM", Format::Iff => "Amiga IFF", + Format::Jp2 => "JPEG 2000", } } @@ -201,6 +206,7 @@ impl Format { Format::Cineon => &["cin"], Format::Dicom => &["dcm", "dicom", "dc3"], Format::Iff => &["iff", "lbm", "ilbm"], + Format::Jp2 => &["jp2", "j2k", "j2c", "jpf", "jpx"], } } @@ -229,6 +235,7 @@ impl Format { Format::Cineon => "image/x-cin", Format::Dicom => "application/dicom", Format::Iff => "image/x-iff", + Format::Jp2 => "image/jp2", } } @@ -303,6 +310,7 @@ pub fn caps(format: Format) -> FormatCaps { Format::Cineon => FormatCaps { depths: &[S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, Format::Dicom => FormatCaps { read: true, write: false, depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, Format::Iff => FormatCaps { depths: &[S::U8], layouts: &[L::Rgb, L::Rgba], alpha: true, ..base }, + Format::Jp2 => FormatCaps { read: true, write: false, layouts: &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk, L::CmykA], icc: true, ..base }, } } @@ -320,6 +328,10 @@ pub fn detect(bytes: &[u8]) -> Option { if b.starts_with(&[0xFF, 0x0A]) || b.starts_with(b"\0\0\0\x0cJXL \r\n\x87\n") { return Some(Format::Jxl); } + // JPEG 2000 container signature box or raw J2K codestream (SOC + SIZ). + if b.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") || b.starts_with(b"\xff\x4f\xff\x51") { + return Some(Format::Jp2); + } if b.starts_with(b"II*\0") || b.starts_with(b"MM\0*") || b.starts_with(b"II+\0") || b.starts_with(b"MM\0+") { return Some(Format::Tiff); } diff --git a/crates/image-codecs/src/image.rs b/crates/image-codecs/src/image.rs index dc555c42b..8f68197bf 100644 --- a/crates/image-codecs/src/image.rs +++ b/crates/image-codecs/src/image.rs @@ -8,6 +8,7 @@ use std::fmt; use crate::error::CodecError; use crate::format::Format; +use crate::options::Limits; use half::f16; /// Channel layout of an [`Image`]. Alpha, when present, is always the last @@ -142,6 +143,9 @@ pub struct Metadata { pub dpi: Option<(f32, f32)>, /// Free-form key/value text (PNG tEXt/iTXt, TIFF ASCII tags). pub text: Vec<(String, String)>, + /// HDR content light levels carried by formats such as PNG `cLLI`, in units of + /// 0.0001 cd/m² per value. A zero value means that level is unknown. + pub content_light_level: Option, /// Photoshop image resources (`8BIM` resource blocks): TIFF tag 34377. Kept opaque here; /// `photocraft-io` reads and writes them through `photocraft-psd`. pub photoshop_resources: Option>, @@ -174,6 +178,7 @@ impl Metadata { && self.xmp.is_none() && self.dpi.is_none() && self.text.is_empty() + && self.content_light_level.is_none() && self.photoshop_resources.is_none() && self.photoshop_layers.is_none() && self.extra_samples.is_empty() @@ -712,9 +717,31 @@ impl Image { self.convert(ChannelLayout::Rgba, SampleType::U16).to_u16_samples().unwrap_or_default() } - /// Interleaved RGBA as f32 (integer inputs normalized to `[0,1]`). - pub fn to_rgba_f32(&self) -> Vec { - convert_layout(&self.to_normalized(), self.layout, ChannelLayout::Rgba) + /// Interleaved RGBA as f32 (integer inputs normalized to `[0,1]`), with the same values as + /// [`Image::convert`] to RGBA F32. The output buffer is checked against `limits` (dimensions, + /// pixel count and `max_alloc`) and reserved before any pixel is converted, and the pixels are + /// written straight into it. A size over the limits, or a reservation the allocator refuses, + /// returns [`CodecError::LimitExceeded`]. An image with no pixels gives an empty vector. + pub fn to_rgba_f32(&self, limits: &Limits) -> Result, CodecError> { + if self.width == 0 || self.height == 0 { + return Ok(Vec::new()); + } + limits.check(self.width, self.height, ChannelLayout::Rgba, SampleType::F32)?; + let len = self + .pixel_count() + .checked_mul(ChannelLayout::Rgba.channels()) + .ok_or_else(|| CodecError::LimitExceeded("RGBA f32 size overflows usize".into()))?; + let mut out = Vec::new(); + out.try_reserve_exact(len).map_err(|e| CodecError::LimitExceeded(format!("cannot reserve {len} f32 samples for RGBA: {e}")))?; + let fc = self.layout.channels(); + let mut px = [0.0f32; 5]; + for p in 0..self.pixel_count() { + for (c, v) in px[..fc].iter_mut().enumerate() { + *v = read_normalized(&self.data, self.sample, p * fc + c); + } + convert_pixel(&px[..fc], self.layout, ChannelLayout::Rgba, &mut out); + } + Ok(out) } } @@ -886,33 +913,39 @@ pub(crate) fn convert_layout(src: &[f32], from: ChannelLayout, to: ChannelLayout let n = src.len() / fc; let mut out = Vec::with_capacity(n * tc); for px in src.chunks_exact(fc) { - let alpha = if from.has_alpha() { px[fc - 1] } else { 1.0 }; - let color = &px[..from.color_channels()]; - if from.same_model(to) { - out.extend_from_slice(color); - } else { - let rgb = match from { - ChannelLayout::Gray | ChannelLayout::GrayA => [color[0]; 3], - ChannelLayout::Rgb | ChannelLayout::Rgba => [color[0], color[1], color[2]], - ChannelLayout::Cmyk | ChannelLayout::CmykA => cmyk_to_rgb(color[0], color[1], color[2], color[3]), - ChannelLayout::Lab | ChannelLayout::LabA => crate::lab::lab_to_srgb([color[0], color[1], color[2]]), - }; - match to { - ChannelLayout::Gray | ChannelLayout::GrayA => { - out.push(rgb[0] * LUMA[0] + rgb[1] * LUMA[1] + rgb[2] * LUMA[2]); - } - ChannelLayout::Rgb | ChannelLayout::Rgba => out.extend_from_slice(&rgb), - ChannelLayout::Cmyk | ChannelLayout::CmykA => out.extend_from_slice(&rgb_to_cmyk(rgb[0], rgb[1], rgb[2])), - ChannelLayout::Lab | ChannelLayout::LabA => out.extend_from_slice(&crate::lab::srgb_to_lab(rgb)), - } - } - if to.has_alpha() { - out.push(alpha); - } + convert_pixel(px, from, to, &mut out); } out } +/// One pixel of [`convert_layout`]: the normalized samples `px` (`from` layout) appended to `out` +/// in the `to` layout. +fn convert_pixel(px: &[f32], from: ChannelLayout, to: ChannelLayout, out: &mut Vec) { + let alpha = if from.has_alpha() { px[from.channels() - 1] } else { 1.0 }; + let color = &px[..from.color_channels()]; + if from.same_model(to) { + out.extend_from_slice(color); + } else { + let rgb = match from { + ChannelLayout::Gray | ChannelLayout::GrayA => [color[0]; 3], + ChannelLayout::Rgb | ChannelLayout::Rgba => [color[0], color[1], color[2]], + ChannelLayout::Cmyk | ChannelLayout::CmykA => cmyk_to_rgb(color[0], color[1], color[2], color[3]), + ChannelLayout::Lab | ChannelLayout::LabA => crate::lab::lab_to_srgb([color[0], color[1], color[2]]), + }; + match to { + ChannelLayout::Gray | ChannelLayout::GrayA => { + out.push(rgb[0] * LUMA[0] + rgb[1] * LUMA[1] + rgb[2] * LUMA[2]); + } + ChannelLayout::Rgb | ChannelLayout::Rgba => out.extend_from_slice(&rgb), + ChannelLayout::Cmyk | ChannelLayout::CmykA => out.extend_from_slice(&rgb_to_cmyk(rgb[0], rgb[1], rgb[2])), + ChannelLayout::Lab | ChannelLayout::LabA => out.extend_from_slice(&crate::lab::srgb_to_lab(rgb)), + } + } + if to.has_alpha() { + out.push(alpha); + } +} + #[cfg(test)] mod tests { #[test] @@ -1038,6 +1071,52 @@ mod tests { assert!(Image::from_raw(2, 2, ChannelLayout::Rgb, SampleType::U8, vec![0; 11]).is_err()); } + #[test] + fn rgba_f32_limit_rejects_before_allocation() { + // 3x2 pixels: the RGBA f32 output is 3 * 2 * 4 * 4 = 96 bytes. Most sources here are + // smaller than that, so the source fitting the budget does not let the output through. + for sample in SampleType::ALL { + for layout in ChannelLayout::ALL { + let img = Image::new(3, 2, layout, sample).unwrap(); + let tight = Limits::new(3, 2, 6, 95); + assert!(matches!(img.to_rgba_f32(&tight), Err(CodecError::LimitExceeded(_))), "{layout:?} {sample:?}: max_alloc"); + let exact = Limits::new(3, 2, 6, 96); + assert_eq!(img.to_rgba_f32(&exact).map(|v| v.len()).ok(), Some(24), "{layout:?} {sample:?}"); + for limits in [Limits::new(2, 2, 6, 96), Limits::new(3, 1, 6, 96), Limits::new(3, 2, 5, 96)] { + assert!(matches!(img.to_rgba_f32(&limits), Err(CodecError::LimitExceeded(_))), "{layout:?} {sample:?}: {limits:?}"); + } + } + } + } + + #[test] + fn rgba_f32_matches_existing_conversions() { + // Edge, mid and (for float samples) out-of-range values, so the CMYK, Lab and alpha + // formulas and the f16 and f32 reads are all compared bit for bit. + let base = [0.0, 1.0, 0.5, 0.25, 0.75, 1.0 / 255.0, 0.3, 0.9, 1.5, -0.25]; + for sample in SampleType::ALL { + for layout in ChannelLayout::ALL { + let n = 7 * 3 * layout.channels(); + let vals: Vec = (0..n).map(|i| base[(i * 7 + i / 3) % base.len()]).collect(); + let img = Image::from_normalized(7, 3, layout, sample, &vals).unwrap(); + let got = img.to_rgba_f32(&Limits::default()).unwrap(); + let want = convert_layout(&img.to_normalized(), layout, ChannelLayout::Rgba); + let via_convert = img.convert(ChannelLayout::Rgba, SampleType::F32).to_f32_samples().unwrap(); + let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); + assert_eq!(bits(&got), bits(&want), "{layout:?} {sample:?}"); + assert_eq!(bits(&got), bits(&via_convert), "{layout:?} {sample:?}: convert"); + } + } + } + + #[test] + fn rgba_f32_of_an_empty_image_is_empty() { + for (w, h) in [(0, 0), (0, 3), (4, 0)] { + let img = Image::new(w, h, ChannelLayout::Rgb, SampleType::U8).unwrap(); + assert_eq!(img.to_rgba_f32(&Limits::new(1, 1, 1, 0)).ok(), Some(Vec::new()), "{w}x{h}"); + } + } + #[test] fn rgba8_of_gray() { let img = Image::from_u8(1, 1, ChannelLayout::GrayA, vec![10, 20]).unwrap(); diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index e6a54756c..6516b9ff2 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -15,6 +15,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod allocation; +pub mod apng; pub mod cicp; mod codecs; mod error; @@ -32,16 +33,18 @@ pub mod source_settings; pub mod web; pub use crate::allocation::probe_allocation_size; pub use crate::cicp::Cicp; +pub use crate::cicp::ContentLightLevel; +pub use crate::codecs::avif::{HDR_REFERENCE_WHITE_NITS, HdrTransfer, encode_avif_hdr, encode_avif_with_speed}; pub use crate::codecs::exr_cryptomatte::{cryptomatte_id, cryptomatte_key, cryptomatte_preview_color}; pub use crate::codecs::gif_frames::{AnimationFrame, MAX_GIF_FRAMES}; pub use crate::codecs::png::{ - PngDecodeRows, PngExtras, PngHeader, PngPalette, PngRowSink, PngRows, SharedBytes, encode_indexed as encode_png_indexed, palette as png_palette, - stereo as png_stereo, + PngDecodeRows, PngExtras, PngHeader, PngPalette, PngRowSink, PngRows, SharedBytes, encode_indexed as encode_png_indexed, + encode_pq as encode_png_pq, palette as png_palette, stereo as png_stereo, }; pub use crate::codecs::tiff::{ PhotoshopTags as TiffPhotoshopTags, TiffBands, photoshop_tags as tiff_photoshop_tags, writes_little_endian as tiff_writes_little_endian, }; -pub use crate::codecs::tiff_ifd::{TiffInfo, TiffPage, TiffPageKind}; +pub use crate::codecs::tiff_ifd::{ExtraSampleKind, InkSet, TiffInfo, TiffPage, TiffPageKind}; pub use crate::error::CodecError; pub use crate::exif_color::{EXIF_COLOR_SPACE_SRGB, exif_color_space}; pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_with}; @@ -60,7 +63,7 @@ pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_ pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding}; pub use half::f16; -use crate::codecs::{dds, dicom, dpx, exr, fits, heif, iff, jpeg, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; +use crate::codecs::{dds, dicom, dpx, exr, fits, heif, iff, jp2, jpeg, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; /// Detect the format and decode with default [`Limits`]. pub fn decode(bytes: &[u8]) -> Result { @@ -101,6 +104,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Iff => iff::decode(bytes, l), Format::OpenExr => exr::decode(bytes, l), Format::Heif => heif::decode(bytes, l, opts.keep_orientation), + Format::Jp2 => jp2::decode(bytes, l), Format::Jxl => Err(CodecError::unsupported(format, "JPEG XL reading is not yet available; export is supported")), Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::decode(format, bytes, l), }?; @@ -211,6 +215,29 @@ pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> { Ok(if (5..=8).contains(&o) { (h, w) } else { (w, h) }) } +/// A JPEG's frame as its header declares it, read without decoding pixels: the stored size, the +/// layout [`decode`] returns, whether [`decode`] hands the file to its whole-coefficient +/// decoder (arithmetic-coded, lossless or 12-bit frames), whose working set is several times the +/// decoded image, and the coefficients it holds beside its output when it can't decode row by row. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct JpegInfo { + pub width: u32, + pub height: u32, + pub layout: ChannelLayout, + pub whole_coefficients: bool, + /// Bytes of DCT coefficients [`decode`] holds at once beside its output when it can't turn + /// the frame into rows as it reads: an 8-bit progressive frame (SOF2), whose scans refine + /// every block in turn, or an 8-bit Huffman one (SOF0, SOF1) whose first scan lacks some of + /// its components. Every block of every component at its own sampling, 64 16-bit values + /// each; 0 for the frames it decodes a line of MCUs at a time. + pub held_coefficients: u64, +} + +/// [`JpegInfo`] of `bytes`; `None` without a readable frame of 1, 3 or 4 components. +pub fn jpeg_info(bytes: &[u8]) -> Option { + jpeg::info(bytes) +} + /// PCX's dimensions are available from its fixed-size header without decoding the RLE rows. pub fn pcx_dimensions(bytes: &[u8]) -> Option<(u32, u32)> { codecs::pcx::dimensions(bytes) @@ -433,6 +460,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result iff::encode(image, plan), Format::OpenExr => exr::encode(image, plan, opts), Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")), + Format::Jp2 => Err(CodecError::unsupported(format, "JPEG 2000 is import-only; save as PNG or TIFF instead")), Format::Jxl => jxl::encode(image, plan), Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => { via_image::encode(format, image, plan, opts) diff --git a/crates/image-codecs/src/options.rs b/crates/image-codecs/src/options.rs index 5dd0ac985..71f6030b3 100644 --- a/crates/image-codecs/src/options.rs +++ b/crates/image-codecs/src/options.rs @@ -303,6 +303,9 @@ pub struct EncodeOptions { pub jpeg_chroma_subsampling: bool, /// JPEG scan layout (baseline, baseline optimized or progressive). pub jpeg_format: JpegFormat, + /// Optional number of progressive JPEG scans (typically 3..=5). Ignored unless + /// `jpeg_format` is [`JpegFormat::Progressive`]. + pub jpeg_progressive_scans: Option, pub png_compression: PngCompression, /// Write Adam7-interlaced PNG. pub png_interlaced: bool, @@ -340,6 +343,7 @@ impl Default for EncodeOptions { jpeg_quality: 90, jpeg_chroma_subsampling: true, jpeg_format: JpegFormat::Baseline, + jpeg_progressive_scans: None, png_compression: PngCompression::Default, png_interlaced: false, png_stereo: None, diff --git a/crates/image-codecs/src/orientation.rs b/crates/image-codecs/src/orientation.rs index 2db0de75f..f77e6691f 100644 --- a/crates/image-codecs/src/orientation.rs +++ b/crates/image-codecs/src/orientation.rs @@ -1,15 +1,232 @@ -//! EXIF orientation transforms for decoded images. Byte-level EXIF/XMP inspection and edits are -//! shared with `craft-metadata`. +//! EXIF / TIFF orientation (tag 274): reading it, applying it to the pixels, +//! and rewriting it to 1 ("top-left", upright) once the pixels are upright. +//! +//! Decoders apply the orientation by default (like Photoshop and every photo +//! viewer), so a document is always edited upright. Encoders then write +//! Orientation = 1, so a viewer never rotates the already-upright pixels a +//! second time. +//! +//! Orientation values (TIFF 6.0, EXIF 2.3): 1 = upright, 2 = mirrored, 3 = +//! rotated 180°, 4 = flipped vertically, 5 = transposed, 6 = needs a 90° +//! clockwise turn, 7 = transverse, 8 = needs a 90° counter-clockwise turn. +//! Anything malformed, truncated or out of range reads as 1: an IFD0 that +//! starts inside the 8-byte header or is cut off before its next-IFD pointer, +//! or an Orientation entry that is not exactly one SHORT or LONG (the spec says +//! SHORT, but some cameras and tools write LONG). When IFD0 holds +//! several Orientation entries the first one wins (like libexif). + +use std::borrow::Cow; use crate::error::CodecError; use crate::image::Image; -use std::borrow::Cow; -pub use craft_metadata::edit::{exif_orientation, upright_exif, upright_xmp}; +/// The TIFF/EXIF Orientation tag. +const TAG_ORIENTATION: u16 = 274; +/// Field types accepted for the Orientation tag: SHORT (the spec) and LONG +/// (written by some cameras and tools). +const TYPE_SHORT: u16 = 3; +const TYPE_LONG: u16 = 4; +/// Bytes per IFD entry. +const ENTRY: usize = 12; +/// The TIFF header is 8 bytes, so no IFD can start before it. +const HEADER: usize = 8; +/// BigTIFF uses a 16-byte header, 20-byte entries, and 8-byte offsets. +const BIG_ENTRY: usize = 20; +const BIG_HEADER: usize = 16; -/// TIFF payload of an EXIF block (a JPEG-style `Exif\0\0` prefix is skipped). -pub(crate) fn tiff_body(bytes: &[u8]) -> &[u8] { - bytes.strip_prefix(b"Exif\0\0").unwrap_or(bytes) +/// Byte order of a TIFF structure. +#[derive(Clone, Copy)] +pub(crate) enum Order { + Little, + Big, +} + +impl Order { + pub(crate) fn u16(self, b: &[u8], at: usize) -> Option { + let s: [u8; 2] = b.get(at..at.checked_add(2)?)?.try_into().ok()?; + Some(match self { + Order::Little => u16::from_le_bytes(s), + Order::Big => u16::from_be_bytes(s), + }) + } + + pub(crate) fn u32(self, b: &[u8], at: usize) -> Option { + let s: [u8; 4] = b.get(at..at.checked_add(4)?)?.try_into().ok()?; + Some(match self { + Order::Little => u32::from_le_bytes(s), + Order::Big => u32::from_be_bytes(s), + }) + } + + pub(crate) fn u64(self, b: &[u8], at: usize) -> Option { + let s: [u8; 8] = b.get(at..at.checked_add(8)?)?.try_into().ok()?; + Some(match self { + Order::Little => u64::from_le_bytes(s), + Order::Big => u64::from_be_bytes(s), + }) + } +} + +/// The TIFF payload of an EXIF block (a JPEG-style `Exif\0\0` prefix is skipped). +pub(crate) fn tiff_body(b: &[u8]) -> &[u8] { + b.strip_prefix(b"Exif\0\0").unwrap_or(b) +} + +/// IFD0 of a TIFF structure: byte order, entry layout, and entry offsets. +/// +/// The full table and next-IFD pointer must be present, and IFD0 must start +/// after the corresponding TIFF or BigTIFF header. +pub(crate) fn ifd0_entries(b: &[u8]) -> Option<(Order, usize, usize, usize, bool)> { + let (order, big_tiff) = match b.get(0..4)? { + [b'I', b'I', 42, 0] => (Order::Little, false), + [b'M', b'M', 0, 42] => (Order::Big, false), + [b'I', b'I', 43, 0] => (Order::Little, true), + [b'M', b'M', 0, 43] => (Order::Big, true), + _ => return None, + }; + let (ifd, count_bytes, entry_bytes, next_ifd_bytes, header) = if big_tiff { + if order.u16(b, 4)? != 8 || order.u16(b, 6)? != 0 { + return None; + } + (usize::try_from(order.u64(b, 8)?).ok()?, 8usize, BIG_ENTRY, 8usize, BIG_HEADER) + } else { + (usize::try_from(order.u32(b, 4)?).ok()?, 2usize, ENTRY, 4usize, HEADER) + }; + if ifd < header { + return None; + } + let count = if big_tiff { usize::try_from(order.u64(b, ifd)?).ok()? } else { usize::from(order.u16(b, ifd)?) }; + let first = ifd.checked_add(count_bytes)?; + let next_ifd = first.checked_add(count.checked_mul(entry_bytes)?)?; + if next_ifd.checked_add(next_ifd_bytes)? > b.len() { + return None; + } + // In bounds: every entry ends at or before `next_ifd`. + Some((order, first, count, entry_bytes, big_tiff)) +} + +/// A well-formed Orientation entry's value: where it sits and its field type. +#[derive(Clone, Copy)] +struct Value { + at: usize, + ty: u16, +} + +impl Value { + /// The stored value (a SHORT or LONG, left-justified in the 4-byte field). + fn read(self, order: Order, b: &[u8]) -> Option { + match self.ty { + TYPE_SHORT => order.u16(b, self.at).map(u32::from), + _ => order.u32(b, self.at), + } + } + + /// 1 in this entry's own type, width and byte order. + fn one(self, order: Order) -> Vec { + match (self.ty, order) { + (TYPE_SHORT, Order::Little) => 1u16.to_le_bytes().to_vec(), + (TYPE_SHORT, Order::Big) => 1u16.to_be_bytes().to_vec(), + (_, Order::Little) => 1u32.to_le_bytes().to_vec(), + (_, Order::Big) => 1u32.to_be_bytes().to_vec(), + } + } +} + +/// The value of the entry at `e` if it is a well-formed Orientation entry: +/// exactly one SHORT or LONG. +fn orientation_value(order: Order, b: &[u8], e: usize, big_tiff: bool) -> Option { + let count = if big_tiff { order.u64(b, e.checked_add(4)?)? } else { u64::from(order.u32(b, e.checked_add(4)?)?) }; + if order.u16(b, e)? != TAG_ORIENTATION || count != 1 { + return None; + } + let ty = order.u16(b, e.checked_add(2)?)?; + let value_offset = if big_tiff { 12 } else { 8 }; + matches!(ty, TYPE_SHORT | TYPE_LONG).then_some(Value { at: e.checked_add(value_offset)?, ty }) +} + +/// Locates the Orientation value in IFD0. +/// +/// The **first** Orientation entry wins (like libexif and Photoshop); if that +/// one is malformed (count ≠ 1, or neither SHORT nor LONG) the tag is ignored, +/// even when a later duplicate is well formed. +fn find_entry(b: &[u8]) -> Option<(Order, Value)> { + let (order, first, count, entry_bytes, big_tiff) = ifd0_entries(b)?; + let e = (0..count).filter_map(|i| first.checked_add(i.checked_mul(entry_bytes)?)).find(|&e| order.u16(b, e) == Some(TAG_ORIENTATION))?; + Some((order, orientation_value(order, b, e, big_tiff)?)) +} + +/// The orientation (1–8) recorded in a TIFF-structured block: an EXIF payload +/// (with or without the `Exif\0\0` prefix) or a whole TIFF file. Missing, +/// malformed or out-of-range values give 1. +pub fn exif_orientation(exif: &[u8]) -> u16 { + let b = tiff_body(exif); + find_entry(b).and_then(|(order, v)| v.read(order, b)).and_then(|v| u16::try_from(v).ok()).filter(|v| (1..=8).contains(v)).unwrap_or(1) +} + +/// `exif` with its Orientation rewritten to 1, borrowed when there is nothing +/// to change (no well-formed tag, already 1, or unparseable). +/// +/// Only the value bytes of each well-formed Orientation entry change, written +/// as 1 in the entry's existing type and width (SHORT or LONG); every other +/// byte (other tags, their offset-based values, sub-IFDs) is kept as is. +/// Well-formed duplicates are all set to 1, so a reader that lets a later +/// duplicate win cannot rotate the upright pixels either. +pub fn upright_exif(exif: &[u8]) -> Cow<'_, [u8]> { + let body = tiff_body(exif); + let prefix = exif.len() - body.len(); + let Some((order, first, count, entry_bytes, big_tiff)) = ifd0_entries(body) else { + return Cow::Borrowed(exif); + }; + let values: Vec = (0..count) + .filter_map(|i| first.checked_add(i.checked_mul(entry_bytes)?)) + .filter_map(|e| orientation_value(order, body, e, big_tiff)) + .collect(); + if values.iter().all(|v| v.read(order, body) == Some(1)) { + return Cow::Borrowed(exif); + } + let mut out = exif.to_vec(); + for v in values { + let one = v.one(order); + let slot = prefix.checked_add(v.at).and_then(|at| out.get_mut(at..at.checked_add(one.len())?)); + if let Some(slot) = slot { + slot.copy_from_slice(&one); + } + } + Cow::Owned(out) +} + +/// `xmp` with any `tiff:Orientation` (attribute or element form) set to 1, +/// borrowed when there is nothing to change. +pub fn upright_xmp(xmp: &str) -> Cow<'_, str> { + const KEY: &str = "tiff:Orientation"; + if !xmp.contains(KEY) { + return Cow::Borrowed(xmp); + } + let mut out = String::with_capacity(xmp.len()); + let mut rest = xmp; + let mut changed = false; + while let Some(i) = rest.find(KEY) { + let (head, tail) = rest.split_at(i + KEY.len()); + out.push_str(head); + rest = tail; + // `tiff:Orientation="6"`, `tiff:Orientation='6'` or `6<`. + let open = rest.char_indices().take_while(|&(_, c)| c.is_ascii_whitespace() || matches!(c, '=' | '"' | '\'' | '>')).last(); + let Some((at, c)) = open else { continue }; + if !matches!(c, '"' | '\'' | '>') { + continue; + } + let start = at + 1; + let digits = rest.get(start..).map_or(0, |s| s.bytes().take_while(u8::is_ascii_digit).count()); + if digits == 0 || rest.get(start..start + digits) == Some("1") { + continue; + } + out.push_str(rest.get(..start).unwrap_or_default()); + out.push('1'); + rest = rest.get(start + digits..).unwrap_or_default(); + changed = true; + } + out.push_str(rest); + if changed { Cow::Owned(out) } else { Cow::Borrowed(xmp) } } /// Source pixel index for output pixel `(0, y2)` and the step per output column, for diff --git a/crates/image-codecs/src/resolution.rs b/crates/image-codecs/src/resolution.rs index 54e6759a0..6dbc9d5ee 100644 --- a/crates/image-codecs/src/resolution.rs +++ b/crates/image-codecs/src/resolution.rs @@ -1,11 +1,57 @@ -//! Shared EXIF/XMP/Photoshop resolution parsing and edits. +//! Resolution metadata edits delegated to the shared [`craft_metadata::edit`] implementation. +//! +//! Image codecs keep these wrappers so their public API and format-specific callers remain +//! stable while EXIF, XMP, and Photoshop ResolutionInfo parsing and editing live in one library. -pub use craft_metadata::edit::{ - exif_resolution, exif_with_pixel_size, exif_with_resolution, exif_with_resolution_adding_missing, export_exif, - export_exif_adding_missing_resolution, export_xmp, photoshop_resolution, resolution, xmp_resolution, xmp_with_resolution, -}; +use std::borrow::Cow; -/// Resolution used by raster decode, preferring XMP over EXIF as before. +/// The resolution (pixels per inch, horizontal and vertical) recorded in IFD0 of an EXIF block +/// or TIFF structure. +pub fn exif_resolution(exif: &[u8]) -> Option<(f32, f32)> { + craft_metadata::edit::exif_resolution(exif) +} + +/// `exif` with its IFD0 resolution set to `ppi`, borrowed when no edit is needed. +pub fn exif_with_resolution(exif: &[u8], ppi: (f32, f32)) -> Cow<'_, [u8]> { + craft_metadata::edit::exif_with_resolution(exif, ppi) +} + +/// The resolution (pixels per inch) recorded by Photoshop's ResolutionInfo image resource. +pub fn photoshop_resolution(resources: &[u8]) -> Option<(f32, f32)> { + craft_metadata::edit::photoshop_resolution(resources) +} + +/// The resolution (pixels per inch, horizontal and vertical) recorded in an XMP packet. +pub fn xmp_resolution(xmp: &str) -> Option<(f32, f32)> { + craft_metadata::edit::xmp_resolution(xmp) +} + +/// `xmp` with its resolution set to `ppi`, borrowed when no edit is needed. +pub fn xmp_with_resolution(xmp: &str, ppi: (f32, f32)) -> Cow<'_, str> { + craft_metadata::edit::xmp_with_resolution(xmp, ppi) +} + +/// The EXIF to write next to upright pixels at resolution `ppi`. +pub fn export_exif(exif: &[u8], ppi: Option<(f32, f32)>) -> Cow<'_, [u8]> { + craft_metadata::edit::export_exif(exif, ppi) +} + +/// Export EXIF, adding missing resolution entries when `ppi` is supplied. +pub(crate) fn export_exif_adding_missing_resolution(exif: &[u8], ppi: Option<(f32, f32)>) -> Cow<'_, [u8]> { + craft_metadata::edit::export_exif_adding_missing_resolution(exif, ppi) +} + +/// The XMP to write next to upright pixels at resolution `ppi`. +pub fn export_xmp(xmp: &str, ppi: Option<(f32, f32)>) -> Cow<'_, str> { + craft_metadata::edit::export_xmp(xmp, ppi) +} + +/// Resolution recorded by XMP or EXIF when a format-specific resolution field is absent. +pub fn resolution(exif: Option<&[u8]>, xmp: Option<&str>) -> Option<(f32, f32)> { + craft_metadata::edit::resolution(exif, xmp) +} + +/// Resolution a decoded file's EXIF and XMP blocks record, in precedence order. pub(crate) fn from_metadata(exif: Option<&[u8]>, xmp: Option<&str>) -> Option<(f32, f32)> { craft_metadata::edit::resolution(exif, xmp) } diff --git a/crates/image-codecs/src/web.rs b/crates/image-codecs/src/web.rs index dfd0cd9b9..098462ad7 100644 --- a/crates/image-codecs/src/web.rs +++ b/crates/image-codecs/src/web.rs @@ -286,7 +286,8 @@ pub fn decode_wbmp(bytes: &[u8]) -> Result<(u32, u32, Vec), CodecError> { /// JPEG from 8-bit RGB (`rgb.len() == 3·w·h`): quality 1..=100, optional progressive scans and /// optimised Huffman tables (Save for Web's "Optimized"), optional ICC profile, density, EXIF and -/// XMP. EXIF that doesn't fit in one segment is left out (see [`jpeg_exif_fits`]). +/// XMP. EXIF that doesn't fit in one segment is left out (see [`jpeg_exif_fits`]); XMP that +/// doesn't fit loses its layered-document properties, else is left out too (see [`jpeg_xmp_fits`]). #[allow(clippy::too_many_arguments)] pub fn encode_jpeg_rgb8( width: u32, @@ -326,11 +327,10 @@ pub fn encode_jpeg_rgb8( if let Some(seg) = exif.and_then(|x| crate::codecs::jpeg::exif_segment(x, ppi)) { enc.add_app_segment(1, &seg).map_err(e)?; } - if let Some(x) = xmp { - // Its `tiff:` resolution, if any, says what the JFIF density says (#1691). - let x = crate::resolution::export_xmp(x, ppi); - let mut seg = b"http://ns.adobe.com/xap/1.0/\0".to_vec(); - seg.extend_from_slice(x.as_bytes()); + // Its `tiff:` resolution, if any, says what the JFIF density says. A packet past one segment + // loses its layered-document properties, else is left out, as the other JPEG paths do; see + // [`jpeg_xmp_fits`]. + if let Some(seg) = xmp.and_then(|x| crate::codecs::jpeg::xmp_segment(x, ppi)) { enc.add_app_segment(1, &seg).map_err(e)?; } if let Some(icc) = icc { @@ -345,6 +345,12 @@ pub fn jpeg_exif_fits(exif: &[u8], dpi: Option) -> bool { crate::codecs::jpeg::exif_segment(exif, dpi.filter(|d| *d >= 1.0).map(|d| (d, d))).is_some() } +/// Whether [`encode_jpeg_rgb8`] writes `xmp` at `dpi`: it must fit in one APP1 segment, if need +/// be without its layered-document properties. +pub fn jpeg_xmp_fits(xmp: &str, dpi: Option) -> bool { + crate::codecs::jpeg::xmp_segment(xmp, dpi.filter(|d| *d >= 1.0).map(|d| (d, d))).is_some() +} + #[cfg(test)] mod tests { use super::*; @@ -355,6 +361,27 @@ mod tests { (w, h, img.convert(crate::ChannelLayout::Rgba, crate::SampleType::U8).data().to_vec()) } + /// XMP past one APP1 segment loses its layered-document properties, and a packet still too + /// large is left out; the JPEG is written either way. + #[test] + fn web_jpeg_oversized_xmp_is_trimmed_or_left_out() { + let rgb = vec![100u8; 8 * 8 * 3]; + let ancestors = format!( + "{}", + "id".repeat(5_000) + ); + assert!(ancestors.len() > 70_000); + assert!(jpeg_xmp_fits(&ancestors, Some(72.0)), "trimmed, it fits"); + let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), None, Some(&ancestors)).unwrap(); + let xmp = crate::decode(&out).unwrap().meta.xmp.unwrap_or_default(); + assert!(xmp.contains("dc:title=\"kept\"") && !xmp.contains("DocumentAncestors"), "{xmp}"); + let big = format!("", "x".repeat(70_000)); + assert!(!jpeg_xmp_fits(&big, Some(72.0))); + let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), None, Some(&big)).unwrap(); + let img = crate::decode(&out).unwrap(); + assert_eq!((img.dimensions(), img.meta.xmp), ((8, 8), None), "written without the XMP"); + } + fn pattern(w: usize, h: usize, n: usize) -> Vec { (0..w * h).map(|i| (((i % w) * 7 + (i / w) * 13 + (i * i) % 5) % n) as u8).collect() } diff --git a/crates/image-codecs/tests/it/deep_exr.rs b/crates/image-codecs/tests/it/deep_exr.rs index 37fe315ad..e614f865d 100644 --- a/crates/image-codecs/tests/it/deep_exr.rs +++ b/crates/image-codecs/tests/it/deep_exr.rs @@ -2,11 +2,14 @@ //! specification (NONE, RLE and ZIPS × scanline and tile), the oracle tests check the //! compositing math against hand-computed values, and malformed inputs must error, never //! panic. With the `corpus` feature, the OpenEXR project's deep test images (`corpus/exr/`, -//! pinned) are checked against the ID manifests their sidecars list. +//! each checked against its pinned SHA-256 before decoding) are checked against the ID +//! manifests their sidecars list. use craft_image_codecs::CodecError; use craft_image_codecs::f16; use craft_image_codecs::{Limits, decode, decode_deep_exr}; +use sha2::{Digest, Sha256}; +use std::io::Read as _; use std::io::Write as _; // --------------------------------------------------------------------------------------------- @@ -797,10 +800,55 @@ fn inconsistent_count_table_errors() { } // --------------------------------------------------------------------------------------------- -// Real reference files: the deep test images of the OpenEXR repository, pinned in -// `xtask/src/corpus_pins.rs` and fetched into `corpus/exr/` by `cargo xtask corpus --exr` -// (cargo feature `corpus`; `cargo xtask test-corpus`). Their `.txt` sidecars upstream list the -// ID manifest of each file, an independent oracle for the u32 ID channels. +// Real reference files: the deep test images of the OpenEXR repository at commit +// `69b2604fc76e370615438bdc8d2cd95b9349c12e`, read from `corpus/exr/` at the repo root with the +// cargo feature `corpus`. `REAL_FILE_SHA256` pins each file's SHA-256, and the test refuses a +// file that is missing, is not a regular file, is larger than `MAX_REAL_FILE_BYTES` or does not +// match its digest. The crate README says how to fill the folder. Their `.txt` sidecars upstream +// list the ID manifest of each file, an independent oracle for the u32 ID channels. + +/// The pinned files as name and lowercase hex SHA-256, the same five names as `REAL_FILES`. +const REAL_FILE_SHA256: &[(&str, &str)] = &[ + ("11.deep.exr", "800ec94ffb2085da9a730dcda2f9611f5fb62f922a3f2aef77287e36106b9667"), + ("42.deep.exr", "439907f3448480894264f0c8847f6c572f645441db34a5ad9f36f3f020d101b5"), + ("64.deep.exr", "4d9bfa646323b80630933e114a3112095488e8c008cdf908e210979638e65fe4"), + ("multivariate.deep.exr", "2335ed6052258fe693cb795f2bea57f22ba0564281691c82f2987d31d96e9e74"), + ("objectid.deep.exr", "af8940912bfa856b2650d2005462fd348656385161ccf0745b91b143e934c5f6"), +]; + +/// The largest file read from `corpus/exr/`. The largest pinned file is 611,840 bytes. +#[cfg(feature = "corpus")] +const MAX_REAL_FILE_BYTES: u64 = 4 * 1024 * 1024; + +/// The lowercase hex SHA-256 of `bytes`. +fn sha256_hex(bytes: &[u8]) -> String { + Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect() +} + +/// Reads a regular file of at most `limit` bytes. A symbolic link, a folder or a larger file is an +/// error, and a file that grows during the read is cut off at `limit + 1` bytes and refused. +fn read_bounded(path: &std::path::Path, limit: u64) -> Result, String> { + let meta = std::fs::symlink_metadata(path).map_err(|e| format!("{}: {e}", path.display()))?; + if !meta.is_file() || meta.len() > limit { + return Err(format!("{}: expected a regular file of at most {limit} bytes", path.display())); + } + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|f| f.take(limit + 1).read_to_end(&mut bytes)).map_err(|e| format!("{}: {e}", path.display()))?; + if bytes.len() as u64 > limit { + return Err(format!("{}: exceeds {limit} bytes", path.display())); + } + Ok(bytes) +} + +/// Reads `dir/name` within `limit` bytes and checks its SHA-256 against `pinned`. +fn read_pinned(dir: &std::path::Path, name: &str, pinned: &str, limit: u64) -> Result, String> { + let bytes = read_bounded(&dir.join(name), limit)?; + let got = sha256_hex(&bytes); + if got != pinned { + return Err(format!("{name}: SHA-256 {got} does not match the pinned {pinned}")); + } + Ok(bytes) +} /// One pinned file: name, total samples, most samples in one pixel, and per ID channel the /// manifest IDs its sidecar lists. @@ -846,9 +894,12 @@ const REAL_FILES: &[RealFile] = &[ #[test] fn real_deep_files_decode() { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/exr"); - for &(name, total, max_per_pixel, ids) in REAL_FILES { - let path = dir.join(name); - let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e} (run `cargo xtask corpus --exr`)", path.display())); + let decoded: Vec<&str> = REAL_FILES.iter().map(|f| f.0).collect(); + let pinned: Vec<&str> = REAL_FILE_SHA256.iter().map(|p| p.0).collect(); + assert_eq!(decoded, pinned, "REAL_FILES and REAL_FILE_SHA256 must list the same files"); + for (&(name, total, max_per_pixel, ids), &(_, sha256)) in REAL_FILES.iter().zip(REAL_FILE_SHA256) { + let bytes = read_pinned(&dir, name, sha256, MAX_REAL_FILE_BYTES) + .unwrap_or_else(|e| panic!("{}: {e}; place the pinned OpenEXR deep test images in this folder (see the crate README)", dir.display())); let deep = decode_deep_exr(&bytes, &Limits::none()).unwrap_or_else(|e| panic!("{name}: {e}")); assert_eq!((deep.width, deep.height), (256, 256), "{name}"); assert_eq!(deep.total_samples(), total, "{name}"); @@ -874,6 +925,66 @@ fn real_deep_files_decode() { } } +#[test] +fn real_file_pins_are_well_formed() { + let mut names = std::collections::BTreeSet::new(); + for &(name, sha256) in REAL_FILE_SHA256 { + assert!(name.ends_with(".deep.exr") && !name.contains(['/', '\\']), "{name}"); + assert!(names.insert(name), "{name} is pinned twice"); + assert_eq!(sha256.len(), 64, "{name}"); + assert!(sha256.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')), "{name}: {sha256}"); + } + assert_eq!(names.len(), 5); +} + +/// A folder under the system temp directory, removed when dropped. +struct ScratchDir(std::path::PathBuf); + +impl ScratchDir { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("craft-image-codecs-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create scratch dir"); + Self(dir) + } +} + +impl Drop for ScratchDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn pinned_read_refuses_a_changed_byte() { + let dir = ScratchDir::new("deep-exr-pin"); + // SHA-256 of "abc" (FIPS 180-2, appendix B.1). + let abc = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + std::fs::write(dir.0.join("a.deep.exr"), b"abc").expect("write"); + assert_eq!(read_pinned(&dir.0, "a.deep.exr", abc, 16).as_deref(), Ok(&b"abc"[..])); + + std::fs::write(dir.0.join("a.deep.exr"), b"abd").expect("write"); + let err = read_pinned(&dir.0, "a.deep.exr", abc, 16).expect_err("a changed byte must be refused"); + assert!(err.starts_with("a.deep.exr: ") && err.contains(abc) && err.contains(&sha256_hex(b"abd")), "{err}"); +} + +#[test] +fn pinned_read_refuses_missing_oversize_and_folders() { + let dir = ScratchDir::new("deep-exr-bound"); + let pin = sha256_hex(b"12345678"); + std::fs::write(dir.0.join("eight.deep.exr"), b"12345678").expect("write"); + assert!(read_pinned(&dir.0, "eight.deep.exr", &pin, 8).is_ok()); + let err = read_pinned(&dir.0, "eight.deep.exr", &pin, 7).expect_err("a file over the limit must be refused"); + assert!(err.contains("at most 7 bytes"), "{err}"); + + let err = read_pinned(&dir.0, "missing.deep.exr", &pin, 8).expect_err("a missing file must be refused"); + assert!(err.contains("missing.deep.exr"), "{err}"); + + std::fs::create_dir(dir.0.join("folder.deep.exr")).expect("mkdir"); + let err = read_pinned(&dir.0, "folder.deep.exr", &pin, 8).expect_err("a folder must be refused"); + assert!(err.contains("regular file"), "{err}"); +} + /// `gen_deep` for a cropped render: the data window sits at `(dwx, dwy)` inside a larger /// display window of `sw × sh` (the stage the renderer composed onto). Scanline chunk Y /// coordinates are absolute display rows, so they carry the data-window offset. diff --git a/crates/image-codecs/tests/it/png_jpeg.rs b/crates/image-codecs/tests/it/png_jpeg.rs index 0c7bc03d4..6b213ea83 100644 --- a/crates/image-codecs/tests/it/png_jpeg.rs +++ b/crates/image-codecs/tests/it/png_jpeg.rs @@ -115,6 +115,26 @@ fn jpeg_cmyk_roundtrip_with_adobe_marker() { assert!(psnr(&img, &back) > 35.0, "{}", psnr(&img, &back)); } +#[test] +fn jpeg_cmyk_without_adobe_marker_keeps_samples_as_inks() { + let img = Image::from_u8(16, 16, ChannelLayout::Cmyk, [10u8, 100, 200, 50].repeat(256)).unwrap(); + let marked = encode(&img, Format::Jpeg, &EncodeOptions { jpeg_quality: 95, ..Default::default() }).unwrap(); + let signature = b"\xFF\xEE\x00\x0EAdobe"; + let start = marked.windows(signature.len()).position(|part| part == signature).expect("Adobe APP14 marker"); + // APP14's two marker bytes and two-byte length precede its 12-byte payload. + let mut unmarked = Vec::with_capacity(marked.len() - 16); + unmarked.extend_from_slice(&marked[..start]); + unmarked.extend_from_slice(&marked[start + 16..]); + + let adobe_pixels = decode(&marked).unwrap().data().to_vec(); + let unmarked_pixels = decode(&unmarked).unwrap().data().to_vec(); + for (adobe, raw) in adobe_pixels.as_chunks::<4>().0.iter().zip(unmarked_pixels.as_chunks::<4>().0) { + for (&ink, &stored) in adobe.iter().zip(raw) { + assert_eq!(stored, 255 - ink, "unmarked CMYK samples are direct inks"); + } + } +} + #[test] fn jpeg_ycck_decodes_to_cmyk() { let img = synth(40, 32, ChannelLayout::Cmyk, SampleType::U8, 4, 0.02); diff --git a/crates/image-codecs/tests/it/tiff_pages.rs b/crates/image-codecs/tests/it/tiff_pages.rs index 0e589786f..b94509598 100644 --- a/crates/image-codecs/tests/it/tiff_pages.rs +++ b/crates/image-codecs/tests/it/tiff_pages.rs @@ -382,6 +382,21 @@ fn associated_alpha_is_made_straight() { assert_eq!(img.to_u16_samples().unwrap(), [32768, 32768]); } +#[test] +fn ink_set_and_extra_samples_are_listed() { + let px = [10u8, 20, 30, 40, 17, 128]; + let d = strips(1, 1, 8, 6, 5, 1, &px).tag(332, SHORT, &[2]).tag(338, SHORT, &[0, 1]); + let info = tiff_info(&build(true, false, &[d], &[0]).bytes).unwrap(); + use ExtraSampleKind::*; + assert_eq!((info.pages[0].ink_set, &info.pages[0].extra_samples[..]), (Some(InkSet::InkNames), &[Unspecified, AssociatedAlpha][..])); + let d = strips(1, 1, 8, 6, 5, 1, &px).tag(332, SHORT, &[7]).tag(338, SHORT, &[2, 5]); + let info = tiff_info(&build(true, false, &[d], &[0]).bytes).unwrap(); + assert_eq!((info.pages[0].ink_set, &info.pages[0].extra_samples[..]), (Some(InkSet::Invalid(7)), &[UnassociatedAlpha, Invalid(5)][..])); + let d = strips(1, 1, 8, 4, 5, 1, &px[..4]); + let info = tiff_info(&build(true, false, &[d], &[0]).bytes).unwrap(); + assert_eq!((info.pages[0].ink_set, &info.pages[0].extra_samples[..]), (None, &[][..])); +} + #[test] fn white_is_zero_opens_with_the_right_tones() { // #691: 00 FF 00 in a WhiteIsZero file is white, black, white. diff --git a/crates/jpeg/Cargo.toml b/crates/jpeg/Cargo.toml index afdae2fdb..fba86444d 100644 --- a/crates/jpeg/Cargo.toml +++ b/crates/jpeg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-jpeg" -description = "Clean-room JPEG decoder (ITU-T T.81): 12-bit and arithmetic-coded frames, and baseline frames a band of rows at a time." +description = "Clean-room JPEG decoder and 8-bit optimized baseline encoder (ITU-T T.81)." version.workspace = true edition.workspace = true license.workspace = true @@ -12,8 +12,14 @@ workspace = true [dependencies] thiserror = { workspace = true } +rayon = { workspace = true, optional = true } [dev-dependencies] # Reference encoder and baseline decoder for the comparison tests. jpeg-encoder = "0.6" zune-jpeg = "0.5" +jpeg-decoder = "0.3" + +[features] +default = [] +parallel = ["dep:rayon"] diff --git a/crates/jpeg/README.md b/crates/jpeg/README.md index 6b04cc8ea..3b72ebd06 100644 --- a/crates/jpeg/README.md +++ b/crates/jpeg/README.md @@ -1,11 +1,14 @@ # craft-jpeg -A clean-room JPEG decoder for the Craft apps, written from ITU-T T.81 (ISO/IEC 10918-1). It -covers the processes that common Rust JPEG decoders skip: 12-bit samples and arithmetic coding. -It also decodes the common sequential 8-bit files a band of rows at a time ([`Bands`](#decoding-in-bands)), -for images too large to decode into one buffer. -No `unsafe`, no panics on malformed input, and it builds for `wasm32-unknown-unknown`. The only -dependency is `thiserror`. +A clean-room JPEG decoder and 8-bit baseline encoder for the Craft apps, written from ITU-T T.81 +(ISO/IEC 10918-1). The decoder covers processes that common Rust JPEG decoders skip: 12-bit +samples and arithmetic coding. It also decodes the common sequential 8-bit files a band of rows +at a time ([`Bands`](#decoding-in-bands)), for images too large to decode into one buffer. The +baseline encoder writes per-image optimized Huffman tables and supports grayscale and YCbCr 4:4:4, +4:2:2 and 4:2:0. + +No `unsafe`, no panics on malformed input, and it builds for `wasm32-unknown-unknown`. The required +dependency is `thiserror`; the optional `parallel` feature adds Rayon for multi-core encoding. ```toml craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "" } @@ -99,6 +102,24 @@ fn use_craft_jpeg(bytes: &[u8]) -> bool { SOF11 (lossless) falls in that range and returns `Unsupported`. +## Baseline encoding + +`encode_baseline(data, width, height, channels, quality, subsampling, app_segments)` writes an +interleaved 8-bit baseline JPEG with optimized Huffman tables. `channels` is 1 (gray), 3 (RGB), or +4 (RGBA; alpha is ignored). Dimensions must be in `1..=65535`, quality is clamped to `1..=100`, +and a short sample buffer is rejected. APP segments must use markers `0xE0..=0xEF` and payloads +no larger than 65533 bytes. Invalid input returns `EncodeError::InvalidInput` instead of an empty +or malformed JPEG. + +```rust +use craft_jpeg::{ChromaSubsampling, encode_baseline}; + +let jpeg = encode_baseline(&rgb, width, height, 3, 90, ChromaSubsampling::S420, &[])?; +``` + +Enable the `parallel` Cargo feature to encode restart-interval bands concurrently. The output is +byte-stable across sequential and parallel execution. + ## Decoding in bands `Bands` decodes a sequential Huffman-coded (SOF0, SOF1) 8-bit file whose first scan holds every @@ -141,10 +162,11 @@ if reader.damaged() { /* warn: part of the image is missing */ } ## Boundaries -- In scope: decoding the frames above into samples. -- Out of scope: metadata. The decoder skips every APPn and COM segment. ICC profiles, EXIF, - XMP, Photoshop resources, resolution and the APP14 `Adobe` segment are the app's to read. - Color management and encoding also stay in the apps. +- In scope: decoding the frames above into samples and encoding 8-bit baseline JPEG. +- Out of scope: metadata interpretation. The decoder skips every APPn and COM segment. ICC + profiles, EXIF, XMP, Photoshop resources, resolution and the APP14 `Adobe` segment are the + caller's to read; the encoder accepts caller-constructed APP segments. Color management stays + with each app. ## Testing @@ -152,6 +174,9 @@ if reader.damaged() { /* warn: part of the image is missing */ } - unit tests in `src/tests.rs`: arithmetic-coded streams from a test-only encoder must decode to the coefficients that went in, and Huffman streams are compared against `zune-jpeg`. +- unit tests in `src/encode.rs`: optimized table validity and file-size reduction, independent + `jpeg-decoder` and `zune-jpeg` decoding, 4:4:4/4:2:2/4:2:0 frame-header sampling, invalid input, + and pinned output hashes for grayscale, RGB, RGBA and the existing 4:2:0 path. - `tests/conformance.rs`, on libjpeg-turbo's test images in `tests/data` (provenance and how the derived files were made: `tests/data/SOURCE.md`): - `testimgari.jpg` (SOF9) decodes to exactly the samples of its jpegtran Huffman transcode. diff --git a/crates/jpeg/src/encode.rs b/crates/jpeg/src/encode.rs new file mode 100644 index 000000000..548f4c9f9 --- /dev/null +++ b/crates/jpeg/src/encode.rs @@ -0,0 +1,879 @@ +//! Parallel baseline JPEG encoder (ITU-T T.81 / JFIF). +//! +//! The image is cut into bands of MCU rows separated by restart markers (`DRI` + `RSTn`): DC +//! prediction restarts at every marker, so bands are entropy-coded independently on all cores and +//! concatenated. Quantization uses the example tables of T.81 Annex K scaled by the usual 1–100 +//! quality convention. Huffman tables are made for each image from its own symbol counts (T.81 +//! Annex K.2): a first pass over the bands counts the symbols, a second codes them. The file stays +//! interleaved baseline with the tables in its `DHT` segments, readable by every decoder, and is +//! smaller than with the Annex K example tables at the same pixels. Supports grayscale and YCbCr +//! 4:4:4, 4:2:2, and 4:2:0. + +/// Chroma sampling for baseline JPEG encoding. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ChromaSubsampling { + /// Full resolution chroma. + #[default] + S444, + /// Half horizontal resolution chroma. + S422, + /// Half horizontal and vertical resolution chroma. + S420, +} + +/// Why a baseline JPEG could not be encoded. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum EncodeError { + /// Invalid dimensions, channel count, or source buffer length. + #[error("invalid JPEG input: {0}")] + InvalidInput(String), +} + +/// T.81 Annex K.1 / K.2 example quantization tables (natural order). +const Q_LUMA: [u16; 64] = [ + 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, + 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99, +]; +const Q_CHROMA: [u16; 64] = [ + 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, +]; + +/// Zig-zag position k → natural index. +const ZIGZAG: [usize; 64] = [ + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, + 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +]; + +/// T.81 Annex K.3 example Huffman tables: (code counts per length 1..16, symbols). +const DC_LUMA_BITS: [u8; 16] = [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; +const DC_CHROMA_BITS: [u8; 16] = [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; +const DC_VALS: [u8; 12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; +const AC_LUMA_BITS: [u8; 16] = [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d]; +const AC_LUMA_VALS: [u8; 162] = [ + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, + 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, + 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, +]; +const AC_CHROMA_BITS: [u8; 16] = [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77]; +const AC_CHROMA_VALS: [u8; 162] = [ + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, + 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, + 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, +]; + +/// Huffman code table: symbol → (code, length). +struct Huff { + code: [(u16, u8); 256], +} + +impl Huff { + /// Canonical codes from counts (T.81 Annex C). + fn new(bits: &[u8; 16], vals: &[u8]) -> Huff { + let mut code = [(0u16, 0u8); 256]; + let (mut c, mut k) = (0u16, 0usize); + for (len, &n) in bits.iter().enumerate() { + for _ in 0..n { + if let Some(&v) = vals.get(k) { + code[v as usize] = (c, len as u8 + 1); + } + c = c.wrapping_add(1); + k += 1; + } + c = c.wrapping_shl(1); + } + Huff { code } + } +} + +/// Symbol counts of one Huffman table: index = symbol (DC size category, or AC run/size byte). +type Freq = [u64; 256]; + +/// The code lengths (`BITS`, counts per length 1..16) and symbols (`HUFFVAL`) of an optimal +/// Huffman table for `freq`, limited to 16-bit codes and never assigning the all-ones code +/// (T.81 Annex K.2, figures K.1–K.4). Symbols with a zero count get no code. At least one symbol +/// is always present (a table nothing used gets symbol 0), so the result is a valid `DHT`. +fn optimal_table(freq: &Freq) -> ([u8; 16], Vec) { + // 256 is the reserved pseudo-symbol: counted once, it takes the longest code, which is + // then dropped so no real code is all ones (K.2) + let mut f = [0u64; 257]; + f[..256].copy_from_slice(freq); + if f[..256].iter().all(|&c| c == 0) { + f[0] = 1; + } + f[256] = 1; + let mut size = [0usize; 257]; + let mut next: [Option; 257] = [None; 257]; + loop { + // the two smallest non-zero counts; on equal counts the larger symbol goes first (K.1) + let mut c1: Option = None; + for i in 0..257 { + if f[i] > 0 && c1.is_none_or(|c| f[i] <= f[c]) { + c1 = Some(i); + } + } + let Some(c1) = c1 else { break }; + let mut c2: Option = None; + for i in 0..257 { + if i != c1 && f[i] > 0 && c2.is_none_or(|c| f[i] <= f[c]) { + c2 = Some(i); + } + } + let Some(c2) = c2 else { break }; + f[c1] = f[c1].saturating_add(f[c2]); + f[c2] = 0; + // every symbol in both trees goes one level deeper; c2's chain is appended to c1's + let mut k = c1; + size[k] += 1; + while let Some(n) = next[k] { + k = n; + size[k] += 1; + } + next[k] = Some(c2); + let mut k = c2; + size[k] += 1; + while let Some(n) = next[k] { + k = n; + size[k] += 1; + } + } + // counts per code length; 257 symbols need at most 256 levels + let mut bits = [0usize; 257]; + for &s in &size { + if s > 0 { + bits[s.min(256)] += 1; + } + } + // limit to 16 bits (K.3): move pairs of the longest codes up, one level at a time (the + // deepest level of a full tree always holds an even number of codes) + for i in (17..257).rev() { + while bits[i] >= 2 { + let Some(j) = (1..i - 1).rev().find(|&j| bits[j] > 0) else { break }; + bits[i] -= 2; + bits[i - 1] += 1; + bits[j + 1] += 2; + bits[j] -= 1; + } + } + // drop the reserved symbol's code: it is one of the longest + if let Some(i) = (1..=16).rev().find(|&i| bits[i] > 0) { + bits[i] -= 1; + } + // symbols by code length, then by value (K.4); the reserved symbol is not listed + let mut vals = Vec::new(); + for len in 1..257 { + vals.extend((0..256).filter(|&s| size[s] == len).map(|s| s as u8)); + } + let mut out = [0u8; 16]; + for (o, &b) in out.iter_mut().zip(&bits[1..=16]) { + *o = b.min(255) as u8; + } + (out, vals) +} + +fn scaled_quant(base: &[u16; 64], quality: u8) -> [u16; 64] { + let q = quality.clamp(1, 100) as u32; + let scale = if q < 50 { 5000 / q } else { 200 - 2 * q }; + base.map(|b| ((b as u32 * scale + 50) / 100).clamp(1, 255) as u16) +} + +/// Entropy-coded segment writer with 0xFF byte stuffing. +struct Bits { + out: Vec, + acc: u32, + n: u32, +} + +impl Bits { + fn new() -> Bits { + Bits { out: Vec::new(), acc: 0, n: 0 } + } + #[inline] + fn put(&mut self, code: u32, len: u32) { + if len == 0 { + return; + } + self.acc = (self.acc << len) | (code & ((1 << len) - 1)); + self.n += len; + while self.n >= 8 { + let b = (self.acc >> (self.n - 8)) as u8; + self.out.push(b); + if b == 0xFF { + self.out.push(0); + } + self.n -= 8; + } + self.acc &= (1 << self.n) - 1; + } + /// Pad with 1-bits to a byte boundary. + fn finish(mut self) -> Vec { + if self.n > 0 { + let pad = 8 - self.n; + self.put((1 << pad) - 1, pad); + } + self.out + } +} + +/// AAN output scale factors: `s[0] = 1`, `s[k] = cos(kπ/16)·√2`. +fn aan_scale() -> [f32; 8] { + std::array::from_fn(|k| if k == 0 { 1.0 } else { ((k as f64 * std::f64::consts::PI / 16.0).cos() * std::f64::consts::SQRT_2) as f32 }) +} + +/// Quantization reciprocals with the AAN scaling folded in: coefficient = out / (8·s[u]·s[v]·q). +fn recip_table(q: &[u16; 64]) -> [f32; 64] { + let s = aan_scale(); + std::array::from_fn(|i| 1.0 / (q[i] as f32 * s[i / 8] * s[i % 8] * 8.0)) +} + +/// One 8-point forward DCT (Arai–Agui–Nakajima flowgraph, 5 multiplies) on `d[o + k·stride]`. +#[inline(always)] +fn aan_1d(d: &mut [f32; 64], o: usize, stride: usize) { + let g = |k: usize| o + k * stride; + let (t0, t7) = (d[g(0)] + d[g(7)], d[g(0)] - d[g(7)]); + let (t1, t6) = (d[g(1)] + d[g(6)], d[g(1)] - d[g(6)]); + let (t2, t5) = (d[g(2)] + d[g(5)], d[g(2)] - d[g(5)]); + let (t3, t4) = (d[g(3)] + d[g(4)], d[g(3)] - d[g(4)]); + // even part + let (t10, t13, t11, t12) = (t0 + t3, t0 - t3, t1 + t2, t1 - t2); + d[g(0)] = t10 + t11; + d[g(4)] = t10 - t11; + let z1 = (t12 + t13) * 0.707_106_77; + d[g(2)] = t13 + z1; + d[g(6)] = t13 - z1; + // odd part + let (t10, t11, t12) = (t4 + t5, t5 + t6, t6 + t7); + let z5 = (t10 - t12) * 0.382_683_43; + let z2 = 0.541_196_1 * t10 + z5; + let z4 = 1.306_563 * t12 + z5; + let z3 = t11 * 0.707_106_77; + let (z11, z13) = (t7 + z3, t7 - z3); + d[g(5)] = z13 + z2; + d[g(3)] = z13 - z2; + d[g(1)] = z11 + z4; + d[g(7)] = z11 - z4; +} + +/// Forward DCT of a level-shifted 8×8 block and quantization. +#[inline] +fn fdct_quant(block: &[f32; 64], recip: &[f32; 64], out: &mut [i16; 64]) { + let mut d = *block; + for r in 0..8 { + aan_1d(&mut d, r * 8, 1); + } + for c in 0..8 { + aan_1d(&mut d, c, 8); + } + for i in 0..64 { + out[i] = round_i16(d[i] * recip[i]); + } +} +/// `x.round() as i16` (half away from zero, saturating, NaN to 0) for every `x` (checked for all of them), in plain +/// arithmetic: without SSE4.1 `f32::round` is a libm call, one per coefficient, that keeps the loop from vectorising. +#[inline(always)] +fn round_i16(x: f32) -> i16 { + // (below 2^24 the truncation is exact and so is the remainder) + let c = x.clamp(-65536.0, 65536.0); + let t = c as i32; + let f = c - t as f32; + let r = t + i32::from(f >= 0.5) - i32::from(f <= -0.5); + r.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16 +} + +#[inline] +fn magnitude(v: i32) -> (u32, u32) { + let a = v.unsigned_abs(); + let size = 32 - a.leading_zeros(); + let bits = if v < 0 { (v - 1) as u32 } else { v as u32 }; + (size, bits & ((1u32 << size) - 1)) +} + +/// The Huffman symbols of one quantized block in coding order: `sym(ac, symbol, bits, n)` for the +/// DC size category (`ac` false) and each AC run/size, ZRL and EOB (`ac` true), each followed by +/// its `n` extra bits `bits`. +#[inline(always)] +fn block_symbols(q: &[i16; 64], pred: &mut i32, mut sym: impl FnMut(bool, usize, u32, u32)) { + let d = q[0] as i32 - *pred; + *pred = q[0] as i32; + let (s, b) = magnitude(d); + sym(false, s as usize, b, s); + let mut run = 0u32; + for &zi in &ZIGZAG[1..] { + let v = q[zi] as i32; + if v == 0 { + run += 1; + continue; + } + while run >= 16 { + sym(true, 0xF0, 0, 0); + run -= 16; + } + let (s, b) = magnitude(v); + sym(true, ((run << 4) | s) as usize, b, s); + run = 0; + } + if run > 0 { + sym(true, 0x00, 0, 0); + } +} + +/// One coded symbol of the entropy-coded data: bits 0–7 the symbol, 8–9 its table (0 DC luma, +/// 1 AC luma, 2 DC chroma, 3 AC chroma), 10–13 the number of extra bits, 14–29 those bits (a +/// baseline coefficient needs at most 11). +type Token = u32; + +/// Append one block's symbols to `out` and count them in `freq` (by table, as in [`Token`]). +fn tokenize_block(q: &[i16; 64], pred: &mut i32, chroma: bool, out: &mut Vec, freq: &mut [Freq; 4]) { + let base = if chroma { 2 } else { 0 }; + block_symbols(q, pred, |is_ac, s, bits, n| { + let table = base + is_ac as usize; + freq[table][s & 0xFF] += 1; + out.push((s as u32 & 0xFF) | (table as u32) << 8 | (n & 0xF) << 10 | (bits & 0xFFFF) << 14); + }); +} + +/// Code a band's symbols with `tables` (indexed as in [`Token`]). +fn write_tokens(tokens: &[Token], tables: &[Huff; 4]) -> Vec { + let mut w = Bits::new(); + for &t in tokens { + let (s, table, n, bits) = (t & 0xFF, (t >> 8) & 3, (t >> 10) & 0xF, t >> 14); + let (c, l) = tables[table as usize].code[s as usize]; + w.put(c as u32, l as u32); + w.put(bits, n); + } + w.finish() +} + +/// Planar component samples (level-shifted to −128..127) with edge replication on read. +struct Plane { + w: usize, + h: usize, + data: Vec, +} + +impl Plane { + #[inline] + fn block(&self, bx: usize, by: usize, out: &mut [f32; 64]) { + let (x0, y0) = (bx * 8, by * 8); + if x0 + 8 <= self.w && y0 + 8 <= self.h { + for y in 0..8 { + let i = (y0 + y) * self.w + x0; + out[y * 8..y * 8 + 8].copy_from_slice(&self.data[i..i + 8]); + } + return; + } + for y in 0..8 { + let sy = (by * 8 + y).min(self.h - 1); + let row = &self.data[sy * self.w..(sy + 1) * self.w]; + for x in 0..8 { + out[y * 8 + x] = row[(bx * 8 + x).min(self.w - 1)]; + } + } + } +} + +fn segment(out: &mut Vec, marker: u8, payload: &[u8]) { + out.extend_from_slice(&[0xFF, marker]); + out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes()); + out.extend_from_slice(payload); +} + +fn dht(out: &mut Vec, class_id: u8, bits: &[u8; 16], vals: &[u8]) { + let mut p = vec![class_id]; + p.extend_from_slice(bits); + p.extend_from_slice(vals); + segment(out, 0xC4, &p); +} + +/// Encode interleaved 8-bit samples (`channels` 1, 3 or 4; alpha is dropped), with Huffman +/// tables made for the image. +pub fn encode( + data: &[u8], + width: usize, + height: usize, + channels: usize, + quality: u8, + sub: ChromaSubsampling, + app_segments: &[(u8, Vec)], +) -> Vec { + encode_with(data, width, height, channels, quality, sub, app_segments, true) +} + +/// Encode an 8-bit grayscale, RGB, or RGBA image as an interleaved baseline JPEG with per-image +/// optimized Huffman tables. Alpha is ignored. Metadata APP segments are supplied as `(marker, +/// payload)` pairs. +pub fn encode_baseline( + data: &[u8], + width: usize, + height: usize, + channels: usize, + quality: u8, + sub: ChromaSubsampling, + app_segments: &[(u8, Vec)], +) -> Result, EncodeError> { + let fits = width.checked_mul(height).and_then(|n| n.checked_mul(channels)).is_some_and(|n| n <= data.len()); + if !fits || width == 0 || height == 0 || width > 65_535 || height > 65_535 || !matches!(channels, 1 | 3 | 4) { + return Err(EncodeError::InvalidInput(format!("{width}x{height}, {channels} channels, {} bytes", data.len()))); + } + if app_segments.iter().any(|(marker, payload)| !(0xE0..=0xEF).contains(marker) || payload.len() > 65_533) { + return Err(EncodeError::InvalidInput("APP markers must be 0xE0..=0xEF with payloads no larger than 65533 bytes".into())); + } + Ok(encode(data, width, height, channels, quality, sub, app_segments)) +} + +/// [`encode`], with optimized Huffman tables or (`optimize` false) the Annex K example tables. +#[allow(clippy::too_many_arguments)] +fn encode_with( + data: &[u8], + width: usize, + height: usize, + channels: usize, + quality: u8, + sub: ChromaSubsampling, + app_segments: &[(u8, Vec)], + optimize: bool, +) -> Vec { + // The public entry takes caller-sized dimensions: refuse (an empty output) what would size an allocation from + // them or index past `data`, rather than panic or allocate for them. + let fits = width.checked_mul(height).and_then(|n| n.checked_mul(channels)).is_some_and(|n| n <= data.len()); + if !fits || width == 0 || height == 0 || width > 65_535 || height > 65_535 || !matches!(channels, 1 | 3 | 4) { + return Vec::new(); + } + let gray = channels == 1; + let (hs, vs) = match (gray, sub) { + (true, _) | (false, ChromaSubsampling::S444) => (1usize, 1usize), + (false, ChromaSubsampling::S422) => (2, 1), + (false, ChromaSubsampling::S420) => (2, 2), + }; + #[cfg(feature = "parallel")] + use rayon::prelude::*; + // colour conversion (JFIF YCbCr, full range, level-shifted) of the pixel rows `rows`, one band's worth at a + // time (in the band's task: the planes of the whole image would be ~290 MB at 24 MP, written and read back + // once): 4:4:4 Y, Cb, Cr at full resolution in one pass; 4:2:0 Y, and chroma (rows `crows` of the + // half-size planes) straight from 2×2 RGB means (conversion is linear: average first, then convert once) + let ncomp = if gray || hs == 2 { 1 } else { 3 }; + let (cw, ch) = (width.div_ceil(hs), height.div_ceil(vs)); + let convert = |rows: std::ops::Range, crows: std::ops::Range| -> Vec { + let mut full: Vec> = (0..ncomp).map(|_| vec![0f32; rows.len() * width]).collect(); + for (k, y) in rows.clone().enumerate() { + let src = &data[y * width * channels..(y + 1) * width * channels]; + let mut out: Vec<&mut [f32]> = full.iter_mut().map(|p| &mut p[k * width..(k + 1) * width]).collect(); + if gray { + for (o, p) in out[0].iter_mut().zip(src.chunks_exact(channels)) { + *o = p[0] as f32 - 128.0; + } + continue; + } + if out.len() == 1 { + for (o, p) in out[0].iter_mut().zip(src.chunks_exact(channels)) { + *o = 0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32 - 128.0; + } + continue; + } + for (x, p) in src.chunks_exact(channels).enumerate() { + let (r, g, b) = (p[0] as f32, p[1] as f32, p[2] as f32); + out[0][x] = 0.299 * r + 0.587 * g + 0.114 * b - 128.0; + out[1][x] = -0.168_736 * r - 0.331_264 * g + 0.5 * b; + out[2][x] = 0.5 * r - 0.418_688 * g - 0.081_312 * b; + } + } + let mut planes: Vec = full.into_iter().map(|data| Plane { w: width, h: rows.len(), data }).collect(); + if !gray && hs == 2 { + let (mut cb, mut cr) = (vec![0f32; cw * crows.len()], vec![0f32; cw * crows.len()]); + for (cy, (ob, or)) in crows.clone().zip(cb.chunks_mut(cw).zip(cr.chunks_mut(cw))) { + for cx in 0..cw { + let s = |k: usize| { + let mut sum = 0.0; + for dy in 0..vs { + for dx in 0..hs { + let y = (cy * vs + dy).min(height - 1); + let x = (cx * hs + dx).min(width - 1); + sum += data[(y * width + x) * channels + k] as f32; + } + } + sum / (hs * vs) as f32 + }; + let (r, g, b) = (s(0), s(1), s(2)); + ob[cx] = -0.168_736 * r - 0.331_264 * g + 0.5 * b; + or[cx] = 0.5 * r - 0.418_688 * g - 0.081_312 * b; + } + } + planes.push(Plane { w: cw, h: crows.len(), data: cb }); + planes.push(Plane { w: cw, h: crows.len(), data: cr }); + } + planes + }; + + let ql = scaled_quant(&Q_LUMA, quality); + let qc = scaled_quant(&Q_CHROMA, quality); + let (rl, rc) = (recip_table(&ql), recip_table(&qc)); + let (mcu_w, mcu_h) = (8 * hs, 8 * vs); + let (mx, my) = (width.div_ceil(mcu_w), height.div_ceil(mcu_h)); + // restart interval: whole MCU rows per band, ≤ 65535 MCUs, enough bands to keep all cores busy + let rows_per_band = (my / 64).clamp(1, (65_535 / mx.max(1)).max(1)); + let bands: Vec = (0..my.div_ceil(rows_per_band)).collect(); + // first pass: each band's quantized blocks as symbols, with their counts per table (DC + // prediction restarts per band, as the restart markers say) + let tokenize_band = |band: &usize| -> (Vec, [Freq; 4]) { + let (mut blk, mut q) = ([0f32; 64], [0i16; 64]); + let (mut tokens, mut freq) = (Vec::new(), [[0u64; 256]; 4]); + let mut pred = [0i32; 3]; + let (m0, m1) = (band * rows_per_band, ((band + 1) * rows_per_band).min(my)); + // the band's planes, its MCU row `m0` at their top (blocks past the image's bottom repeat its last row, + // which is the band's last row then) + let planes = convert(m0 * mcu_h..(m1 * mcu_h).min(height), m0 * 8..(m1 * 8).min(ch)); + for mcu_y in m0..m1 { + let mcu_y = mcu_y - m0; + for mcu_x in 0..mx { + for vy in 0..vs { + for hx in 0..hs { + planes[0].block(mcu_x * hs + hx, mcu_y * vs + vy, &mut blk); + fdct_quant(&blk, &rl, &mut q); + tokenize_block(&q, &mut pred[0], false, &mut tokens, &mut freq); + } + } + if !gray { + for (plane, pred) in planes.iter().zip(pred.iter_mut()).take(3).skip(1) { + plane.block(mcu_x, mcu_y, &mut blk); + fdct_quant(&blk, &rc, &mut q); + tokenize_block(&q, pred, true, &mut tokens, &mut freq); + } + } + } + } + (tokens, freq) + }; + #[cfg(feature = "parallel")] + let tokenized: Vec<(Vec, [Freq; 4])> = bands.par_iter().map(tokenize_band).collect(); + #[cfg(not(feature = "parallel"))] + let tokenized: Vec<(Vec, [Freq; 4])> = bands.iter().map(tokenize_band).collect(); + // the tables: DC luma, AC luma, DC chroma, AC chroma + let tables: [([u8; 16], Vec); 4] = if optimize { + let mut total = [[0u64; 256]; 4]; + for (_, f) in &tokenized { + for (t, f) in total.iter_mut().zip(f) { + for (t, f) in t.iter_mut().zip(f) { + *t = t.saturating_add(*f); + } + } + } + total.each_ref().map(optimal_table) + } else { + [ + (DC_LUMA_BITS, DC_VALS.to_vec()), + (AC_LUMA_BITS, AC_LUMA_VALS.to_vec()), + (DC_CHROMA_BITS, DC_VALS.to_vec()), + (AC_CHROMA_BITS, AC_CHROMA_VALS.to_vec()), + ] + }; + let huff = tables.each_ref().map(|(bits, vals)| Huff::new(bits, vals)); + // second pass: code the symbols + #[cfg(feature = "parallel")] + let coded: Vec> = tokenized.into_par_iter().map(|(t, _)| write_tokens(&t, &huff)).collect(); + #[cfg(not(feature = "parallel"))] + let coded: Vec> = tokenized.into_iter().map(|(t, _)| write_tokens(&t, &huff)).collect(); + + // headers + let mut out = Vec::with_capacity(coded.iter().map(Vec::len).sum::() + 4096); + out.extend_from_slice(&[0xFF, 0xD8]); + // JFIF APP0 first (callers may pass their own, e.g. with a print density) + if !app_segments.iter().any(|(m, _)| *m == 0xE0) { + segment(&mut out, 0xE0, &[b'J', b'F', b'I', b'F', 0, 1, 2, 0, 0, 1, 0, 1, 0, 0]); + } + for (marker, payload) in app_segments { + segment(&mut out, *marker, payload); + } + let dqt = |id: u8, q: &[u16; 64]| -> Vec { + let mut p = vec![id]; + p.extend(ZIGZAG.iter().map(|&i| q[i] as u8)); + p + }; + segment(&mut out, 0xDB, &dqt(0, &ql)); + if !gray { + segment(&mut out, 0xDB, &dqt(1, &qc)); + } + let mut sof = vec![8]; + sof.extend_from_slice(&(height as u16).to_be_bytes()); + sof.extend_from_slice(&(width as u16).to_be_bytes()); + if gray { + sof.extend_from_slice(&[1, 1, 0x11, 0]); + } else { + sof.extend_from_slice(&[3, 1, ((hs as u8) << 4) | vs as u8, 0, 2, 0x11, 1, 3, 0x11, 1]); + } + segment(&mut out, 0xC0, &sof); + let [(dlb, dlv), (alb, alv), (dcb, dcv), (acb, acv)] = &tables; + dht(&mut out, 0x00, dlb, dlv); + dht(&mut out, 0x10, alb, alv); + if !gray { + dht(&mut out, 0x01, dcb, dcv); + dht(&mut out, 0x11, acb, acv); + } + let interval = (rows_per_band * mx) as u16; + if coded.len() > 1 { + segment(&mut out, 0xDD, &interval.to_be_bytes()); + } + if gray { + segment(&mut out, 0xDA, &[1, 1, 0x00, 0, 63, 0]); + } else { + segment(&mut out, 0xDA, &[3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 63, 0]); + } + let last = coded.len().saturating_sub(1); + for (i, c) in coded.iter().enumerate() { + out.extend_from_slice(c); + if i < last { + out.extend_from_slice(&[0xFF, 0xD0 + (i % 8) as u8]); + } + } + out.extend_from_slice(&[0xFF, 0xD9]); + out +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + + #[test] + fn hostile_dimensions_give_no_output_instead_of_a_panic_or_allocation() { + for (w, h, c) in [(1usize << 40, 1usize << 40, 3usize), (0, 8, 3), (70_000, 2, 3), (8, 8, 7), (8, 8, 3)] { + assert!(encode(&[0u8; 16], w, h, c, 90, ChromaSubsampling::S444, &[]).is_empty(), "{w} x {h} x {c}"); + } + } + + #[test] + fn checked_entry_point_reports_invalid_input() { + assert!(matches!(encode_baseline(&[0; 16], 8, 8, 3, 90, ChromaSubsampling::S444, &[]), Err(EncodeError::InvalidInput(_)))); + assert!(matches!( + encode_baseline(&[0; 192], 8, 8, 3, 90, ChromaSubsampling::S422, &[]), + Ok(bytes) if bytes.starts_with(&[0xFF, 0xD8]) + )); + let too_large_app = [(0xE1, vec![0; 65_534])]; + assert!(matches!(encode_baseline(&[0; 192], 8, 8, 3, 90, ChromaSubsampling::S444, &too_large_app), Err(EncodeError::InvalidInput(_)))); + } + + #[test] + fn requested_chroma_subsampling_is_written_in_the_frame_header() { + let src = test_rgb(19, 9); + for (sub, expected) in [(ChromaSubsampling::S444, 0x11), (ChromaSubsampling::S422, 0x21), (ChromaSubsampling::S420, 0x22)] { + let jpeg = encode(&src, 19, 9, 3, 90, sub, &[]); + let sof = jpeg.windows(2).position(|w| w == [0xFF, 0xC0]).expect("SOF0 marker"); + assert_eq!(jpeg.get(sof + 11), Some(&expected), "{sub:?}"); + } + } + + fn test_rgb(w: usize, h: usize) -> Vec { + let mut v = Vec::with_capacity(w * h * 3); + for y in 0..h { + for x in 0..w { + let t = ((x as f32 / 13.0).sin() * 0.5 + 0.5) * 255.0; + v.extend_from_slice(&[(x * 255 / w) as u8, (y * 255 / h) as u8, t as u8]); + } + } + v + } + + fn psnr(a: &[u8], b: &[u8]) -> f64 { + let mse = a.iter().zip(b).map(|(x, y)| (*x as f64 - *y as f64).powi(2)).sum::() / a.len() as f64; + 10.0 * (255.0f64.powi(2) / mse.max(1e-9)).log10() + } + + /// The AAN path matches the direct DCT-II definition. + #[test] + fn aan_matches_reference_dct() { + let block: [f32; 64] = std::array::from_fn(|i| ((i * 37 % 255) as f32) - 128.0); + let q = [1u16; 64]; + let mut out = [0i16; 64]; + fdct_quant(&block, &recip_table(&q), &mut out); + for v in 0..8 { + for u in 0..8 { + let c = |k: usize| if k == 0 { std::f64::consts::FRAC_1_SQRT_2 } else { 1.0 }; + let mut s = 0.0; + for y in 0..8 { + for x in 0..8 { + s += block[y * 8 + x] as f64 + * (((2 * x + 1) * u) as f64 * std::f64::consts::PI / 16.0).cos() + * (((2 * y + 1) * v) as f64 * std::f64::consts::PI / 16.0).cos(); + } + } + let f = 0.25 * c(u) * c(v) * s; + assert!((out[v * 8 + u] as f64 - f).abs() <= 0.51, "({u},{v}): {} vs {f}", out[v * 8 + u]); + } + } + } + + #[test] + fn huffman_tables_are_consistent() { + for (bits, n) in [(&AC_LUMA_BITS, AC_LUMA_VALS.len()), (&AC_CHROMA_BITS, AC_CHROMA_VALS.len()), (&DC_LUMA_BITS, 12), (&DC_CHROMA_BITS, 12)] { + assert_eq!(bits.iter().map(|&b| b as usize).sum::(), n); + } + } + + #[test] + fn decodes_with_independent_decoders_at_odd_sizes() { + for (w, h, sub) in [ + (1, 1, ChromaSubsampling::S444), + (37, 23, ChromaSubsampling::S420), + (37, 23, ChromaSubsampling::S422), + (640, 1031, ChromaSubsampling::S420), + (803, 600, ChromaSubsampling::S444), + ] { + let src = test_rgb(w, h); + let jpg = encode(&src, w, h, 3, 92, sub, &[]); + let mut d = jpeg_decoder::Decoder::new(&jpg[..]); + let px = d.decode().expect("jpeg-decoder"); + let info = d.info().unwrap(); + assert_eq!((info.width as usize, info.height as usize), (w, h)); + if w * h > 64 { + assert!(psnr(&src, &px) > 30.0, "{w}x{h} {sub:?}: psnr {}", psnr(&src, &px)); + } + let z = zune_jpeg::JpegDecoder::new(zune_jpeg::zune_core::bytestream::ZCursor::new(&jpg[..])).decode().expect("zune-jpeg"); + assert_eq!(z.len(), px.len()); + } + } + + /// The code lengths of `(bits, vals)`, checked: every listed symbol once, at most 16 bits, + /// and room left in the code space (the all-ones code is never assigned, Kraft sum < 1). + fn check_table(bits: &[u8; 16], vals: &[u8]) { + assert_eq!(bits.iter().map(|&b| b as usize).sum::(), vals.len()); + let mut seen = [false; 256]; + for &v in vals { + assert!(!seen[v as usize], "symbol {v} listed twice"); + seen[v as usize] = true; + } + let kraft: f64 = bits.iter().enumerate().map(|(i, &n)| n as f64 / 2f64.powi(i as i32 + 1)).sum(); + assert!(kraft < 1.0, "code space full: {kraft}"); + let h = Huff::new(bits, vals); + for &v in vals { + let (c, l) = h.code[v as usize]; + assert!((1..=16).contains(&l)); + assert_ne!(c as u32, (1u32 << l) - 1, "symbol {v} has the all-ones code"); + } + } + + #[test] + fn optimal_tables_are_valid_and_bounded() { + // one symbol, two, a typical spread and every symbol + let mut one = [0u64; 256]; + one[7] = 5; + let mut two = [0u64; 256]; + two[0] = 1; + two[0xF0] = 1_000_000; + let typical: Freq = std::array::from_fn(|s| if s % 3 == 0 { (s as u64 * 7919) % 1000 + 1 } else { 0 }); + let all: Freq = std::array::from_fn(|s| s as u64 + 1); + // Fibonacci counts make an unbounded Huffman tree ~40 levels deep: the 16-bit limit applies + let mut fib = [0u64; 256]; + let (mut a, mut b) = (1u64, 1u64); + for f in fib.iter_mut().take(40) { + *f = a; + (a, b) = (b, a + b); + } + for (name, f) in [("one", one), ("two", two), ("typical", typical), ("all", all), ("fib", fib), ("none", [0; 256])] { + let (bits, vals) = optimal_table(&f); + check_table(&bits, &vals); + for (s, &count) in f.iter().enumerate() { + assert_eq!(vals.contains(&(s as u8)), count > 0 || (name == "none" && s == 0), "{name}: symbol {s}"); + } + } + // more frequent symbols never get longer codes + let (bits, vals) = optimal_table(&typical); + let h = Huff::new(&bits, &vals); + for &x in &vals { + for &y in &vals { + if typical[x as usize] > typical[y as usize] { + assert!(h.code[x as usize].1 <= h.code[y as usize].1, "{x} vs {y}"); + } + } + } + // the Annex K example tables pass the same checks + check_table(&AC_LUMA_BITS, &AC_LUMA_VALS); + check_table(&DC_CHROMA_BITS, &DC_VALS); + } + + /// Issue #1373: tables made for the image give a smaller file with exactly the same pixels as + /// the Annex K example tables (the quantized coefficients are the same), at every quality and + /// subsampling, and both decoders read it. + #[test] + fn optimized_tables_shrink_files_without_changing_pixels() { + let (w, h) = (517, 333); + // gradients plus deterministic noise, like a photo's grain + let mut seed = 0x2545_f491_u32; + let src: Vec = test_rgb(w, h) + .into_iter() + .map(|v| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + v.saturating_add((seed % 23) as u8) + }) + .collect(); + for (q, sub) in [ + (100, ChromaSubsampling::S444), + (92, ChromaSubsampling::S444), + (75, ChromaSubsampling::S420), + (30, ChromaSubsampling::S420), + (85, ChromaSubsampling::S422), + ] { + let std = encode_with(&src, w, h, 3, q, sub, &[], false); + let opt = encode(&src, w, h, 3, q, sub, &[]); + assert!(opt.len() < std.len(), "q{q} {sub:?}: {} ≥ {}", opt.len(), std.len()); + let a = jpeg_decoder::Decoder::new(&std[..]).decode().expect("standard tables"); + let b = jpeg_decoder::Decoder::new(&opt[..]).decode().expect("optimized tables"); + assert_eq!(a, b, "q{q} {sub:?}: pixels differ"); + let z = zune_jpeg::JpegDecoder::new(zune_jpeg::zune_core::bytestream::ZCursor::new(&opt[..])).decode().expect("zune-jpeg"); + assert_eq!(z.len(), b.len()); + } + // grayscale too + let gray: Vec = src.iter().step_by(3).copied().collect(); + let std = encode_with(&gray, w, h, 1, 90, ChromaSubsampling::S444, &[], false); + let opt = encode(&gray, w, h, 1, 90, ChromaSubsampling::S444, &[]); + assert!(opt.len() < std.len()); + assert_eq!(jpeg_decoder::Decoder::new(&std[..]).decode().unwrap(), jpeg_decoder::Decoder::new(&opt[..]).decode().unwrap()); + } + + /// The bytes written for 4:4:4, 4:2:0, grayscale and RGBA input at a size cut into many bands, with partial MCUs + /// at the right and bottom edges, pinned: each band converts its own rows to YCbCr, which must not change a bit. + #[test] + fn encoded_bytes_are_pinned() { + let fnv = |b: &[u8]| b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| (h ^ u64::from(x)).wrapping_mul(0x100_0000_01b3)); + let (w, h) = (1203, 1037); + let rgb = test_rgb(w, h); + let gray: Vec = rgb.as_chunks::<3>().0.iter().map(|p| p[1]).collect(); + let rgba: Vec = rgb.as_chunks::<3>().0.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect(); + let got = [ + fnv(&encode(&rgb, w, h, 3, 90, ChromaSubsampling::S444, &[])), + fnv(&encode(&rgb, w, h, 3, 75, ChromaSubsampling::S420, &[])), + fnv(&encode(&gray, w, h, 1, 90, ChromaSubsampling::S444, &[])), + fnv(&encode(&rgba, w, h, 4, 85, ChromaSubsampling::S444, &[])), + ]; + assert_eq!(got, PINNED, "{got:#x?}"); + } + /// [`round_i16`] against `f32::round` at the halves, the ends of `i16`, NaN and infinities, and a spread of every + /// magnitude (all 2^32 inputs were compared once, offline). + #[test] + fn round_i16_is_round_as_i16() { + let special = [0.5f32, -0.5, 1.5, -1.5, 2.5, -2.5, 0.499_999_97, -0.499_999_97, 32767.5, -32768.5, 32766.5, 1e9, -1e9]; + let all = special.into_iter().chain([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]).chain((0..=u32::MAX).step_by(9973).map(f32::from_bits)); + for x in all { + assert_eq!(round_i16(x), x.round() as i16, "{x:e}"); + } + } + const PINNED: [u64; 4] = [0x52ba_772a_589c_1430, 0x013f_8364_821f_1dde, 0xb2a3_b5e5_aef3_7402, 0x08df_d6dc_aa2f_1c78]; + #[test] + fn grayscale_and_quality_monotone() { + let (w, h) = (300, 200); + let src: Vec = (0..w * h).map(|i| ((i % w) * 255 / w) as u8 ^ ((i / w) as u8 & 0x10)).collect(); + let lo = encode(&src, w, h, 1, 30, ChromaSubsampling::S444, &[]); + let hi = encode(&src, w, h, 1, 95, ChromaSubsampling::S444, &[]); + assert!(lo.len() < hi.len()); + let px = jpeg_decoder::Decoder::new(&hi[..]).decode().unwrap(); + assert!(psnr(&src, &px) > 35.0); + } +} diff --git a/crates/jpeg/src/lib.rs b/crates/jpeg/src/lib.rs index 185bf3ec5..50e1bd625 100644 --- a/crates/jpeg/src/lib.rs +++ b/crates/jpeg/src/lib.rs @@ -1,6 +1,5 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -//! Clean-room decoder for the JPEG processes most Rust JPEG decoders don't handle, written from -//! ITU-T T.81 (ISO/IEC 10918-1). +//! Clean-room JPEG decoding and baseline encoding, written from ITU-T T.81 (ISO/IEC 10918-1). //! //! [`decode`] supports these frames: //! @@ -1703,3 +1702,7 @@ pub use bands::{Band, Bands, Reader}; #[cfg(test)] mod tests; + +/// Baseline JPEG encoder (8-bit, Huffman-coded sequential DCT). +mod encode; +pub use encode::{ChromaSubsampling, EncodeError, encode_baseline}; diff --git a/crates/jsonrpc/Cargo.toml b/crates/jsonrpc/Cargo.toml new file mode 100644 index 000000000..7456ececf --- /dev/null +++ b/crates/jsonrpc/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-jsonrpc" +description = "Bounded JSON-RPC 2.0 server envelopes without transport or application routing" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde_json = { workspace = true } diff --git a/crates/jsonrpc/README.md b/crates/jsonrpc/README.md new file mode 100644 index 000000000..8711c25ff --- /dev/null +++ b/crates/jsonrpc/README.md @@ -0,0 +1,31 @@ +# craft-jsonrpc + +`craft-jsonrpc` provides bounded JSON-RPC 2.0 server envelopes independently of a transport or an +application's method router. It can read a bounded newline-delimited message, parse it from bytes, +check request IDs and batch sizes, dispatch requests and notifications separately, and build +response envelopes. It does not start a server, choose an MCP protocol version, or interpret tool +names and arguments. + +`Limits` defaults to 64 MiB per message and 4096 batch entries. `parse_json` checks the byte limit +before deserialization, and `process` rejects an oversized batch before calling any handler. +For newline-delimited transports, `read_line` bounds memory while reading; after an over-limit +line, the caller must close the stream or discard the rest of that line. +`serde_json`'s nesting limit remains in effect. Response sizes are the caller's responsibility. + +A valid request receives the handler's result or error with its original string, numeric, or null +ID. The default accepts numeric IDs as required by [JSON-RPC 2.0](https://www.jsonrpc.org/specification#request_object), +which discourages fractional values. Set `integer_ids_only` and clear `allow_null_ids` for +protocols such as MCP that require integer or string IDs. A legacy server can retain its previous +null-ID behavior independently. An omitted ID is a notification: it calls the separate notification +handler and gets no reply. +Malformed batch entries receive an invalid-request error; an empty batch gets one error response; +a batch containing only notifications has no response. Invalid parameter shapes receive an +invalid-params error for requests and no reply for notifications. The handler decides whether +object or array parameters are valid for each method. + +The caller may inspect the bounded parsed value before `process` to support an existing legacy +protocol. Parse failures and limit failures are returned explicitly so each transport can choose +its error and connection policy; `parse_error_response` builds the JSON-RPC parse error. + +The envelope behavior is extracted from StencilCraft's JSON-lines MCP/control server. App-specific +method routing, legacy control requests, and MCP lifecycle policy stay with the app. diff --git a/crates/jsonrpc/src/lib.rs b/crates/jsonrpc/src/lib.rs new file mode 100644 index 000000000..9f8128d1d --- /dev/null +++ b/crates/jsonrpc/src/lib.rs @@ -0,0 +1,197 @@ +//! Bounded JSON-RPC 2.0 server envelopes without a transport or application router. +//! +//! Parse a bounded line with [`parse_json`], then pass the value to [`process`]. A host may +//! inspect the parsed value first for a legacy protocol. `process` validates envelopes, dispatches +//! requests and notifications separately, and constructs single or batch replies. The host owns +//! the transport, method semantics and response-size policy. + +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use serde_json::{Value, json}; +use std::io::BufRead; + +/// Bounds on a single JSON document and on the number of requests in a batch. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + pub max_message_bytes: usize, + pub max_batch_items: usize, + /// Reject fractional JSON numbers as IDs for protocols that require integer IDs. + pub integer_ids_only: bool, + /// Permit an explicit null request ID, as JSON-RPC does; some protocols prohibit it. + pub allow_null_ids: bool, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_message_bytes: 64 * 1024 * 1024, max_batch_items: 4096, integer_ids_only: false, allow_null_ids: true } + } +} + +/// Failure before dispatch. An over-limit batch is rejected before any callback is invoked. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ParseError { + MessageTooLarge, + InvalidJson, + BatchTooLarge, +} + +impl std::fmt::Display for ParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::MessageTooLarge => "JSON-RPC message exceeds the byte limit", + Self::InvalidJson => "invalid JSON", + Self::BatchTooLarge => "JSON-RPC batch exceeds the item limit", + }) + } +} +impl std::error::Error for ParseError {} + +/// Error reading a newline-delimited message. After `TooLong`, close or otherwise discard the +/// remaining input line before reading another message. +#[derive(Debug)] +pub enum LineError { + Io(std::io::Error), + TooLong, +} + +impl std::fmt::Display for LineError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Io(error) => write!(f, "message read failed: {error}"), + Self::TooLong => f.write_str("message exceeds the byte limit"), + } + } +} +impl std::error::Error for LineError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + Self::TooLong => None, + } + } +} + +/// Read at most `max_bytes` before a newline, without allocating for an oversized line. The +/// newline is consumed but omitted from the returned bytes. EOF with no bytes returns `None`; +/// an empty line returns `Some(Vec::new())`. +pub fn read_line(reader: &mut R, max_bytes: usize) -> Result>, LineError> { + let mut line = Vec::new(); + loop { + let bytes = reader.fill_buf().map_err(LineError::Io)?; + if bytes.is_empty() { + return Ok((!line.is_empty()).then_some(line)); + } + let newline = bytes.iter().position(|&byte| byte == b'\n'); + let len = newline.unwrap_or(bytes.len()); + if line.len().saturating_add(len) > max_bytes { + return Err(LineError::TooLong); + } + line.extend_from_slice(&bytes[..len]); + reader.consume(len + usize::from(newline.is_some())); + if newline.is_some() { + return Ok(Some(line)); + } + } +} + +/// Parse JSON after checking its byte length. `serde_json` also bounds nesting depth. +pub fn parse_json(bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.max_message_bytes { + return Err(ParseError::MessageTooLarge); + } + serde_json::from_slice(bytes).map_err(|_| ParseError::InvalidJson) +} + +/// A validated request or notification. A present null `id` is distinct from an omitted `id`. +#[derive(Clone, Copy, Debug)] +pub struct Request<'a> { + pub id: Option<&'a Value>, + pub method: &'a str, + pub params: Option<&'a Value>, +} + +/// Inspect a single request envelope. This validates its JSON-RPC version, method and ID; +/// [`process`] additionally validates parameter shape before dispatching it. +pub fn request(value: &Value, limits: Limits) -> Option> { + let object = value.as_object()?; + let id = object.get("id"); + let valid_id = id.is_none_or(|v| { + (v.is_null() && limits.allow_null_ids) || v.is_string() || if limits.integer_ids_only { v.is_i64() || v.is_u64() } else { v.is_number() } + }); + if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") || !valid_id { + return None; + } + Some(Request { id, method: object.get("method")?.as_str()?, params: object.get("params") }) +} + +/// A JSON-RPC error returned by a method handler. +#[derive(Clone, Debug, PartialEq)] +pub struct RpcError { + pub code: i64, + pub message: String, + pub data: Option, +} + +impl RpcError { + pub fn new(code: i64, message: impl Into) -> Self { + Self { code, message: message.into(), data: None } + } +} + +/// Build an error response, including optional error data. +pub fn error_response(id: Value, error: RpcError) -> Value { + let mut detail = json!({"code": error.code, "message": error.message}); + if let (Some(data), Some(object)) = (error.data, detail.as_object_mut()) { + object.insert("data".into(), data); + } + json!({"jsonrpc": "2.0", "id": id, "error": detail}) +} + +/// Build the standard parse-error response for input that is not JSON. +pub fn parse_error_response() -> Value { + error_response(Value::Null, RpcError::new(-32700, "Parse error")) +} + +fn invalid_request() -> Value { + error_response(Value::Null, RpcError::new(-32600, "Invalid Request")) +} + +fn one(value: &Value, limits: Limits, on_request: &mut F, on_notification: &mut N) -> Option +where + F: FnMut(Request<'_>) -> Result, + N: FnMut(Request<'_>), +{ + let Some(request) = request(value, limits) else { return Some(invalid_request()) }; + let id = request.id; + if request.params.is_some_and(|v| !v.is_object() && !v.is_array()) { + return id.map(|id| error_response(id.clone(), RpcError::new(-32602, "Invalid params"))); + } + let Some(id) = id else { + on_notification(request); + return None; + }; + Some(match on_request(request) { + Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}), + Err(error) => error_response(id.clone(), error), + }) +} + +/// Process a parsed JSON-RPC message. Notifications never receive a response. Invalid batch +/// entries produce individual errors; an empty batch produces one invalid-request response. +/// A batch over the limit returns [`ParseError::BatchTooLarge`] without invoking either callback. +pub fn process(value: &Value, limits: Limits, mut on_request: F, mut on_notification: N) -> Result, ParseError> +where + F: FnMut(Request<'_>) -> Result, + N: FnMut(Request<'_>), +{ + let Some(batch) = value.as_array() else { return Ok(one(value, limits, &mut on_request, &mut on_notification)) }; + if batch.len() > limits.max_batch_items { + return Err(ParseError::BatchTooLarge); + } + if batch.is_empty() { + return Ok(Some(invalid_request())); + } + let responses: Vec<_> = batch.iter().filter_map(|v| one(v, limits, &mut on_request, &mut on_notification)).collect(); + Ok((!responses.is_empty()).then_some(Value::Array(responses))) +} diff --git a/crates/jsonrpc/tests/server.rs b/crates/jsonrpc/tests/server.rs new file mode 100644 index 000000000..a9186f4ae --- /dev/null +++ b/crates/jsonrpc/tests/server.rs @@ -0,0 +1,172 @@ +use craft_jsonrpc::{Limits, ParseError, RpcError, parse_error_response, parse_json, process}; +use serde_json::{Value, json}; + +#[test] +fn batches_preserve_ids_order_and_suppress_notification_replies() { + let input = json!([ + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": "a", "method": "ping"}, + {"jsonrpc": "2.0", "id": 2, "method": "unknown"}, + 17, + {"jsonrpc": "2.0", "id": null, "method": "ping"} + ]); + let mut notifications = Vec::new(); + let result = process( + &input, + Limits::default(), + |request| match request.method { + "ping" => Ok(json!({})), + _ => Err(RpcError::new(-32601, "Method not found")), + }, + |request| notifications.push(request.method.to_owned()), + ) + .unwrap() + .unwrap(); + assert_eq!(notifications, ["notifications/initialized"]); + assert_eq!( + result, + json!([ + {"jsonrpc":"2.0", "id":"a", "result":{}}, + {"jsonrpc":"2.0", "id":2, "error":{"code":-32601,"message":"Method not found"}}, + {"jsonrpc":"2.0", "id":null, "error":{"code":-32600,"message":"Invalid Request"}}, + {"jsonrpc":"2.0", "id":null, "result":{}} + ]) + ); +} + +#[test] +fn notifications_never_receive_responses_including_all_notification_batches() { + let input = json!([ + {"jsonrpc":"2.0", "method":"tools/call", "params":{"name":"mutating"}}, + {"jsonrpc":"2.0", "method":"notifications/initialized"} + ]); + let mut requests = 0; + let mut notices = 0; + let result = process( + &input, + Limits::default(), + |_| { + requests += 1; + Ok(Value::Null) + }, + |_| notices += 1, + ) + .unwrap(); + assert!(result.is_none()); + assert_eq!(requests, 0); + assert_eq!(notices, 2); +} + +#[test] +fn invalid_envelopes_and_params_return_standard_errors() { + for id in [json!(true), json!([]), json!({})] { + let input = json!({"jsonrpc":"2.0", "id":id, "method":"ping"}); + let reply = process(&input, Limits::default(), |_| panic!("invalid id dispatched"), |_| panic!("invalid id notified")).unwrap().unwrap(); + assert_eq!(reply["id"], Value::Null); + assert_eq!(reply["error"]["code"], -32600); + } + for input in [json!({}), json!({"jsonrpc":"1.0", "id":1, "method":"ping"}), json!({"jsonrpc":"2.0", "id":1}), json!([])] { + let reply = + process(&input, Limits::default(), |_| panic!("invalid request dispatched"), |_| panic!("invalid notification")).unwrap().unwrap(); + assert_eq!(reply["error"]["code"], -32600); + } + let input = json!({"jsonrpc":"2.0", "id":4, "method":"ping", "params":17}); + let reply = process(&input, Limits::default(), |_| panic!("invalid params dispatched"), |_| {}).unwrap().unwrap(); + assert_eq!(reply["id"], 4); + assert_eq!(reply["error"]["code"], -32602); + let notification = json!({"jsonrpc":"2.0", "method":"notice", "params":17}); + assert!(process(¬ification, Limits::default(), |_| panic!("invalid request"), |_| panic!("invalid notification")).unwrap().is_none()); +} + +#[test] +fn arrays_are_valid_params_and_errors_can_include_data() { + let input = json!({"jsonrpc":"2.0", "id":-7, "method":"test", "params":[1, 2]}); + let reply = process( + &input, + Limits::default(), + |request| { + assert_eq!(request.params, Some(&json!([1, 2]))); + let mut error = RpcError::new(-32000, "failure"); + error.data = Some(json!({"why":"example"})); + Err(error) + }, + |_| {}, + ) + .unwrap() + .unwrap(); + assert_eq!(reply, json!({"jsonrpc":"2.0", "id":-7, "error":{"code":-32000,"message":"failure","data":{"why":"example"}}})); +} + +#[test] +fn parse_and_batch_limits_apply_before_dispatch() { + let limits = Limits { max_message_bytes: 3, max_batch_items: 1, ..Limits::default() }; + assert_eq!(parse_json(b"null", limits), Err(ParseError::MessageTooLarge)); + assert_eq!(parse_json(b"123", limits).unwrap(), json!(123)); + assert_eq!(parse_json(b"{", limits), Err(ParseError::InvalidJson)); + assert_eq!(parse_error_response()["error"]["code"], -32700); + let input = json!([{"jsonrpc":"2.0", "id":1, "method":"ping"}, {"jsonrpc":"2.0", "method":"notice"}]); + assert_eq!( + process(&input, limits, |_| panic!("over-limit batch dispatched"), |_| panic!("over-limit batch notified")), + Err(ParseError::BatchTooLarge) + ); + let one = json!([{"jsonrpc":"2.0", "id":1, "method":"ping"}]); + assert_eq!(process(&one, limits, |_| Ok(json!({})), |_| {}).unwrap().unwrap().as_array().unwrap().len(), 1); +} + +#[test] +fn invalid_utf8_and_excessive_nesting_are_rejected() { + assert_eq!(parse_json(&[0xff], Limits::default()), Err(ParseError::InvalidJson)); + let nested = format!("{}0{}", "[".repeat(200), "]".repeat(200)); + assert_eq!(parse_json(nested.as_bytes(), Limits::default()), Err(ParseError::InvalidJson)); +} + +#[test] +fn bounded_line_read_handles_chunks_empty_lines_and_eof() { + use std::io::{BufReader, Cursor}; + let mut reader = BufReader::with_capacity(2, Cursor::new(b"abc\n\nxy")); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(b"abc".to_vec())); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(Vec::new())); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(b"xy".to_vec())); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), None); + let mut too_long = BufReader::with_capacity(2, Cursor::new(b"abcd\n")); + assert!(matches!(craft_jsonrpc::read_line(&mut too_long, 3), Err(craft_jsonrpc::LineError::TooLong))); +} + +#[test] +fn bounded_line_read_propagates_io_errors() { + struct Broken; + impl std::io::Read for Broken { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(std::io::Error::other("broken")) + } + } + let mut reader = std::io::BufReader::new(Broken); + assert!(matches!(craft_jsonrpc::read_line(&mut reader, 1), Err(craft_jsonrpc::LineError::Io(_)))); +} + +#[test] +fn inspect_single_request_distinguishes_null_ids_and_invalid_envelopes() { + let request = json!({"jsonrpc":"2.0", "id":null, "method":"ping"}); + let parsed = craft_jsonrpc::request(&request, Limits::default()).unwrap(); + assert_eq!(parsed.id, Some(&Value::Null)); + assert_eq!(parsed.method, "ping"); + let notification = json!({"jsonrpc":"2.0", "method":"ping"}); + assert!(craft_jsonrpc::request(¬ification, Limits::default()).unwrap().id.is_none()); + assert!(craft_jsonrpc::request(&json!({"jsonrpc":"2.0", "id":false, "method":"ping"}), Limits::default()).is_none()); + assert!(craft_jsonrpc::request(&json!({"method":"ping"}), Limits::default()).is_none()); +} + +#[test] +fn numeric_ids_follow_the_selected_protocol_policy() { + let input = json!({"jsonrpc":"2.0", "id":1.5, "method":"ping"}); + let reply = process(&input, Limits::default(), |_| Ok(json!({})), |_| {}).unwrap().unwrap(); + assert_eq!(reply["id"], json!(1.5)); + let strict = Limits { integer_ids_only: true, ..Limits::default() }; + let reply = process(&input, strict, |_| panic!("fractional ID dispatched"), |_| {}).unwrap().unwrap(); + assert_eq!(reply["id"], Value::Null); + assert_eq!(reply["error"]["code"], -32600); + let no_null = Limits { allow_null_ids: false, ..strict }; + let null_id = json!({"jsonrpc":"2.0", "id":null, "method":"ping"}); + let reply = process(&null_id, no_null, |_| panic!("null ID dispatched"), |_| {}).unwrap().unwrap(); + assert_eq!(reply["error"]["code"], -32600); +} diff --git a/crates/jxl/Cargo.toml b/crates/jxl/Cargo.toml new file mode 100644 index 000000000..45ed44f12 --- /dev/null +++ b/crates/jxl/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "craft-jxl" +description = "JPEG XL image decoding and encoding with bounded input and allocation tracking." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +default = ["decode", "encode"] +decode = ["dep:jxl-oxide"] +encode = ["dep:jixel"] + +[dependencies] +jxl-oxide = { workspace = true, optional = true } +thiserror = { workspace = true } + +[dev-dependencies] +craft-cms = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +jixel = { workspace = true, optional = true } diff --git a/crates/jxl/README.md b/crates/jxl/README.md new file mode 100644 index 000000000..a3a8c6fa4 --- /dev/null +++ b/crates/jxl/README.md @@ -0,0 +1,25 @@ +# craft-jxl + +JPEG XL decoding and encoding for still raster images. + +The decoder reads a codestream incrementally, checks its dimensions before loading the remainder, +and applies a caller-selected compressed-input, pixel-count, and tracked-decoder-allocation budget. +`jxl-oxide`'s allocation tracker cannot account for every allocation made by the decoder, and the +input slice is already owned by the caller. The decoder returns the first frame as interleaved +`f32` samples together with source and rendered color metadata. It does not perform an external +ICC transform; callers that need color-managed output should use the returned profiles with their +CMS. CMYK output is rejected because this crate does not bundle an external CMS. + +`decode_with_color` can request linear Rec. 2020 for enum-encoded images. XYB is rendered through +linear sRGB and converted to Rec. 2020 to avoid the known wide-gamut XYB rendering issue in +`jxl-oxide`. If a source embeds an ICC profile, the decoder keeps the source-profile samples and +returns the profile; it does not claim to transform ICC data without a CMS. `decode` retains the +decoder's default rendering target. + +The encoder accepts interleaved 8-bit, 16-bit, or HDR floating-point samples. Floating-point input +is linear-light and is currently available only with the Rec. 2020 PQ option; one input unit maps +to 203 cd/m². Gray input is expanded to RGB, and opaque alpha is omitted. ICC data is embedded in +lossless output; Exif and XMP boxes are written when provided. Encoding is unavailable on +`wasm32` targets. + +`jxl-oxide` is MIT OR Apache-2.0. `jixel` is BSD-3-Clause OR Apache-2.0. diff --git a/crates/jxl/src/decode.rs b/crates/jxl/src/decode.rs new file mode 100644 index 000000000..955774b23 --- /dev/null +++ b/crates/jxl/src/decode.rs @@ -0,0 +1,259 @@ +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use jxl_oxide::color::{ColourEncoding, ColourSpace, EnumColourEncoding, Primaries, RenderingIntent, TransferFunction, WhitePoint}; +use jxl_oxide::{AllocTracker, AuxBoxData, ExtraChannelType, InitializeResult, JxlImage}; + +use crate::{DecodeLimits, Decoded, Error, Layout, Metadata, OutputColor, Result}; + +const INPUT_CHUNK: usize = 4096; +const TRACKED_BYTES_PER_PIXEL: u64 = 4 * 4 * 8; +const MIN_TRACKED_BYTES: u64 = 64 << 20; + +/// Decode the first frame, keeping the decoder's tracked allocations within `limits`. +/// +/// The allocator budget applies to allocations registered with `jxl-oxide`'s `AllocTracker`. +/// The decoder may also make untracked allocations, including the input buffer supplied by the +/// caller. Header data is fed in small chunks so the dimensions are checked before the rest of +/// the codestream is loaded. +pub fn decode(bytes: &[u8], limits: DecodeLimits) -> Result { + decode_with_color(bytes, limits, OutputColor::DecoderDefault) +} + +/// Decode the first image frame using an explicit rendered-pixel color target. +pub fn decode_with_color(bytes: &[u8], limits: DecodeLimits, output_color: OutputColor) -> Result { + catch_unwind(AssertUnwindSafe(|| decode_inner(bytes, limits, output_color))) + .unwrap_or_else(|_| Err(Error::Malformed("decoder failed while reading this file".into()))) +} + +fn decode_inner(bytes: &[u8], limits: DecodeLimits, output_color: OutputColor) -> Result { + if bytes.len() > limits.max_input_bytes { + return Err(Error::LimitExceeded(format!("{} input bytes exceed the {} byte input limit", bytes.len(), limits.max_input_bytes))); + } + let budget = limits.max_tracked_bytes.unwrap_or_else(|| limits.max_pixels.saturating_mul(TRACKED_BYTES_PER_PIXEL).max(MIN_TRACKED_BYTES)); + let tracker = AllocTracker::with_limit(usize::try_from(budget).unwrap_or(usize::MAX)); + let mut uninit = JxlImage::builder().alloc_tracker(tracker).build_uninit(); + let mut rest = bytes; + let mut window = INPUT_CHUNK; + let mut image = loop { + let feed = rest.get(..window).unwrap_or(rest); + let consumed = uninit.feed_bytes(feed).map_err(decode_error)?; + rest = rest.get(consumed..).unwrap_or_default(); + match uninit.try_init().map_err(decode_error)? { + InitializeResult::Initialized(image) => break image, + InitializeResult::NeedMoreData(next) => uninit = next, + } + if consumed == 0 { + if window >= rest.len() { + return Err(Error::Malformed("truncated JPEG XL header".into())); + } + window = window.saturating_mul(2); + } + }; + + let (width, height) = (image.width(), image.height()); + if width == 0 || height == 0 { + return Err(Error::Malformed("zero image dimension".into())); + } + let pixels = u64::from(width).saturating_mul(u64::from(height)); + if pixels > limits.max_pixels { + return Err(Error::PixelLimitExceeded { width, height, max_pixels: limits.max_pixels }); + } + + // `JxlImageBuilder::read` feeds the full input. Continue in bounded chunks so trailing frame + // data and boxes are not copied into an untracked buffer all at once. + while !image.is_loading_done() && !rest.is_empty() { + let consumed = image.feed_bytes(rest.get(..INPUT_CHUNK).unwrap_or(rest)).map_err(decode_error)?; + if consumed == 0 { + break; + } + rest = rest.get(consumed..).unwrap_or_default(); + } + image.finalize().map_err(decode_error)?; + + let (bit_depth, float_samples, grayscale, source_orientation, xyb_encoded, extra_channels, colour_encoding) = { + let metadata = &image.image_header().metadata; + ( + metadata.bit_depth.bits_per_sample() as u8, + matches!(metadata.bit_depth, jxl_oxide::image::BitDepth::FloatSample { .. }), + metadata.grayscale(), + metadata.orientation, + metadata.xyb_encoded, + metadata.ec_info.iter().map(|info| info.ty).collect::>(), + metadata.colour_encoding.clone(), + ) + }; + let source_icc = image.original_icc().map(ToOwned::to_owned); + let has_source_icc = source_icc.is_some(); + if has_black_channel(&extra_channels) || image.pixel_format().has_black() { + return Err(Error::Unsupported("CMYK JPEG XL rendering requires an external color-management transform".into())); + } + let alpha_channel = first_alpha(&extra_channels); + let alpha_associated = alpha_channel.is_some_and(|(_, associated)| associated); + let via_srgb = output_color == OutputColor::LinearRec2020 && source_icc.is_none() && !grayscale && xyb_encoded; + // Associated samples must be divided while still in their coded nonlinear space. Leave these + // frames in their own encoding so the caller can apply its color transform after unpremultiplying. + // XYB and unsupported transfer curves stay on the renderer's linear target path; those cases + // are premultiplied after decoding instead. + let enum_source_has_supported_curve = matches!( + &colour_encoding, + ColourEncoding::Enum(encoding) if enum_encoding_has_supported_curve(encoding) + ); + let preserve_source_encoding = + output_color == OutputColor::LinearRec2020 && alpha_associated && !xyb_encoded && (source_icc.is_some() || enum_source_has_supported_curve); + if output_color == OutputColor::LinearRec2020 && source_icc.is_none() && !preserve_source_encoding { + image.request_color_encoding(EnumColourEncoding { + colour_space: if grayscale { ColourSpace::Grey } else { ColourSpace::Rgb }, + white_point: WhitePoint::D65, + primaries: if via_srgb { Primaries::Srgb } else { Primaries::Bt2100 }, + tf: TransferFunction::Linear, + rendering_intent: RenderingIntent::Relative, + }); + } + let colors = if grayscale { 1 } else { 3 }; + let pixel_format = image.pixel_format(); + if pixel_format.has_black() { + return Err(Error::Unsupported("CMYK JPEG XL rendering requires an external color-management transform".into())); + } + let has_alpha = alpha_channel.is_some(); + let layout = match (grayscale, has_alpha) { + (true, false) => Layout::Gray, + (true, true) => Layout::GrayAlpha, + (false, false) => Layout::Rgb, + (false, true) => Layout::Rgba, + }; + let keep = colors + usize::from(has_alpha); + let frame = image.render_frame(0).map_err(decode_error)?; + let buffer = frame.image_all_channels(); + let channels = buffer.channels(); + if channels < colors || (has_alpha && channels < keep) { + return Err(Error::Malformed("decoded frame has too few channels".into())); + } + let color_channels = channels + .checked_sub(extra_channels.len()) + .filter(|&count| count >= colors) + .ok_or_else(|| Error::Malformed("decoded frame has too few color channels".into()))?; + let alpha_index = alpha_channel.map(|(index, _)| color_channels + index); + let (rendered_width, rendered_height) = ( + u32::try_from(buffer.width()).map_err(|_| Error::LimitExceeded("rendered width exceeds 32-bit dimensions".into()))?, + u32::try_from(buffer.height()).map_err(|_| Error::LimitExceeded("rendered height exceeds 32-bit dimensions".into()))?, + ); + let frame_pixels = u128::from(rendered_width) * u128::from(rendered_height); + if frame_pixels != u128::from(pixels) { + return Err(Error::Malformed("decoded frame dimensions do not match the image header".into())); + } + let sample_count = usize::try_from(frame_pixels.checked_mul(keep as u128).ok_or_else(|| Error::LimitExceeded("sample count overflows".into()))?) + .map_err(|_| Error::LimitExceeded("sample count exceeds addressable memory".into()))?; + let mut out = Vec::new(); + out.try_reserve_exact(sample_count).map_err(|e| Error::LimitExceeded(format!("cannot reserve decoded pixels: {e}")))?; + for pixel in buffer.buf().chunks_exact(channels) { + let start = out.len(); + out.extend_from_slice(&pixel[..colors]); + if let Some(index) = alpha_index { + let alpha_value = pixel.get(index).copied().ok_or_else(|| Error::Malformed("decoded frame is missing its alpha channel".into()))?; + if preserve_source_encoding && alpha_associated { + let divisor = alpha_value.clamp(0.0, 1.0); + if divisor > 0.0 { + for channel in &mut out[start..] { + *channel /= divisor; + } + } + } + out.push(alpha_value); + } + if via_srgb { + let [r, g, b] = [out[start], out[start + 1], out[start + 2]]; + out[start] = 0.627_403_9 * r + 0.329_283_04 * g + 0.043_313_067 * b; + out[start + 1] = 0.069_097_29 * r + 0.919_540_4 * g + 0.011_362_316 * b; + out[start + 2] = 0.016_391_44 * r + 0.088_013_31 * g + 0.895_595_25 * b; + } + } + + let metadata = Metadata { + icc: source_icc, + exif: match image.aux_boxes().first_exif() { + Ok(AuxBoxData::Data(exif)) => { + usize::try_from(exif.tiff_header_offset()).ok().and_then(|offset| exif.payload().get(offset..)).map(ToOwned::to_owned) + } + _ => None, + }, + xmp: match image.aux_boxes().first_xml() { + AuxBoxData::Data(xmp) => Some(xmp.to_vec()), + _ => None, + }, + }; + let pixels_linear_rec2020 = output_color == OutputColor::LinearRec2020 && !has_source_icc && !preserve_source_encoding; + Ok(Decoded { + width: rendered_width, + height: rendered_height, + layout, + bit_depth, + float_samples, + pixels: out, + metadata, + source_orientation, + rendered_cicp: image.rendered_cicp(), + rendered_icc: image.rendered_icc(), + xyb_encoded, + pixels_linear_rec2020, + pixels_premultiplied: alpha_associated && !preserve_source_encoding, + }) +} + +fn first_alpha(channels: &[ExtraChannelType]) -> Option<(usize, bool)> { + channels.iter().enumerate().find_map(|(index, channel)| match channel { + ExtraChannelType::Alpha { alpha_associated } => Some((index, *alpha_associated)), + _ => None, + }) +} + +fn has_black_channel(channels: &[ExtraChannelType]) -> bool { + channels.iter().any(|channel| matches!(channel, ExtraChannelType::Black)) +} + +fn enum_encoding_has_supported_curve(encoding: &EnumColourEncoding) -> bool { + matches!(encoding.colour_space, ColourSpace::Rgb | ColourSpace::Grey) + && match &encoding.tf { + TransferFunction::Linear | TransferFunction::Srgb | TransferFunction::Bt709 | TransferFunction::Dci => true, + TransferFunction::Gamma { g, .. } => *g > 0, + _ => false, + } +} + +fn decode_error(error: impl std::fmt::Display) -> Error { + Error::Malformed(error.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const STRAIGHT: ExtraChannelType = ExtraChannelType::Alpha { alpha_associated: false }; + const ASSOCIATED: ExtraChannelType = ExtraChannelType::Alpha { alpha_associated: true }; + const SPOT: ExtraChannelType = ExtraChannelType::SpotColour { red: 1.0, green: 0.0, blue: 0.0, solidity: 1.0 }; + + #[test] + fn alpha_is_selected_by_type_and_order() { + assert_eq!(first_alpha(&[SPOT, STRAIGHT]), Some((1, false))); + assert_eq!(first_alpha(&[STRAIGHT, SPOT]), Some((0, false))); + assert_eq!(first_alpha(&[ExtraChannelType::Depth, ASSOCIATED, STRAIGHT]), Some((1, true))); + assert_eq!(first_alpha(&[ExtraChannelType::Black, SPOT, ExtraChannelType::Depth]), None); + } + + #[test] + fn black_extra_channel_is_detected_by_type() { + assert!(has_black_channel(&[SPOT, ExtraChannelType::Black])); + assert!(!has_black_channel(&[SPOT, STRAIGHT])); + } + + #[test] + fn only_modeled_nonlinear_enum_encodings_are_preserved_for_unpremultiplication() { + let mut encoding = EnumColourEncoding::srgb(RenderingIntent::Relative); + assert!(enum_encoding_has_supported_curve(&encoding)); + encoding.tf = TransferFunction::Pq; + assert!(!enum_encoding_has_supported_curve(&encoding)); + encoding.tf = TransferFunction::Linear; + assert!(enum_encoding_has_supported_curve(&encoding)); + encoding.colour_space = ColourSpace::Xyb; + assert!(!enum_encoding_has_supported_curve(&encoding)); + } +} diff --git a/crates/jxl/src/encode.rs b/crates/jxl/src/encode.rs new file mode 100644 index 000000000..caf77957c --- /dev/null +++ b/crates/jxl/src/encode.rs @@ -0,0 +1,236 @@ +#[cfg(not(target_arch = "wasm32"))] +use std::panic::{AssertUnwindSafe, catch_unwind}; + +#[cfg(not(target_arch = "wasm32"))] +use crate::Layout; +use crate::{Error, ImageRef, Metadata, Result, Samples}; + +/// Encoder search effort. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Effort { + /// Quickest search, with larger output files. + Fast, + /// Balanced search. + #[default] + Normal, +} + +/// Color encoding declared by a JPEG XL image. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum JxlColour { + /// sRGB primaries and transfer curve. + #[default] + Srgb, + /// Display P3 primaries, D65, with the sRGB transfer curve. + DisplayP3, + /// Rec. 2020 primaries with the BT.709 transfer curve. + Rec2020, + /// Rec. 2020 primaries with the SMPTE ST 2084 PQ transfer curve. + Rec2020Pq, +} + +/// JPEG XL encoder settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EncodeOptions { + /// Lossy quality on a 1..=100 scale (90 is approximately visually lossless). Ignored for + /// mathematically lossless output. + pub quality: u8, + /// Use mathematically lossless Modular coding. + pub lossless: bool, + /// Encoder search effort. + pub effort: Effort, + /// Use progressive encoding; lossless output uses the Squeeze transform. + pub progressive: bool, + /// Color encoding to write. + pub colour: JxlColour, +} + +impl Default for EncodeOptions { + fn default() -> Self { + Self { quality: 90, lossless: false, effort: Effort::Normal, progressive: false, colour: JxlColour::Srgb } + } +} + +/// SDR reference white used when converting linear float input to HDR PQ, in cd/m². +pub const HDR_REFERENCE_WHITE_NITS: f32 = 203.0; + +/// Encode a still image to JPEG XL. +/// +/// Gray input is widened to RGB. Alpha is omitted when every sample is opaque. Float input is +/// encoded only with `JxlColour::Rec2020Pq`; its linear values use SDR white at 203 cd/m². +/// ICC data is embedded only for lossless output, where the explicit ICC profile takes precedence +/// over the enum color encoding. Exif and XMP are embedded when supplied. +pub fn encode(image: &ImageRef<'_>, options: EncodeOptions, metadata: &Metadata) -> Result> { + validate(image)?; + #[cfg(all(not(target_arch = "wasm32"), feature = "encode"))] + { + let pixels = Pixels::from(image, options.colour)?; + catch_unwind(AssertUnwindSafe(|| run(&pixels, image.width as usize, image.height as usize, options, metadata))) + .unwrap_or_else(|_| Err(Error::Encode("encoder failed while writing this image".into()))) + } + #[cfg(any(target_arch = "wasm32", not(feature = "encode")))] + { + let _ = (image, options, metadata); + Err(Error::Unsupported("JPEG XL encoding is unavailable on this target".into())) + } +} + +fn validate(image: &ImageRef<'_>) -> Result<()> { + if image.width == 0 || image.height == 0 { + return Err(Error::InvalidImage("zero dimension".into())); + } + let pixels = u128::from(image.width) * u128::from(image.height); + let samples = pixels * image.layout.channels() as u128; + if samples > usize::MAX as u128 { + return Err(Error::InvalidImage("image sample count exceeds addressable memory".into())); + } + let have = match image.samples { + Samples::U8(data) => data.len(), + Samples::U16(data) => data.len(), + Samples::F32(data) => data.len(), + }; + if have < samples as usize { + return Err(Error::InvalidImage(format!("sample buffer has {have} samples, expected at least {samples}"))); + } + Ok(()) +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "encode"))] +enum Pixels { + U8 { data: Vec, alpha: bool }, + U16 { data: Vec, alpha: bool }, +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "encode"))] +impl Pixels { + fn from(image: &ImageRef<'_>, colour: JxlColour) -> Result { + let n = usize::try_from(u64::from(image.width) * u64::from(image.height)) + .map_err(|_| Error::InvalidImage("image pixel count exceeds addressable memory".into()))?; + Ok(match image.samples { + Samples::U8(samples) => { + let (data, alpha) = convert(samples, image.layout, n, |a| a == u8::MAX)?; + Pixels::U8 { data, alpha } + } + Samples::U16(samples) => { + let (data, alpha) = convert(samples, image.layout, n, |a| a == u16::MAX)?; + Pixels::U16 { data, alpha } + } + Samples::F32(samples) if colour == JxlColour::Rec2020Pq => { + let count = n.checked_mul(4).ok_or_else(|| Error::InvalidImage("pixel buffer size overflows".into()))?; + let mut encoded = Vec::new(); + encoded.try_reserve_exact(count).map_err(|e| Error::InvalidImage(format!("cannot reserve pixel buffer: {e}")))?; + for pixel in samples.chunks_exact(image.layout.channels()).take(n) { + let (rgb, alpha) = pixel_to_rgba(pixel, image.layout); + for channel in rgb { + encoded.push(pq_sample(channel)); + } + encoded.push(alpha_sample(alpha)); + } + let (data, alpha) = convert(&encoded, Layout::Rgba, n, |a| a == u16::MAX)?; + Pixels::U16 { data, alpha } + } + Samples::F32(_) => return Err(Error::InvalidImage("float samples require Rec. 2020 PQ encoding".into())), + }) + } +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "encode"))] +fn convert(samples: &[T], layout: Layout, pixels: usize, opaque: impl Fn(T) -> bool) -> Result<(Vec, bool)> { + let channels = layout.channels(); + let input = samples + .get(..pixels.checked_mul(channels).ok_or_else(|| Error::InvalidImage("sample count overflows".into()))?) + .ok_or_else(|| Error::InvalidImage("sample buffer is too short".into()))?; + let alpha = layout.has_alpha() && input.chunks_exact(channels).any(|p| p.last().is_some_and(|a| !opaque(*a))); + let output_channels = if alpha { 4 } else { 3 }; + let output_count = pixels.checked_mul(output_channels).ok_or_else(|| Error::InvalidImage("converted sample count overflows".into()))?; + let mut out = Vec::new(); + out.try_reserve_exact(output_count).map_err(|e| Error::InvalidImage(format!("cannot reserve converted samples: {e}")))?; + for pixel in input.chunks_exact(channels) { + match (layout, pixel) { + (Layout::Gray, [g]) => out.extend_from_slice(&[*g, *g, *g]), + (Layout::GrayAlpha, [g, a]) if alpha => out.extend_from_slice(&[*g, *g, *g, *a]), + (Layout::GrayAlpha, [g, _]) => out.extend_from_slice(&[*g, *g, *g]), + (Layout::Rgb, [r, g, b]) => out.extend_from_slice(&[*r, *g, *b]), + (Layout::Rgba, [r, g, b, a]) if alpha => out.extend_from_slice(&[*r, *g, *b, *a]), + (Layout::Rgba, [r, g, b, _]) => out.extend_from_slice(&[*r, *g, *b]), + _ => return Err(Error::InvalidImage("unsupported pixel layout".into())), + } + } + Ok((out, alpha)) +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "encode"))] +fn pixel_to_rgba(pixel: &[f32], layout: Layout) -> ([f32; 3], f32) { + let finite = |v: f32| if v.is_finite() { v } else { 0.0 }; + match (layout, pixel) { + (Layout::Gray, [g]) => ([finite(*g); 3], 1.0), + (Layout::GrayAlpha, [g, a]) => ([finite(*g); 3], finite(*a).clamp(0.0, 1.0)), + (Layout::Rgb, [r, g, b]) => ([finite(*r), finite(*g), finite(*b)], 1.0), + (Layout::Rgba, [r, g, b, a]) => ([finite(*r), finite(*g), finite(*b)], finite(*a).clamp(0.0, 1.0)), + _ => ([0.0; 3], 1.0), + } +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "encode"))] +fn pq_sample(value: f32) -> u16 { + let linear_nits = (if value.is_finite() { value.max(0.0) } else { 0.0 }) * HDR_REFERENCE_WHITE_NITS; + (pq_encode(linear_nits) * 65535.0).round().clamp(0.0, 65535.0) as u16 +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "encode"))] +fn alpha_sample(value: f32) -> u16 { + ((if value.is_finite() { value.clamp(0.0, 1.0) } else { 1.0 }) * 65535.0).round() as u16 +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "encode"))] +fn pq_encode(nits: f32) -> f32 { + const M1: f32 = 2610.0 / 16384.0; + const M2: f32 = 2523.0 / 4096.0 * 128.0; + const C1: f32 = 3424.0 / 4096.0; + const C2: f32 = 2413.0 / 4096.0 * 32.0; + const C3: f32 = 2392.0 / 4096.0 * 32.0; + let y = (nits / 10_000.0).clamp(0.0, 1.0).powf(M1); + ((C1 + C2 * y) / (1.0 + C3 * y)).powf(M2) +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "encode"))] +fn run(pixels: &Pixels, width: usize, height: usize, options: EncodeOptions, metadata: &Metadata) -> Result> { + use jixel::{ColorEncoding, EncodeConfig, Primaries, Speed, TransferFunction}; + + let colour = match options.colour { + JxlColour::Srgb => ColorEncoding::srgb(), + JxlColour::DisplayP3 => ColorEncoding::display_p3(), + JxlColour::Rec2020 => ColorEncoding { primaries: Primaries::Bt2020, transfer: TransferFunction::Bt709, ..ColorEncoding::srgb() }, + JxlColour::Rec2020Pq => ColorEncoding::bt2020_pq(), + }; + let mut config = EncodeConfig::default() + .with_quality(f32::from(options.quality.clamp(1, 100))) + .with_color_encoding(colour) + .with_lossless(options.lossless) + .with_progressive(options.progressive) + .with_speed(match options.effort { + Effort::Fast => Speed::Fastest, + Effort::Normal => Speed::Fast, + }); + if options.colour == JxlColour::Rec2020Pq { + config = config.with_intensity_target(10_000.0); + } + if options.lossless + && let Some(icc) = &metadata.icc + { + config = config.with_icc_profile(icc.clone()); + } + if let Some(exif) = &metadata.exif { + config = config.with_exif(exif.clone()); + } + if let Some(xmp) = &metadata.xmp { + config = config.with_xmp(xmp.clone()); + } + let result = match pixels { + Pixels::U8 { data, alpha: false } => jixel::encode_image(data, width, height, &config), + Pixels::U8 { data, alpha: true } => jixel::encode_image_with_alpha(data, width, height, &config), + Pixels::U16 { data, alpha: false } => jixel::encode_image_16bit(data, width, height, &config), + Pixels::U16 { data, alpha: true } => jixel::encode_image_with_alpha_16bit(data, width, height, &config), + }; + result.map_err(|error| Error::Encode(error.to_string())) +} diff --git a/crates/jxl/src/lib.rs b/crates/jxl/src/lib.rs new file mode 100644 index 000000000..fcdd96199 --- /dev/null +++ b/crates/jxl/src/lib.rs @@ -0,0 +1,186 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +#![warn(missing_docs)] +//! JPEG XL image decoding and encoding. +//! +//! Decoding incrementally feeds the input, checks image dimensions before loading remaining +//! frames, and applies a tracked-allocation budget. The allocation tracker covers allocations +//! made through `jxl-oxide`; it cannot account for every allocation inside a decoder dependency. +//! The first image frame is returned, with orientation already applied to its pixels. + +#[cfg(feature = "decode")] +mod decode; +#[cfg(feature = "encode")] +mod encode; + +/// Pixel channel layout. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Layout { + /// One grayscale channel. + Gray, + /// Grayscale and straight alpha. + GrayAlpha, + /// Red, green, blue. + Rgb, + /// Red, green, blue and straight alpha. + Rgba, +} + +/// Color encoding requested for rendered pixels. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum OutputColor { + /// Use `jxl-oxide`'s default rendering target and report its rendered profile. + #[default] + DecoderDefault, + /// For files with enum color encoding, render linear Rec. 2020. XYB files render to linear + /// sRGB first and are converted to Rec. 2020 to avoid a `jxl-oxide` wide-gamut XYB issue. + /// Files with an embedded ICC profile remain rendered in that profile's space; the source + /// ICC is returned in [`Metadata::icc`] because this crate does not bundle an ICC CMS. + LinearRec2020, +} + +impl Layout { + /// Number of interleaved channels. + pub const fn channels(self) -> usize { + match self { + Layout::Gray => 1, + Layout::GrayAlpha => 2, + Layout::Rgb => 3, + Layout::Rgba => 4, + } + } + + /// Whether this layout includes alpha. + pub const fn has_alpha(self) -> bool { + matches!(self, Layout::GrayAlpha | Layout::Rgba) + } +} + +/// Sample data accepted by the encoder. +#[derive(Clone, Copy, Debug)] +pub enum Samples<'a> { + /// Unsigned 8-bit samples, already encoded using the selected color transfer curve. + U8(&'a [u8]), + /// Unsigned 16-bit samples, already encoded using the selected color transfer curve. + U16(&'a [u16]), + /// Floating point samples. These are accepted only for Rec. 2020 PQ encoding. + F32(&'a [f32]), +} + +/// A borrowed image to encode. Samples are interleaved and alpha is straight. +#[derive(Clone, Copy, Debug)] +pub struct ImageRef<'a> { + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// Channel layout. + pub layout: Layout, + /// Interleaved sample data. + pub samples: Samples<'a>, +} + +/// Metadata embedded in the JPEG XL container. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Metadata { + /// ICC profile bytes, when present. + pub icc: Option>, + /// TIFF-structured Exif payload, without an `Exif\0\0` prefix. + pub exif: Option>, + /// XMP packet bytes. + pub xmp: Option>, +} + +/// JPEG XL operation error. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The image is malformed or cannot be decoded. + #[error("JPEG XL: malformed image: {0}")] + Malformed(String), + /// The image exceeds a caller supplied size or allocation limit. + #[error("JPEG XL: limit exceeded: {0}")] + LimitExceeded(String), + /// The encoded dimensions exceed the caller's pixel-count limit. + #[error("JPEG XL: image dimensions {width}×{height} exceed the {max_pixels} pixel limit")] + PixelLimitExceeded { + /// Encoded image width. + width: u32, + /// Encoded image height. + height: u32, + /// Maximum accepted pixel count. + max_pixels: u64, + }, + /// The image layout or samples are unsupported. + #[error("JPEG XL: invalid image: {0}")] + InvalidImage(String), + /// Encoding failed. + #[error("JPEG XL: encode failed: {0}")] + Encode(String), + /// The requested operation is not available in this build. + #[error("JPEG XL: unsupported: {0}")] + Unsupported(String), +} + +/// Result returned by this crate. +pub type Result = std::result::Result; + +/// Decoded first frame and source metadata. +#[cfg(feature = "decode")] +#[derive(Clone, Debug)] +pub struct Decoded { + /// Width after applying the codestream orientation. + pub width: u32, + /// Height after applying the codestream orientation. + pub height: u32, + /// Output channel layout. + pub layout: Layout, + /// Bits per sample signalled in the file. + pub bit_depth: u8, + /// Whether the source samples use a floating-point representation. + pub float_samples: bool, + /// Interleaved floating point samples in the decoder's rendered color encoding. + pub pixels: Vec, + /// Metadata from the source image. + pub metadata: Metadata, + /// Original orientation value. Pixels in `pixels` already have this orientation applied. + pub source_orientation: u32, + /// CICP value describing the rendered pixel encoding, when the decoder supplies one. + pub rendered_cicp: Option<[u8; 4]>, + /// ICC profile describing the rendered pixel encoding. + pub rendered_icc: Vec, + /// Whether the codestream uses XYB encoding. + pub xyb_encoded: bool, + /// Whether `pixels` are linear Rec. 2020. This is false when associated alpha requires keeping + /// a modeled nonlinear source encoding so the caller can unpremultiply before its color transform. + pub pixels_linear_rec2020: bool, + /// Whether color samples in `pixels` remain associated with alpha. When true, divide them by + /// alpha after any necessary transfer conversion; at zero alpha the color values are undefined. + pub pixels_premultiplied: bool, +} + +/// Options for bounded decoding. +#[cfg(feature = "decode")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DecodeLimits { + /// Largest accepted pixel count. Defaults to 1 gigapixel. + pub max_pixels: u64, + /// Maximum allocation budget passed to `jxl-oxide`'s tracked allocator. `None` scales the + /// budget from `max_pixels` and preserves fixed decoder overhead for small images. + pub max_tracked_bytes: Option, + /// Largest compressed input size. Defaults to `usize::MAX`. + pub max_input_bytes: usize, +} + +#[cfg(feature = "decode")] +impl Default for DecodeLimits { + fn default() -> Self { + Self { max_pixels: 1 << 30, max_tracked_bytes: None, max_input_bytes: usize::MAX } + } +} + +/// Decode the first image frame. +#[cfg(feature = "decode")] +pub use decode::{decode, decode_with_color}; +/// Encode a JPEG XL image. +#[cfg(feature = "encode")] +pub use encode::{Effort, EncodeOptions, HDR_REFERENCE_WHITE_NITS, JxlColour, encode}; diff --git a/crates/jxl/tests/roundtrip.rs b/crates/jxl/tests/roundtrip.rs new file mode 100644 index 000000000..2bc4cf8e1 --- /dev/null +++ b/crates/jxl/tests/roundtrip.rs @@ -0,0 +1,425 @@ +use craft_jxl::{ + DecodeLimits, EncodeOptions, HDR_REFERENCE_WHITE_NITS, ImageRef, JxlColour, Layout, Metadata, OutputColor, Samples, decode, decode_with_color, + encode, +}; + +fn raw_codestream(bytes: &[u8]) -> Vec { + if bytes.starts_with(b"\xff\x0a") { + return bytes.to_vec(); + } + let mut raw = Vec::new(); + let mut at = 12_usize; + while at.checked_add(8).is_some_and(|end| end <= bytes.len()) { + let Some(size) = bytes.get(at..at + 4).and_then(|s| s.try_into().ok()).map(u32::from_be_bytes) else { break }; + let end = if size == 0 { bytes.len() } else { at.saturating_add(size as usize) }; + let Some(kind) = bytes.get(at + 4..at + 8) else { break }; + if end < at + 8 || end > bytes.len() { + break; + } + let header = if kind == b"jxlp" { 12 } else { 8 }; + if (kind == b"jxlc" || kind == b"jxlp") + && let Some(data) = bytes.get(at + header..end) + { + raw.extend_from_slice(data); + } + if end <= at { + break; + } + at = end; + } + raw +} + +fn box_bytes(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { + out.extend_from_slice(&u32::try_from(data.len() + 8).unwrap_or(u32::MAX).to_be_bytes()); + out.extend_from_slice(kind); + out.extend_from_slice(data); +} + +#[test] +fn lossless_rgba_roundtrip_keeps_alpha_layout() { + let samples = [255, 0, 0, 255, 0, 255, 0, 64]; + let image = ImageRef { width: 2, height: 1, layout: Layout::Rgba, samples: Samples::U8(&samples) }; + let exif = b"II*\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x01\0\0\0\0\0\0\0"; + let xmp = b""; + let metadata = Metadata { exif: Some(exif.to_vec()), xmp: Some(xmp.to_vec()), ..Metadata::default() }; + let encoded = encode(&image, EncodeOptions { lossless: true, ..EncodeOptions::default() }, &metadata); + assert!(encoded.is_ok(), "valid image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + let decoded = decode(&encoded, DecodeLimits::default()); + assert!(decoded.is_ok(), "encoded image should decode: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + + assert_eq!((decoded.width, decoded.height), (2, 1)); + assert_eq!(decoded.layout, Layout::Rgba); + assert_eq!(decoded.pixels.len(), 8); + assert_eq!(decoded.pixels[3], 1.0); + assert!((decoded.pixels[7] - 64.0 / 255.0).abs() < 0.01); + assert_eq!(decoded.metadata.exif.as_deref(), Some(exif.as_slice())); + assert_eq!(decoded.metadata.xmp.as_deref(), Some(xmp.as_slice())); +} + +#[test] +fn exif_payload_starts_at_its_declared_tiff_header_offset() { + let image = ImageRef { width: 2, height: 1, layout: Layout::Rgb, samples: Samples::U8(&[10, 20, 30, 40, 50, 60]) }; + let encoded = encode(&image, EncodeOptions { lossless: true, ..EncodeOptions::default() }, &Metadata::default()); + assert!(encoded.is_ok(), "valid image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + let raw = raw_codestream(&encoded); + let exif = b"II*\0\x08\0\0\0\0\0\0\0"; + + for offset in [0_u32, 6, 64] { + let mut exif_box = offset.to_be_bytes().to_vec(); + exif_box.resize(4 + offset as usize, 0xab); + exif_box.extend_from_slice(exif); + let mut container = b"\0\0\0\x0cJXL \x0d\x0a\x87\x0a".to_vec(); + box_bytes(&mut container, b"ftyp", b"jxl \0\0\0\0jxl "); + box_bytes(&mut container, b"jxlc", &raw); + box_bytes(&mut container, b"Exif", &exif_box); + + let decoded = decode(&container, DecodeLimits::default()); + assert!(decoded.is_ok(), "container with Exif offset {offset} should decode: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + assert_eq!(decoded.metadata.exif.as_deref(), Some(exif.as_slice()), "TIFF header offset {offset}"); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn associated_alpha_is_unpremultiplied_before_color_conversion() { + let straight = [[200_u8, 100, 50, 128], [30, 180, 240, 192], [100, 80, 60, 255], [220, 110, 40, 160]]; + let mut premultiplied = Vec::with_capacity(straight.len() * 4); + for pixel in &straight { + let alpha = f32::from(pixel[3]) / 255.0; + premultiplied.extend(pixel[..3].iter().map(|channel| (f32::from(*channel) * alpha).round() as u8)); + premultiplied.push(pixel[3]); + } + let metadata = jixel::FlMeta { alpha_premultiplied: true, ..jixel::FlMeta::srgb() }; + let encoded = jixel::encode_fast_lossless(&premultiplied, 2, 2, jixel::ColorSpace::Rgb, true, &metadata); + assert!(encoded.is_ok(), "associated-alpha image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + + let decoded = decode_with_color(&encoded, DecodeLimits::default(), OutputColor::LinearRec2020); + assert!(decoded.is_ok(), "associated-alpha image should decode: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + assert_eq!(decoded.layout, Layout::Rgba); + assert!(!decoded.pixels_linear_rec2020, "the source encoding is needed for the caller's color transform"); + assert!(!decoded.pixels_premultiplied, "associated color samples must be divided before nonlinear conversion"); + + for (i, source) in straight.iter().enumerate() { + let alpha = f32::from(source[3]) / 255.0; + assert!((decoded.pixels[i * 4 + 3] - alpha).abs() < 1e-6); + for (channel, &value) in source[..3].iter().enumerate() { + let expected = f32::from(value) / 255.0; + assert!((decoded.pixels[i * 4 + channel] - expected).abs() < 0.01, "pixel {i}, channel {channel}"); + } + } +} + +#[test] +fn decoder_enforces_input_and_pixel_limits() { + let samples = [10_u8, 20, 30]; + let image = ImageRef { width: 1, height: 1, layout: Layout::Rgb, samples: Samples::U8(&samples) }; + let encoded = encode(&image, EncodeOptions { lossless: true, ..EncodeOptions::default() }, &Metadata::default()); + assert!(encoded.is_ok(), "valid image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + + let input_limit = DecodeLimits { max_input_bytes: encoded.len() - 1, ..DecodeLimits::default() }; + assert!(matches!(decode(&encoded, input_limit), Err(craft_jxl::Error::LimitExceeded(_)))); + let pixel_limit = DecodeLimits { max_pixels: 0, ..DecodeLimits::default() }; + assert!(matches!(decode(&encoded, pixel_limit), Err(craft_jxl::Error::PixelLimitExceeded { width: 1, height: 1, max_pixels: 0 }))); +} + +#[test] +fn malformed_input_returns_an_error() { + assert!(decode(b"not a JPEG XL file", DecodeLimits::default()).is_err()); +} + +#[test] +fn encoder_rejects_short_sample_buffers() { + let image = ImageRef { width: 2, height: 1, layout: Layout::Rgb, samples: Samples::U8(&[1, 2, 3]) }; + assert!(matches!(encode(&image, EncodeOptions::default(), &Metadata::default()), Err(craft_jxl::Error::InvalidImage(_)))); +} + +#[test] +fn lossless_gray_input_is_expanded_to_rgb() { + let samples = [0, 40, 128, 255]; + let image = ImageRef { width: 4, height: 1, layout: Layout::Gray, samples: Samples::U8(&samples) }; + let encoded = encode(&image, EncodeOptions { lossless: true, ..EncodeOptions::default() }, &Metadata::default()); + assert!(encoded.is_ok(), "valid grayscale image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + let decoded = decode(&encoded, DecodeLimits::default()); + assert!(decoded.is_ok(), "grayscale image should decode: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + assert_eq!(decoded.layout, Layout::Rgb); + assert_eq!(decoded.pixels.len(), 4 * 3); + let (pixels, remainder) = decoded.pixels.as_chunks::<3>(); + assert!(remainder.is_empty()); + for (pixel, gray) in pixels.iter().zip(samples) { + let expected = f32::from(gray) / 255.0; + assert!(pixel.iter().all(|channel| (channel - expected).abs() < 0.01)); + } +} + +#[test] +fn lossless_u16_samples_keep_their_bit_depth_and_values() { + let samples: Vec<u16> = (0..40 * 30 * 3).map(|i| (i as u32 * 2741 % 65536) as u16).collect(); + let image = ImageRef { width: 40, height: 30, layout: Layout::Rgb, samples: Samples::U16(&samples) }; + let encoded = encode(&image, EncodeOptions { lossless: true, ..EncodeOptions::default() }, &Metadata::default()); + assert!(encoded.is_ok(), "valid 16-bit image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + let decoded = decode(&encoded, DecodeLimits::default()); + assert!(decoded.is_ok(), "16-bit image should decode: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + assert_eq!(decoded.bit_depth, 16); + assert_eq!(decoded.layout, Layout::Rgb); + assert_eq!(decoded.pixels.len(), samples.len()); + for (got, sample) in decoded.pixels.iter().zip(samples) { + let expected = f32::from(sample) / 65535.0; + assert!((got - expected).abs() < 1e-5, "16-bit value differs: {got} vs {expected}"); + } +} + +#[test] +fn enum_encoded_pixels_can_be_rendered_as_linear_rec2020() { + let samples = [180, 40, 20, 10, 140, 60, 20, 80, 180]; + let image = ImageRef { width: 3, height: 1, layout: Layout::Rgb, samples: Samples::U8(&samples) }; + let encoded = encode(&image, EncodeOptions { lossless: true, colour: JxlColour::Rec2020, ..EncodeOptions::default() }, &Metadata::default()); + assert!(encoded.is_ok(), "valid image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + let decoded = decode_with_color(&encoded, DecodeLimits::default(), OutputColor::LinearRec2020); + assert!(decoded.is_ok(), "valid image should decode: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + + assert!(!decoded.xyb_encoded, "lossless enum encoding should use Modular coding"); + assert_eq!(decoded.layout, Layout::Rgb); + assert_eq!((decoded.width, decoded.height), (3, 1)); + assert!(decoded.pixels.iter().all(|sample| sample.is_finite())); + assert!(decoded.rendered_icc.len() > 128, "requested Rec. 2020 linear target has a rendered profile"); +} + +#[test] +fn xybcoded_pixels_use_the_linear_srgb_workaround_before_rec2020() { + let samples = [ + 250, 5, 5, 128, 10, 240, 10, 255, 5, 10, 250, 255, 190, 130, 40, 255, 120, 20, 170, 255, 20, 160, 180, 255, 240, 230, 10, 255, 80, 90, 100, + 255, + ]; + let image = ImageRef { width: 4, height: 2, layout: Layout::Rgba, samples: Samples::U8(&samples) }; + let encoded = encode(&image, EncodeOptions { quality: 95, colour: JxlColour::Srgb, ..EncodeOptions::default() }, &Metadata::default()); + assert!(encoded.is_ok(), "valid image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + let decoded = decode_with_color(&encoded, DecodeLimits::default(), OutputColor::LinearRec2020); + assert!(decoded.is_ok(), "valid image should decode: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + + assert!(decoded.xyb_encoded, "lossy RGB JPEG XL should use XYB"); + assert_eq!(decoded.layout, Layout::Rgba); + assert_eq!(decoded.pixels.len(), 4 * 2 * 4); + let (decoded_pixels, decoded_remainder) = decoded.pixels.as_chunks::<4>(); + assert!(decoded_remainder.is_empty()); + assert!(decoded_pixels.iter().all(|pixel| (0.0..=1.0).contains(&pixel[3]))); + assert!(decoded.pixels.iter().all(|sample| sample.is_finite())); + + let reference = jxl_oxide::JxlImage::builder().read(encoded.as_slice()); + assert!(reference.is_ok(), "reference decoder should accept the encoded image: {reference:?}"); + let Ok(mut reference) = reference else { return }; + reference.request_color_encoding(jxl_oxide::color::EnumColourEncoding { + colour_space: jxl_oxide::color::ColourSpace::Rgb, + white_point: jxl_oxide::color::WhitePoint::D65, + primaries: jxl_oxide::color::Primaries::Srgb, + tf: jxl_oxide::color::TransferFunction::Linear, + rendering_intent: jxl_oxide::color::RenderingIntent::Relative, + }); + let reference_frame = reference.render_frame(0); + assert!(reference_frame.is_ok(), "reference frame should render: {reference_frame:?}"); + let Ok(reference_frame) = reference_frame else { return }; + let reference = reference_frame.image_all_channels(); + assert_eq!(reference.channels(), 4); + let (actual_pixels, actual_remainder) = decoded.pixels.as_chunks::<4>(); + let (reference_pixels, reference_remainder) = reference.buf().as_chunks::<4>(); + assert!(actual_remainder.is_empty()); + assert!(reference_remainder.is_empty()); + for (actual, linear_srgb) in actual_pixels.iter().zip(reference_pixels) { + let [r, g, b] = [linear_srgb[0], linear_srgb[1], linear_srgb[2]]; + let expected = [ + 0.627_403_9 * r + 0.329_283_04 * g + 0.043_313_067 * b, + 0.069_097_29 * r + 0.919_540_4 * g + 0.011_362_316 * b, + 0.016_391_44 * r + 0.088_013_31 * g + 0.895_595_25 * b, + ]; + for (got, want) in actual[..3].iter().zip(expected) { + assert!((got - want).abs() < 1e-6, "linear Rec. 2020 channel differs: {got} vs {want}"); + } + assert_eq!(actual[3], linear_srgb[3], "color conversion leaves alpha unchanged"); + } +} + +#[test] +fn icc_encoded_pixels_keep_the_embedded_profile_under_linear_target_request() { + let samples = [180, 40, 20, 10, 140, 60, 20, 80, 180]; + let image = ImageRef { width: 3, height: 1, layout: Layout::Rgb, samples: Samples::U8(&samples) }; + let icc = craft_cms::Builtin::DisplayP3.profile().to_bytes(); + let metadata = Metadata { icc: Some(icc.as_ref().clone()), ..Metadata::default() }; + let encoded = encode(&image, EncodeOptions { lossless: true, colour: JxlColour::DisplayP3, ..EncodeOptions::default() }, &metadata); + assert!(encoded.is_ok(), "valid image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + let decoder_default = decode(&encoded, DecodeLimits::default()); + let linear_request = decode_with_color(&encoded, DecodeLimits::default(), OutputColor::LinearRec2020); + assert!(decoder_default.is_ok(), "ICC image should decode: {decoder_default:?}"); + assert!(linear_request.is_ok(), "ICC image should decode: {linear_request:?}"); + let (Ok(decoder_default), Ok(linear_request)) = (decoder_default, linear_request) else { return }; + + assert_eq!(decoder_default.metadata.icc.as_deref(), Some(icc.as_slice())); + assert_eq!(linear_request.metadata.icc.as_deref(), Some(icc.as_slice())); + assert_eq!(decoder_default.pixels, linear_request.pixels, "without a bundled CMS, the requested target preserves ICC-space samples"); +} + +#[test] +fn lossy_quality_effort_and_progressive_options_produce_decodable_images() { + let (width, height) = (160_u32, 120_u32); + let mut samples = Vec::with_capacity(width as usize * height as usize * 4); + for y in 0..height { + for x in 0..width { + let fx = x as f32 / width as f32; + let fy = y as f32 / height as f32; + samples.extend_from_slice(&[(fx * 255.0) as u8, (fy * 255.0) as u8, ((1.0 - fx) * 200.0) as u8, (((fx + fy) * 0.5) * 255.0) as u8]); + } + } + let image = ImageRef { width, height, layout: Layout::Rgba, samples: Samples::U8(&samples) }; + let encode_options = |quality, effort, progressive| EncodeOptions { quality, effort, progressive, ..EncodeOptions::default() }; + let hi = encode(&image, encode_options(95, craft_jxl::Effort::Normal, false), &Metadata::default()); + let lo = encode(&image, encode_options(40, craft_jxl::Effort::Normal, false), &Metadata::default()); + assert!(hi.is_ok(), "high-quality image should encode: {hi:?}"); + assert!(lo.is_ok(), "low-quality image should encode: {lo:?}"); + let (Ok(hi), Ok(lo)) = (hi, lo) else { return }; + assert!(lo.len() < hi.len(), "quality 40 output {} should be smaller than quality 95 output {}", lo.len(), hi.len()); + + for bytes in [&hi, &lo] { + let decoded = decode(bytes, DecodeLimits::default()); + assert!(decoded.is_ok(), "encoded image should decode: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + assert_eq!((decoded.width, decoded.height), (width, height)); + assert_eq!(decoded.layout, Layout::Rgba); + let threshold = if bytes.len() == hi.len() { 38.0 } else { 28.0 }; + let psnr = psnr8(&samples, &decoded.pixels, 4); + assert!(psnr > threshold, "PSNR {psnr:.2} dB must exceed {threshold:.1} dB"); + } + + for effort in [craft_jxl::Effort::Fast, craft_jxl::Effort::Normal] { + for progressive in [false, true] { + let encoded = encode(&image, encode_options(90, effort, progressive), &Metadata::default()); + assert!(encoded.is_ok(), "{effort:?} progressive={progressive} should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + let decoded = decode(&encoded, DecodeLimits::default()); + assert!(decoded.is_ok(), "{effort:?} progressive={progressive} should decode: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + let psnr = psnr8(&samples, &decoded.pixels, 4); + assert!(psnr > 34.0, "{effort:?} progressive={progressive} PSNR {psnr:.2} dB"); + } + } +} + +fn psnr8(source: &[u8], decoded: &[f32], channels: usize) -> f64 { + let mut squared_error = 0.0; + for (source, decoded) in source.chunks_exact(channels).zip(decoded.chunks_exact(channels)) { + for channel in 0..3 { + let difference = f64::from(source[channel]) - f64::from(decoded[channel] * 255.0); + squared_error += difference * difference; + } + } + let samples = (source.len() / channels * 3) as f64; + let mse = squared_error / samples; + if mse == 0.0 { f64::INFINITY } else { 10.0 * (255.0 * 255.0 / mse).log10() } +} + +#[test] +fn rec2020_pq_float_samples_are_written_as_hdr() { + let (width, height) = (64_u32, 32_u32); + let samples: Vec<f32> = + (0..(width * height) as usize).flat_map(|i| [if i % (width as usize) < width as usize / 2 { 1.0 } else { 4.0 }; 3]).collect(); + let image = ImageRef { width, height, layout: Layout::Rgb, samples: Samples::F32(&samples) }; + for lossless in [false, true] { + let encoded = + encode(&image, EncodeOptions { lossless, quality: 95, colour: JxlColour::Rec2020Pq, ..EncodeOptions::default() }, &Metadata::default()); + assert!(encoded.is_ok(), "HDR image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + let decoded = jxl_oxide::JxlImage::builder().read(encoded.as_slice()); + assert!(decoded.is_ok(), "reference decoder should read HDR output: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + let metadata = &decoded.image_header().metadata; + assert_eq!(metadata.tone_mapping.intensity_target, 10_000.0); + assert!(format!("{:?}", metadata.colour_encoding).contains("Pq"), "{:?}", metadata.colour_encoding); + let frame = decoded.render_frame(0); + assert!(frame.is_ok(), "reference decoder should render HDR output: {frame:?}"); + let Ok(frame) = frame else { return }; + let buffer = frame.image_all_channels(); + let channels = buffer.channels(); + assert!(channels >= 3); + let sample_at = |x: usize| buffer.buf()[((height as usize / 2) * width as usize + x) * channels + 1]; + for (x, nits) in [(width as usize / 4, HDR_REFERENCE_WHITE_NITS), (width as usize * 3 / 4, 4.0 * HDR_REFERENCE_WHITE_NITS)] { + let encoded_pq = pq_encode(nits); + let actual = sample_at(x); + assert!((actual - encoded_pq).abs() < 0.005, "lossless={lossless}: {nits} nits encoded as {actual}, expected {encoded_pq}"); + } + } + assert!(matches!(encode(&image, EncodeOptions::default(), &Metadata::default()), Err(craft_jxl::Error::InvalidImage(_)))); +} + +fn pq_encode(nits: f32) -> f32 { + const M1: f32 = 2610.0 / 16384.0; + const M2: f32 = 2523.0 / 4096.0 * 128.0; + const C1: f32 = 3424.0 / 4096.0; + const C2: f32 = 2413.0 / 4096.0 * 32.0; + const C3: f32 = 2392.0 / 4096.0 * 32.0; + let y = (nits / 10_000.0).clamp(0.0, 1.0).powf(M1); + ((C1 + C2 * y) / (1.0 + C3 * y)).powf(M2) +} + +#[test] +fn bounded_feeds_keep_metadata_after_the_final_progressive_part() { + let samples: Vec<u8> = (0..8 * 8 * 4).map(|i| (i * 13 % 256) as u8).collect(); + let image = ImageRef { width: 8, height: 8, layout: Layout::Rgba, samples: Samples::U8(&samples) }; + let encoded = encode(&image, EncodeOptions { lossless: true, progressive: true, ..EncodeOptions::default() }, &Metadata::default()); + assert!(encoded.is_ok(), "valid image should encode: {encoded:?}"); + let Ok(encoded) = encoded else { return }; + let raw = raw_codestream(&encoded); + assert!(raw.starts_with(b"\xff\x0a"), "extract the JXL codestream from the encoder output"); + + let mut bytes = b"\0\0\0\x0cJXL \x0d\x0a\x87\x0a".to_vec(); + box_bytes(&mut bytes, b"ftyp", b"jxl \0\0\0\0jxl "); + let split = raw.len() / 2; + let mut part = 0_u32.to_be_bytes().to_vec(); + part.extend_from_slice(&raw[..split]); + box_bytes(&mut bytes, b"jxlp", &part); + let padding = vec![0; 4096usize.saturating_sub(bytes.len() + 8)]; + box_bytes(&mut bytes, b"free", &padding); + let mut part = 0x8000_0001_u32.to_be_bytes().to_vec(); + part.extend_from_slice(&raw[split..]); + box_bytes(&mut bytes, b"jxlp", &part); + let exif = b"II*\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x01\0\0\0\0\0\0\0"; + let mut exif_box = vec![0; 4]; + exif_box.extend_from_slice(exif); + box_bytes(&mut bytes, b"Exif", &exif_box); + let xmp = b"<xmp/>"; + box_bytes(&mut bytes, b"xml ", xmp); + assert!(bytes.len() < 8192, "metadata fixture should fit in two decoder feeds"); + + let reference = jxl_oxide::JxlImage::builder().read(bytes.as_slice()); + assert!(reference.is_ok(), "reference decoder should read the fixture: {reference:?}"); + let Ok(reference) = reference else { return }; + let reference_exif = match reference.aux_boxes().first_exif() { + Ok(jxl_oxide::AuxBoxData::Data(data)) => Some(data.payload().to_vec()), + _ => None, + }; + let reference_xmp = match reference.aux_boxes().first_xml() { + jxl_oxide::AuxBoxData::Data(data) => Some(data.to_vec()), + _ => None, + }; + assert!(reference_exif.is_some(), "reference decoder should preserve the Exif box"); + assert!(reference_xmp.is_some(), "reference decoder should preserve the XMP box"); + let (Some(reference_exif), Some(reference_xmp)) = (reference_exif, reference_xmp) else { return }; + let decoded = decode(&bytes, DecodeLimits::default()); + assert!(decoded.is_ok(), "shared decoder should read the fixture: {decoded:?}"); + let Ok(decoded) = decoded else { return }; + assert_eq!(decoded.metadata.exif.as_deref(), Some(reference_exif.as_slice())); + assert_eq!(decoded.metadata.xmp.as_deref(), Some(reference_xmp.as_slice())); +} diff --git a/crates/kra/README.md b/crates/kra/README.md index 363455bdf..582a0117d 100644 --- a/crates/kra/README.md +++ b/crates/kra/README.md @@ -31,6 +31,7 @@ here. There is no writer. | `<layer>` nodes | 8192 (`MAX_NODES`) | | `maindoc.xml` | 32 MiB, 512 levels of nesting, no internal DTD subset | | A pixel file, inflated | 1 GiB (`MAX_LAYER_FILE`) | +| All entries read from one archive | 4 GiB (`MAX_TOTAL`) | | ICC profile | 16 MiB | | Tile | 1024 × 1024 px, 64 bytes per pixel, header lines of 256 bytes | diff --git a/crates/kra/src/lib.rs b/crates/kra/src/lib.rs index 12ae3468b..e2dfb1f64 100644 --- a/crates/kra/src/lib.rs +++ b/crates/kra/src/lib.rs @@ -56,6 +56,10 @@ pub const MAX_MAINDOC: usize = 32 << 20; pub const MAX_LAYER_FILE: usize = 1 << 30; /// Most entries the archive may declare; checked before the archive is indexed. pub const MAX_ENTRIES: u64 = 100_000; +/// Most bytes all the entries read from one archive may expand to together. Each pixel file may be +/// [`MAX_LAYER_FILE`] on its own, so without a total a document of many layers could spend far more +/// than one open should. +pub const MAX_TOTAL: u64 = 4 << 30; /// Largest ICC profile. pub const MAX_ICC: usize = 16 << 20; /// Deepest element nesting of `maindoc.xml`. @@ -247,7 +251,10 @@ impl Image { limits: craft_xml::Limits { max_input: MAX_MAINDOC, max_depth: MAX_XML_DEPTH, ..craft_xml::Limits::DEFAULT }, ..craft_xml::Options::local().strict() }; - let root = options.parse(maindoc).map_err(|e| invalid(format!("maindoc.xml: {e}")))?; + let root = options.parse(maindoc).map_err(|e| match e { + craft_xml::Error::Doctype => invalid("maindoc.xml: a document type with an internal DTD subset is not accepted"), + other => invalid(format!("maindoc.xml: {other}")), + })?; let image = root.child("IMAGE").ok_or_else(|| invalid("maindoc.xml has no IMAGE"))?; let side = |a: &str| -> Result<u32> { let v = number(image, a, 0.0)?; @@ -284,8 +291,13 @@ pub struct Archive<'a> { impl<'a> Archive<'a> { /// Opens the archive, checks its `mimetype` and reads `maindoc.xml`. pub fn open(bytes: &'a [u8]) -> Result<Archive<'a>> { - let mut zip = - craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes: u64::MAX }).map_err(zip_error)?; + Self::open_with(bytes, craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes: MAX_TOTAL }) + } + + /// [`Archive::open`] with explicit zip limits, so a test can set a small document-wide total + /// ([`MAX_TOTAL`] is what [`Archive::open`] passes). + pub(crate) fn open_with(bytes: &'a [u8], limits: craft_zip::Limits) -> Result<Archive<'a>> { + let mut zip = craft_zip::Archive::open(bytes, limits).map_err(zip_error)?; // `zip` keeps one entry of a repeated name; which one the writer meant is not known. if zip.has_duplicate_names() { return Err(invalid("two entries of the archive share a name")); diff --git a/crates/kra/src/tests.rs b/crates/kra/src/tests.rs index 31656e4e1..b6dfd4b72 100644 --- a/crates/kra/src/tests.rs +++ b/crates/kra/src/tests.rs @@ -386,6 +386,23 @@ fn an_archive_declaring_too_many_entries_is_refused_before_it_is_indexed() { ); } +/// Every entry read is charged to one document-wide total: each pixel file may be +/// [`MAX_LAYER_FILE`] on its own, but a document with many of them still has one budget. +#[test] +fn pixel_files_share_one_document_wide_budget() { + let doc = maindoc("RGBA", ""); + // `layer_file("x")` reads `<image name>/layers/x`. + let (first, second) = ("img/layers/x", "img/layers/y"); + let files: Vec<(&str, Vec<u8>)> = vec![(first, vec![3; 64]), (second, vec![4; 64])]; + let bytes = archive(&doc, &files); + // The mimetype and maindoc reads are charged too: room for one 64-byte pixel file and 16 bytes. + let total = doc.len() as u64 + MIMETYPE.len() as u64 + 64 + 16; + let limits = craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes: total }; + let mut archive = Archive::open_with(&bytes, limits).unwrap(); + assert_eq!(archive.layer_file("x").unwrap().unwrap(), vec![3; 64]); + assert!(matches!(archive.layer_file("y"), Err(Error::Invalid(_))), "the second pixel file is past the total"); +} + /// Two entries of one name: `zip` keeps one, and which one the writer meant is not known. #[test] fn two_entries_of_one_name_are_refused() { diff --git a/crates/lottie/Cargo.toml b/crates/lottie/Cargo.toml index 0d934843c..945be4d54 100644 --- a/crates/lottie/Cargo.toml +++ b/crates/lottie/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-lottie" -description = "Lottie (Bodymovin) JSON: the lottie-spec 1.0 document model with a bounded reader and a writer, animated properties and their keyframes, ease tangents, bezier paths, gradients, value coercions and embedded image data URIs" +description = "Lottie (Bodymovin) JSON and dotLottie ZIP containers: the lottie-spec 1.0 document model, bounded readers and writers, animated properties, keyframes, ease tangents, bezier paths, gradients, value coercions and embedded image data URIs" version.workspace = true edition.workspace = true license.workspace = true @@ -11,5 +11,6 @@ repository.workspace = true workspace = true [dependencies] +craft-zip = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/lottie/src/lib.rs b/crates/lottie/src/lib.rs index 569063ebf..16c1c6e07 100644 --- a/crates/lottie/src/lib.rs +++ b/crates/lottie/src/lib.rs @@ -15,8 +15,8 @@ //! LottieFiles format documentation); no player or exporter source was used. //! //! Which layer, shape, effect and text feature maps to what in an application's document is the -//! application's work. dotLottie (`.lottie`) is a ZIP archive around the same JSON and is not -//! read here. +//! application's work. [`zip`] reads and writes the stored-entry ZIP container used by dotLottie; +//! selecting its manifest and mapping it to this document model remains the application's work. // The test documents are large `json!` literals. #![cfg_attr(test, recursion_limit = "512")] @@ -28,6 +28,7 @@ pub mod model; mod path; mod prop; mod value; +pub mod zip; pub use gradient::Gradient; pub use model::{Animated, Animation, Layer, LayerContent, Limits, Shape, ShapeKind}; diff --git a/crates/lottie/src/zip.rs b/crates/lottie/src/zip.rs new file mode 100644 index 000000000..05ebe0b70 --- /dev/null +++ b/crates/lottie/src/zip.rs @@ -0,0 +1,151 @@ +//! Bounded ZIP handling for dotLottie archives. +//! +//! The ZIP implementation delegates to `craft-zip`; this module applies dotLottie's relative +//! entry-name rule and caps archive expansion before returning entry bytes. + +use craft_zip::{Archive, Error, Writer}; +pub use craft_zip::{Compression, Limits}; + +/// Largest entry count accepted from a dotLottie archive. +pub const MAX_ENTRIES: u64 = 10_000; +/// Largest combined uncompressed payload returned from a dotLottie archive. +pub const MAX_TOTAL_BYTES: u64 = 1 << 30; + +/// Whether an entry name is a relative path inside the archive: not absolute (`/…`, `\\…`), no +/// drive (`C:…`) and no `..` component. +fn is_relative_name(name: &str) -> bool { + let drive = name.as_bytes().get(1) == Some(&b':'); + !name.starts_with(['/', '\\']) && !drive && !name.split(['/', '\\']).any(|c| c == "..") +} + +/// Read files from a dotLottie ZIP archive within [`MAX_ENTRIES`] and [`MAX_TOTAL_BYTES`]. +/// +/// Both stored and deflated entries are supported. Directories and names that escape the archive +/// root are skipped. Duplicate names and overlapping payloads are rejected because a consumer +/// must not guess which content a manifest or animation name identifies. +pub fn read_entries(data: &[u8]) -> Result<Vec<(String, Vec<u8>)>, Error> { + read_entries_with_limits(data, Limits { max_entries: MAX_ENTRIES, max_total_bytes: MAX_TOTAL_BYTES }) +} + +/// Read a dotLottie archive under caller-provided entry and expansion limits. +pub fn read_entries_with_limits(data: &[u8], limits: Limits) -> Result<Vec<(String, Vec<u8>)>, Error> { + let mut archive = Archive::open(data, limits)?; + if archive.has_duplicate_names() || archive.has_overlapping_files()? { + return Err(Error::NotZip("duplicate names or overlapping entry data".into())); + } + let mut out = Vec::new(); + for index in 0..archive.len() { + let (Some(name), Some(is_dir)) = (archive.entry_name(index)?, archive.entry_is_dir(index)?) else { continue }; + if is_dir || !is_relative_name(&name) { + continue; + } + if let Some(bytes) = archive.read(&name, limits.max_total_bytes)? { + out.push((name, bytes)); + } + } + Ok(out) +} + +/// Read the stored local-file entries in a ZIP written by [`store`]. This compatibility reader +/// retains its original behavior: compressed entries are skipped, an incomplete trailing entry +/// stops the walk while already-read entries are returned, and unsafe names are skipped. New code +/// should use [`read_entries`] for central-directory validation and deflate support. +pub fn read_stored(data: &[u8]) -> Vec<(String, Vec<u8>)> { + let u16_at = |p: usize| p.checked_add(2).and_then(|e| data.get(p..e)).map(|b| u16::from_le_bytes([b[0], b[1]]) as usize); + let u32_at = |p: usize| p.checked_add(4).and_then(|e| data.get(p..e)).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize); + let mut out = Vec::new(); + let mut i = 0usize; + while u32_at(i) == Some(0x0403_4b50) { + let (Some(method), Some(size), Some(nlen), Some(xlen)) = ( + i.checked_add(8).and_then(u16_at), + i.checked_add(18).and_then(u32_at), + i.checked_add(26).and_then(u16_at), + i.checked_add(28).and_then(u16_at), + ) else { + break; + }; + let Some(name_start) = i.checked_add(30) else { break }; + let Some(name_end) = name_start.checked_add(nlen) else { break }; + let Some(body) = name_end.checked_add(xlen) else { break }; + let Some(body_end) = body.checked_add(size) else { break }; + let (Some(name), Some(bytes)) = (data.get(name_start..name_end), data.get(body..body_end)) else { break }; + let name = String::from_utf8_lossy(name).to_string(); + if method == 0 && is_relative_name(&name) { + out.push((name, bytes.to_vec())); + } + i = body_end; + } + out +} + +/// Write ZIP entries uncompressed, preserving input order and the legacy deterministic timestamp. +pub fn try_store(entries: &[(String, Vec<u8>)]) -> Result<Vec<u8>, Error> { + try_store_with_compression(entries, Compression::Stored) +} + +/// Write entries using the selected shared ZIP compression mode. +pub fn try_store_with_compression(entries: &[(String, Vec<u8>)], compression: Compression) -> Result<Vec<u8>, Error> { + let mut writer = Writer::legacy_utf8(); + for (name, bytes) in entries { + writer.add(name, bytes, compression)?; + } + writer.finish() +} + +/// Compatibility wrapper for the original infallible writer API. Use [`try_store`] when the +/// caller needs an actionable error for an invalid or unrepresentable archive. +pub fn store(entries: &[(String, Vec<u8>)]) -> Vec<u8> { + try_store(entries).unwrap_or_default() +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::*; + + #[test] + fn stored_writer_roundtrips_and_keeps_entry_order() { + let entries = [("a.json".into(), b"{}".to_vec()), ("b/c.txt".into(), b"hello".to_vec())]; + let bytes = try_store(&entries).unwrap(); + assert_eq!(read_entries(&bytes).unwrap(), entries); + assert_eq!(bytes, store(&entries)); + } + + #[test] + fn deflated_entries_are_read_and_path_traversal_is_skipped() { + let mut writer = Writer::new(); + writer.add("animations/main.json", br#"{"w":1,"h":1}"#, Compression::Deflated).unwrap(); + writer.add("../outside.json", b"{}", Compression::Deflated).unwrap(); + let bytes = writer.finish().unwrap(); + assert_eq!(read_entries(&bytes).unwrap(), [("animations/main.json".into(), br#"{"w":1,"h":1}"#.to_vec())]); + assert!(read_entries_with_limits(&bytes, Limits { max_entries: 10, max_total_bytes: 4 }).is_err()); + } + + #[test] + fn malformed_and_truncated_archives_return_errors_without_panicking() { + let mut hostile = vec![0; 30]; + hostile[..4].copy_from_slice(&0x0403_4b50u32.to_le_bytes()); + hostile[8..10].copy_from_slice(&0u16.to_le_bytes()); + hostile[18..22].copy_from_slice(&u32::MAX.to_le_bytes()); + hostile[26..28].copy_from_slice(&u16::MAX.to_le_bytes()); + hostile[28..30].copy_from_slice(&u16::MAX.to_le_bytes()); + assert!(read_entries(&hostile).is_err()); + for end in 0..hostile.len() { + let _ = read_entries(&hostile[..end]); + } + } + + #[test] + fn legacy_stored_archive_bytes_and_partial_tail_are_compatible() { + const HEX: &str = "504b03041400000800000000210043bfa6a3020000000200000006000000612e6a736f6e7b7d504b03041400000800000000210086a61036050000000500000007000000622f632e74787468656c6c6f504b010214001400000800000000210043bfa6a30200000002000000060000000000000000000000000000000000612e6a736f6e504b010214001400000800000000210086a610360500000005000000070000000000000000000000000026000000622f632e747874504b0506000000000200020069000000500000000000"; + let legacy: Vec<u8> = HEX.as_bytes().chunks(2).map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap()).collect(); + let entries = [("a.json".into(), b"{}".to_vec()), ("b/c.txt".into(), b"hello".to_vec())]; + assert_eq!(read_stored(&legacy), entries); + assert_eq!(read_entries(&legacy).unwrap(), entries); + assert_eq!(try_store(&entries).unwrap(), legacy); + let partial = &legacy[..50]; + assert_eq!(read_stored(partial), [("a.json".into(), b"{}".to_vec())]); + assert!(read_entries(partial).is_err()); + } +} diff --git a/crates/materialx/src/lib.rs b/crates/materialx/src/lib.rs index d60db3eef..99701366f 100644 --- a/crates/materialx/src/lib.rs +++ b/crates/materialx/src/lib.rs @@ -183,7 +183,14 @@ const OPENPBR_WRITABLE: &[(&str, InputKind)] = &[ impl Document { /// Parses a MaterialX document while enforcing size, nesting and node-count limits. pub fn parse(bytes: &[u8]) -> Result<Self, Error> { - let limits = Limits { max_input: MAX_BYTES, max_depth: MAX_DEPTH, max_nodes: MAX_NODES, max_attrs: 256, max_attrs_total: 400_000 }; + let limits = Limits { + max_input: MAX_BYTES, + max_depth: MAX_DEPTH, + max_nodes: MAX_NODES, + max_elements: MAX_NODES, + max_attrs: 256, + max_attrs_total: 400_000, + }; let options = Options { doctype: Doctype::Reject, unknown_entity: UnknownEntity::Error, @@ -320,7 +327,13 @@ impl Document { .and_then(|i| i.attr("nodename")) .and_then(|n| nodes.get(n).copied()) .and_then(|d| d.children("input").find(|i| i.attr("name") == Some("displacement"))) - .and_then(|i| resolve_value(&self.root, i, None, &nodes, &outputs, 0, &mut warnings).map(|f| f.value)); + .and_then(|i| resolve_value(&self.root, i, None, &nodes, &outputs, 0, &mut warnings)) + .map(|found| { + if tiling.is_none() { + tiling = found.tiling; + } + found.value + }); Ok(Material { name: mat.attr("name").unwrap_or("Material").to_owned(), shader: kind, @@ -545,6 +558,19 @@ mod tests { assert!(matches!(Document::parse(&vec![b' '; MAX_BYTES + 1]), Err(Error::Xml(XmlError::TooLarge(_))))); } + #[test] + fn displacement_image_supplies_tiling_when_surface_inputs_do_not() { + let xml = br#"<materialx> + <open_pbr_surface name="S"><input name="base_color" value="0.3,0.4,0.5"/></open_pbr_surface> + <tiledimage name="H"><input name="file" value="height.png"/><input name="uvtiling" value="4,2"/></tiledimage> + <displacement name="D"><input name="displacement" nodename="H"/></displacement> + <surfacematerial name="M"><input name="surfaceshader" nodename="S"/><input name="displacementshader" nodename="D"/></surfacematerial> + </materialx>"#; + let material = Document::parse(xml).unwrap().read_material(None).unwrap(); + assert_eq!(material.displacement, Some(Value::Image("height.png".into()))); + assert_eq!(material.uv_tiling, [4.0, 2.0]); + } + #[test] fn resolves_openpbr_values_images_graphs_and_displacement() { let doc = Document::parse(br#"<materialx fileprefix="tex/"> diff --git a/crates/mcmat/Cargo.toml b/crates/mcmat/Cargo.toml new file mode 100644 index 000000000..ee3a18626 --- /dev/null +++ b/crates/mcmat/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-mcmat" +description = "Bounded portable material archive interchange for Craft applications" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-zip = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/mcmat/README.md b/crates/mcmat/README.md new file mode 100644 index 000000000..074a0ac44 --- /dev/null +++ b/crates/mcmat/README.md @@ -0,0 +1,17 @@ +# craft-mcmat + +A bounded reader and writer for portable MaterialCraft `.mcmat` ZIP packages. A package +contains `material.json`, named texture maps and a source package. Applications interpret +parameter values and cook or render maps themselves; this crate does not depend on an app's +model. It supports callers that read either version 1 or version 2 of the manifest, or both. + +`is_material` checks for a manifest with a bounded ZIP index; `Material::open` takes caller-provided version, entry-count, map-count, per-entry and total +expanded-byte limits. Each subsequent `read` and `read_source` shares that budget, including +repeated references to the same ZIP member. Duplicate member names are refused. The manifest +preserves unknown fields at the top level and on maps; parameter, input and preset objects are +kept as JSON values so their unknown fields survive too. `write` preserves the caller's source +entry name and map names, and rejects duplicate archive member names through `craft-zip`. + +The source package is opaque. Version 1 commonly names `source.mcraft`; MaterialCraft's version 2 +writer names `source.sbs`. Callers that invoke another application must preserve the source's +format and extension rather than infer it from `.mcmat` alone. diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs new file mode 100644 index 000000000..75b8709ef --- /dev/null +++ b/crates/mcmat/src/lib.rs @@ -0,0 +1,216 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Bounded interchange for MaterialCraft portable materials (`.mcmat`). +//! +//! The manifest and its version belong to the format, while interpreting parameter values, +//! cooking maps and opening the source package belong to the caller. Unknown fields survive +//! deserialization and serialization, including fields added by later versions. + +use std::collections::BTreeMap; + +use craft_zip::{Archive, Compression, Writer}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +pub const FORMAT: &str = "craft-material"; +pub const MANIFEST_ENTRY: &str = "material.json"; + +/// A portable manifest; typed parameter values remain JSON so applications can adapt their own model. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Manifest { + pub format: String, + pub version: u32, + pub name: String, + pub graph: String, + pub size: [u32; 2], + pub maps: Vec<MapEntry>, + #[serde(default)] + pub parameters: Vec<Value>, + #[serde(default)] + pub inputs: Vec<Value>, + #[serde(default)] + pub presets: Vec<Value>, + pub source: String, + #[serde(flatten)] + pub extra: BTreeMap<String, Value>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MapEntry { + pub usage: String, + pub file: String, + #[serde(flatten)] + pub extra: BTreeMap<String, Value>, +} + +/// All limits are supplied by the consumer, including the versions it understands. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + pub min_version: u32, + pub max_version: u32, + pub max_entries: u64, + pub max_maps: usize, + pub max_manifest_bytes: u64, + pub max_entry_bytes: u64, + pub max_total_bytes: u64, +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid portable material: {0}")] + Invalid(String), + #[error("unsupported portable material version {0}")] + Version(u32), + #[error("portable material limit: {0}")] + Limit(String), + #[error("portable material archive: {0}")] + Archive(#[from] craft_zip::Error), +} + +/// Whether a bounded ZIP index contains a material manifest. This does not validate the manifest. +pub fn is_material(bytes: &[u8], max_entries: u64) -> bool { + Archive::open(bytes, craft_zip::Limits { max_entries, max_total_bytes: 0 }) + .is_ok_and(|archive| !archive.has_duplicate_names() && archive.contains(MANIFEST_ENTRY)) +} + +/// Manifest and original archive, retaining one shared expanded-byte budget across reads. +pub struct Material<'a> { + pub manifest: Manifest, + archive: Archive<'a>, + max_entry_bytes: u64, +} + +impl<'a> Material<'a> { + pub fn open(bytes: &'a [u8], limits: Limits) -> Result<Self, Error> { + let mut archive = Archive::open(bytes, craft_zip::Limits { max_entries: limits.max_entries, max_total_bytes: limits.max_total_bytes })?; + if archive.has_duplicate_names() { + return Err(Error::Invalid("duplicate archive entries".into())); + } + let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("material.json is missing".into()))?; + let manifest: Manifest = serde_json::from_slice(&json).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; + if manifest.format != FORMAT { + return Err(Error::Invalid(format!("format `{}`", manifest.format))); + } + if !(limits.min_version..=limits.max_version).contains(&manifest.version) { + return Err(Error::Version(manifest.version)); + } + if manifest.maps.len() > limits.max_maps { + return Err(Error::Limit(format!("{} maps exceeds {}", manifest.maps.len(), limits.max_maps))); + } + Ok(Self { manifest, archive, max_entry_bytes: limits.max_entry_bytes }) + } + + /// Read one named member, charging it to the same budget as previous reads. + pub fn read(&mut self, name: &str) -> Result<Vec<u8>, Error> { + self.archive.read(name, self.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("{name} is missing"))) + } + + pub fn read_source(&mut self) -> Result<Vec<u8>, Error> { + self.read(&self.manifest.source.clone()) + } +} + +/// Write a manifest, its named maps, and the source. Duplicate member names are rejected. +pub fn write(manifest: &Manifest, maps: &[(String, Vec<u8>)], source: &[u8]) -> Result<Vec<u8>, Error> { + // Flattened fields must not serialize a second copy of a known key. + const KNOWN: &[&str] = &["format", "version", "name", "graph", "size", "maps", "parameters", "inputs", "presets", "source"]; + if manifest.extra.keys().any(|key| KNOWN.contains(&key.as_str())) + || manifest.maps.iter().any(|map| map.extra.contains_key("usage") || map.extra.contains_key("file")) + { + return Err(Error::Invalid("an extra field duplicates a known field".into())); + } + let json = serde_json::to_vec_pretty(manifest).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; + let mut writer = Writer::new(); + writer.add(MANIFEST_ENTRY, &json, Compression::Deflated)?; + for (name, bytes) in maps { + writer.add(name, bytes, Compression::Stored)?; + } + writer.add(&manifest.source, source, Compression::Stored)?; + Ok(writer.finish()?) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn limits() -> Limits { + Limits { + min_version: 1, + max_version: 2, + max_entries: 100, + max_maps: 4, + max_manifest_bytes: 4096, + max_entry_bytes: 100, + max_total_bytes: 8192, + } + } + + fn sample(version: u32) -> Manifest { + serde_json::from_value(serde_json::json!({ + "format": "craft-material", "version": version, "name": "Stone", "graph": "Stone", "size": [64, 64], + "maps": [{"usage": "baseColor", "file": "maps/base.png", "colorSpace": "srgb", "futureMap": true}], + "parameters": [{"id": "rough", "value": {"t": "float", "v": 0.25}, "futureParam": 42}], + "inputs": [{"identifier": "curvature", "kind": "gray"}], "presets": [], + "source": if version == 1 { "source.mcraft" } else { "source.sbs" }, "futureField": {"keep": true} + })) + .unwrap() + } + + #[test] + fn both_protocol_versions_keep_unknown_fields_and_payloads() { + for version in [1, 2] { + let manifest = sample(version); + let bytes = write(&manifest, &[("maps/base.png".into(), vec![1, 2, 3])], b"source").unwrap(); + assert!(is_material(&bytes, 100)); + assert!(!is_material(&bytes, 1)); + let mut material = Material::open(&bytes, limits()).unwrap(); + assert_eq!(material.manifest, manifest); + assert_eq!(material.read("maps/base.png").unwrap(), [1, 2, 3]); + assert_eq!(material.read_source().unwrap(), b"source"); + let json = serde_json::to_value(&material.manifest).unwrap(); + assert_eq!(json["futureField"]["keep"], true); + assert_eq!(json["maps"][0]["futureMap"], true); + assert_eq!(json["parameters"][0]["futureParam"], 42); + } + } + + #[test] + fn limits_apply_to_the_manifest_maps_and_aggregate_reads() { + let manifest = sample(2); + let bytes = write(&manifest, &[("maps/base.png".into(), vec![1; 8])], &[2; 8]).unwrap(); + let mut unsupported = limits(); + unsupported.max_version = 1; + assert!(matches!(Material::open(&bytes, unsupported), Err(Error::Version(2)))); + let mut no_maps = limits(); + no_maps.max_maps = 0; + assert!(matches!(Material::open(&bytes, no_maps), Err(Error::Limit(_)))); + let mut tiny_entry = limits(); + tiny_entry.max_entry_bytes = 7; + assert!(Material::open(&bytes, tiny_entry).unwrap().read("maps/base.png").is_err()); + let json_len = serde_json::to_vec_pretty(&manifest).unwrap().len() as u64; + let mut aggregate = limits(); + aggregate.max_total_bytes = json_len + 15; + let mut material = Material::open(&bytes, aggregate).unwrap(); + assert_eq!(material.read("maps/base.png").unwrap().len(), 8); + assert!(material.read_source().is_err()); + } + + #[test] + fn refuses_extra_fields_that_duplicate_known_keys() { + let mut manifest = sample(2); + manifest.extra.insert("version".into(), 3.into()); + assert!(write(&manifest, &[], b"source").is_err()); + manifest.extra.remove("version"); + manifest.maps[0].extra.insert("file".into(), "other".into()); + assert!(write(&manifest, &[], b"source").is_err()); + } + + #[test] + fn refuses_duplicate_names_on_write() { + let manifest = sample(2); + let duplicate = [("maps/base.png".to_string(), vec![1]), ("maps/base.png".to_string(), vec![2])]; + assert!(write(&manifest, &duplicate, b"source").is_err()); + } +} diff --git a/crates/media/README.md b/crates/media/README.md index 8eca6ecb5..b7ad5be7a 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -243,6 +243,10 @@ let bytes = w.finish_faststart()?.into_inner(); // or finish() for moov-at-end `ipcm`/`fpcm` + `pcmC` in MP4. A PCM `write_sample` call can hold any whole number of frames, and the track timescale must equal the sample rate. - Edit lists: set `TrackConfig::edits` explicitly, or use `media_start` to get a single edit. +- Audio pre-roll: `TrackConfig::roll_distance` puts every sample in a `roll` sample group (`sgpd` + + `sbgp`). Set -1 for AAC with `media_start` at the priming: Apple's decoders apply that edit only + when the track has the group. +- A file starts at the writer's position: chunk offsets count from there. - Timecode: `add_timecode_track(video, TimecodeConfig, start_frame)` adds a `tmcd` track (with `gmhd`) and a `tref/tmcd` link from the video track. - `WriterOptions::metadata` writes `©xxx` text atoms to `udta`. diff --git a/crates/media/src/isobmff/mux.rs b/crates/media/src/isobmff/mux.rs index e38186e9f..bcadfbaeb 100644 --- a/crates/media/src/isobmff/mux.rs +++ b/crates/media/src/isobmff/mux.rs @@ -51,11 +51,17 @@ pub struct TrackConfig { pub media_start: Option<i64>, /// `hdlr` name; a sensible default is used when `None`. pub handler_name: Option<String>, + /// Audio pre-roll: puts every sample in a `roll` sample group (`sgpd` + `sbgp`, ISO/IEC + /// 14496-12 §10.1) with this roll distance, the number of samples a decoder must decode before + /// (negative) a sample for its output to be correct; -1 for AAC. Apple's decoders take an AAC + /// track's priming from the edit list only when the track has this group. Written by + /// [`Mp4Writer`]; [`FragmentedWriter`] ignores it. + pub roll_distance: Option<i16>, } impl TrackConfig { pub fn new(entry: SampleEntry, timescale: u32) -> Self { - TrackConfig { entry, timescale, language: "und".into(), edits: Vec::new(), media_start: None, handler_name: None } + TrackConfig { entry, timescale, language: "und".into(), edits: Vec::new(), media_start: None, handler_name: None, roll_distance: None } } } @@ -543,6 +549,23 @@ fn write_stbl(b: &mut BoxBuf, t: &WTrack, qt: bool, shift: u64, force_co64: bool } } b.end(m); + if let Some(distance) = t.cfg.roll_distance + && sample_count > 0 + { + // One description, which every sample maps to. + let m = b.start_full(b"sgpd", 1, 0); + b.bytes(b"roll"); + b.u32(2); + b.u32(1); + b.i16(distance); + b.end(m); + let m = b.start_full(b"sbgp", 0, 0); + b.bytes(b"roll"); + b.u32(1); + b.u32(sample_count); + b.u32(1); + b.end(m); + } b.end(stbl); Ok(()) } @@ -592,12 +615,21 @@ fn validate_track(entry: &SampleEntry, timescale: u32) -> Result<Option<u32>> { Ok(None) } +/// The position after `bytes` more. A writer that takes bytes past the last position a file can +/// have is an error here, not an overflow. +fn advance(pos: u64, bytes: usize) -> Result<u64> { + pos.checked_add(bytes as u64).ok_or_else(|| Error::Mux("the file would end past the last position".into())) +} + /// Progressive MP4/MOV writer: `ftyp`, then one `mdat` streamed to `W`, then `moov` at [`finish`](Self::finish) /// (or moved in front of `mdat` by [`finish_faststart`](Self::finish_faststart)). pub struct Mp4Writer<W: Write + Seek> { w: W, opts: WriterOptions, tracks: Vec<WTrack>, + /// The writer's position when the file was begun: chunk offsets count from here, the first + /// byte of the file, wherever in the writer that is. + start: u64, /// Offset of the placeholder box (8 bytes) preceding the mdat header. pad_pos: u64, mdat_pos: u64, @@ -608,18 +640,22 @@ pub struct Mp4Writer<W: Write + Seek> { } impl<W: Write + Seek> Mp4Writer<W> { - /// Start a file: writes `ftyp`, a placeholder box and the `mdat` header. + /// Start a file at the writer's current position: writes `ftyp`, a placeholder box and the + /// `mdat` header. pub fn new(mut w: W, opts: WriterOptions) -> Result<Self> { let start = w.stream_position()?; let mut b = BoxBuf::new(); write_ftyp(&mut b, opts.brand); - let pad_pos = start + b.len() as u64; + let pad = b.len() as u64; b.leaf(if opts.brand == Brand::Mov { b"wide" } else { b"free" }, &[]); - let mdat_pos = start + b.len() as u64; + let mdat = b.len() as u64; b.leaf(b"mdat", &[]); + // A writer positioned at the very end of what a position can count has no room for the + // header; the positions below are sums that would overflow. + let pos = start.checked_add(b.len() as u64).ok_or_else(|| Error::Mux("the writer's position leaves no room for a file".into()))?; + let (pad_pos, mdat_pos) = (start + pad, start + mdat); w.write_all(&b.buf)?; - let pos = start + b.len() as u64; - Ok(Mp4Writer { w, opts, tracks: Vec::new(), pad_pos, mdat_pos, pos, last_track: None, chapters: Vec::new() }) + Ok(Mp4Writer { w, opts, tracks: Vec::new(), start, pad_pos, mdat_pos, pos, last_track: None, chapters: Vec::new() }) } /// Add a track; returns its index (track ids are index + 1). @@ -708,8 +744,8 @@ impl<W: Write + Seek> Mp4Writer<W> { return Err(too_many_samples()); } self.w.write_all(s.data)?; - let offset = self.pos; - self.pos += s.data.len() as u64; + let offset = self.pos - self.start; + self.pos = advance(self.pos, s.data.len())?; let contiguous = self.last_track == Some(track); self.last_track = Some(track); let tr = &mut self.tracks[track]; @@ -749,8 +785,8 @@ impl<W: Write + Seek> Mp4Writer<W> { }; let d = rescale(vd, vts, tts).max(tc_dur as u64).min(u32::MAX as u64) as u32; self.w.write_all(&start.to_be_bytes())?; - let off = self.pos; - self.pos += 4; + let off = self.pos - self.start; + self.pos = advance(self.pos, 4)?; self.last_track = None; let t = &mut self.tracks[i].t; t.stts.push((1, d)); @@ -807,13 +843,13 @@ impl<W: Write + Seek> Mp4Writer<W> { } let id = self.tracks.len() as u32 + 1; let mut t = Tables::new(); - let off = self.pos; + let off = self.pos - self.start; for (i, c) in self.chapters.iter().enumerate() { let end = self.chapters.get(i + 1).map_or(duration, |n| n.start); let d = u32::try_from(end.saturating_sub(c.start)).map_err(|_| Error::Mux("chapter longer than 2^32 movie ticks".into()))?; let data = text_sample(&c.title); self.w.write_all(&data)?; - self.pos += data.len() as u64; + self.pos = advance(self.pos, data.len())?; Tables::push_run(&mut t.stts, 1, d); Tables::push_run(&mut t.ctts, 1, 0); t.sizes.push(data.len() as u32); @@ -1341,4 +1377,105 @@ mod tests { } assert_eq!(t.sync_sample_before(5), 3); } + + /// `roll_distance` puts every sample in one `roll` group; without it, or without samples, + /// the track has no sample group. + #[test] + fn roll_distance_is_a_sample_group_over_every_sample() { + let file = |roll: Option<i16>, samples: u32| { + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap(); + let mut cfg = TrackConfig::new(SampleEntry::aac(vec![0x11, 0x90], 2, 48_000), 48_000); + cfg.roll_distance = roll; + let t = w.add_track(cfg).unwrap(); + for _ in 0..samples { + w.write_sample(t, WriteSample { data: &[0; 8], duration: 1024, composition_offset: 0, is_sync: true }).unwrap(); + } + w.finish().unwrap().into_inner() + }; + let out = file(Some(-1), 5); + let f = crate::isobmff::open(out.as_slice()).unwrap(); + let groups = &f.tracks[0].sample_groups; + assert_eq!(groups.len(), 1); + assert_eq!((groups[0].grouping_type, groups[0].runs.as_slice()), (crate::isobmff::FourCc(*b"roll"), [(5, 1)].as_slice())); + assert_eq!(groups[0].descriptions, [(-1i16).to_be_bytes().to_vec()]); + assert_eq!(f.tracks[0].samples.len(), 5); + for out in [file(None, 5), file(Some(-1), 0)] { + assert!(crate::isobmff::open(out.as_slice()).unwrap().tracks[0].sample_groups.is_empty()); + } + // The boxes as ISO/IEC 14496-12 §8.9 has them (and ffmpeg writes them): `sgpd` version 1 + // with a default description length of 2, one description; `sbgp` version 0, one run. + let sgpd = [&26u32.to_be_bytes()[..], b"sgpd", &[1, 0, 0, 0], b"roll", &[0, 0, 0, 2, 0, 0, 0, 1, 0xFF, 0xFF]].concat(); + let sbgp = [&28u32.to_be_bytes()[..], b"sbgp", &[0, 0, 0, 0], b"roll", &[0, 0, 0, 1, 0, 0, 0, 5, 0, 0, 0, 1]].concat(); + let both = [sgpd, sbgp].concat(); + assert!(out.windows(both.len()).any(|w| w == both)); + } + + /// A writer positioned where the header's end would pass `u64::MAX` is refused, not overflowed. + #[test] + fn a_writer_at_the_end_of_the_position_range_is_refused() { + for back in [0, 1, 10, 27] { + let mut bytes = [0u8; 8]; + let mut sink = Cursor::new(&mut bytes[..]); + sink.set_position(u64::MAX - back); + assert!(matches!(Mp4Writer::new(sink, WriterOptions::new(Brand::Mp4)), Err(Error::Mux(_))), "{back} before the end"); + } + } + + /// A writer that keeps taking bytes where positions end makes writing fail, not overflow. + #[test] + fn samples_past_the_last_position_are_refused() { + struct Endless(u64); + impl Write for Endless { + fn write(&mut self, data: &[u8]) -> std::io::Result<usize> { + self.0 = self.0.wrapping_add(data.len() as u64); + Ok(data.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + impl Seek for Endless { + fn seek(&mut self, _: SeekFrom) -> std::io::Result<u64> { + Ok(self.0) + } + } + let mut w = Mp4Writer::new(Endless(u64::MAX - 100), WriterOptions::new(Brand::Mp4)).unwrap(); + let v = w.add_track(TrackConfig::new(avc_entry(), 1000)).unwrap(); + let sample = WriteSample { data: &[0; 40], duration: 40, composition_offset: 0, is_sync: true }; + w.write_sample(v, sample).unwrap(); + assert!(matches!(w.write_sample(v, sample), Err(Error::Mux(_)))); + } + + /// A file begun in the middle of a writer is a file from there: its chunk offsets count from + /// its own first byte, with `moov` at the end or in front, a timecode track and chapters. + #[test] + fn a_file_begun_mid_writer_has_offsets_from_its_start() { + let file = |prefix: usize, faststart: bool| { + let mut sink = Cursor::new(vec![0xAA; prefix]); + sink.set_position(prefix as u64); + let mut opts = WriterOptions::new(Brand::Mov); + opts.chapters = vec![Chapter { start: 0, title: "one".into() }]; + let mut w = Mp4Writer::new(sink, opts).unwrap(); + let v = w.add_track(TrackConfig::new(avc_entry(), 1000)).unwrap(); + let tc = TimecodeConfig { timescale: 1000, frame_duration: 40, frames_per_second: 25, ..Default::default() }; + w.add_timecode_track(v, tc, 7).unwrap(); + for i in 0..4u8 { + w.write_sample(v, WriteSample { data: &[i + 1; 10], duration: 40, composition_offset: 0, is_sync: true }).unwrap(); + } + let out = if faststart { w.finish_faststart() } else { w.finish() }.unwrap(); + assert_eq!(out.position(), out.get_ref().len() as u64); + out.into_inner() + }; + for faststart in [false, true] { + let (plain, offset) = (file(0, faststart), file(100, faststart)); + assert!(offset[..100].iter().all(|&b| b == 0xAA)); + assert!(offset[100..] == plain, "faststart {faststart}"); + let f = crate::isobmff::open(plain.as_slice()).unwrap(); + assert_eq!(f.tracks.len(), 3); + for i in 0..4 { + assert_eq!(f.read_sample(plain.as_slice(), 0, i).unwrap(), vec![i as u8 + 1; 10]); + } + assert_eq!(f.read_sample(plain.as_slice(), 1, 0).unwrap(), 7u32.to_be_bytes()); + } + } } diff --git a/crates/metadata/src/camera_fields.rs b/crates/metadata/src/camera_fields.rs new file mode 100644 index 000000000..ade835736 --- /dev/null +++ b/crates/metadata/src/camera_fields.rs @@ -0,0 +1,445 @@ +//! Unnormalized camera-field EXIF view, reused from PhotoCraft (exposure, aperture, +//! ISO, focal length, camera and lens names). Input is the raw TIFF-structured EXIF payload +//! (`II*\0` / `MM\0*`, as stored in `Document.metadata.exif`); malformed data yields `None` +//! fields, never a panic. Tag numbers are from the EXIF 2.32 specification (CIPA DC-008). + +// Semantics originate in PhotoCraft, including Brandon Thomas and Fabio Lussi. +// Unlike read_exif this view does not normalize dates or derive missing fields. +#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] + +/// Camera settings read from EXIF. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CameraInfo { + pub make: Option<String>, + pub model: Option<String>, + pub lens: Option<String>, + /// Seconds. + pub exposure_time: Option<f64>, + pub f_number: Option<f64>, + pub iso: Option<f64>, + /// Millimetres. + pub focal_length: Option<f64>, + /// 35 mm-equivalent focal length in millimetres. + pub focal_length_35mm: Option<f64>, + /// DateTimeOriginal as stored (`YYYY:MM:DD HH:MM:SS`). + pub date_taken: Option<String>, +} + +impl CameraInfo { + /// Linear exposure factor `t · ISO / N²` (relative brightness of the image for one scene). + pub fn exposure_factor(&self) -> Option<f64> { + let t = self.exposure_time?; + let n = self.f_number.unwrap_or(1.0).max(0.1); + Some(t * self.iso.unwrap_or(100.0) / 100.0 / (n * n)) + } +} + +/// Text bytes decoded per EXIF read (real Make/Model/Lens/Date strings are a few dozen bytes). +const MAX_TEXT_BYTES: usize = 1 << 20; + +struct Tiff<'a> { + b: &'a [u8], + order: craft_tiff::ByteOrder, + /// Text bytes this read may still decode: duplicate tags can share one large blank value. + text_left: std::cell::Cell<usize>, +} + +impl Tiff<'_> { + fn u16(&self, o: usize) -> Option<u16> { + self.order.read_u16(self.b, o) + } + fn u32(&self, o: usize) -> Option<u32> { + self.order.read_u32(self.b, o) + } + /// Entries of the IFD at `off`: (tag, type, count, value offset field position). + fn ifd(&self, off: usize) -> Vec<(u16, u16, u32, usize)> { + let Some(n) = self.u16(off) else { return Vec::new() }; + (0..n as usize) + .filter_map(|k| { + // Checked: offsets come from the file, and usize is 32 bits on wasm. + let e = off.checked_add(2)?.checked_add(k * 12)?; + Some((self.u16(e)?, self.u16(e.checked_add(2)?)?, self.u32(e.checked_add(4)?)?, e.checked_add(8)?)) + }) + .collect() + } + fn data_at(&self, typ: u16, _count: u32, field: usize) -> Option<usize> { + // Keep this caller's historical classic-TIFF type policy; shared spans also + // support IFD/BigTIFF types which CameraInfo never accepted. + if !(1..=12).contains(&typ) { + return None; + } + let span = craft_tiff::entry_span(self.b, field.checked_sub(8)?, self.order, false, 0)?; + usize::try_from(span.start).ok() + } + fn number(&self, typ: u16, count: u32, field: usize) -> Option<f64> { + let at = self.data_at(typ, count, field)?; + match typ { + 3 => self.u16(at).map(f64::from), + 4 => self.u32(at).map(f64::from), + 5 => { + let (n, d) = (self.u32(at)?, self.u32(at.checked_add(4)?)?); + (d != 0).then(|| n as f64 / d as f64) + } + 10 => { + let (n, d) = (self.u32(at)? as i32, self.u32(at.checked_add(4)?)? as i32); + (d != 0).then(|| n as f64 / d as f64) + } + _ => None, + } + } + fn text(&self, typ: u16, count: u32, field: usize) -> Option<String> { + #[cfg(test)] + TEXT_DECODES.with(|c| c.set(c.get() + 1)); + if typ != 2 { + return None; + } + let at = self.data_at(typ, count, field)?; + let n = usize::try_from(count).ok()?; + self.text_left.set(self.text_left.get().checked_sub(n)?); + let s = self.b.get(at..at.checked_add(n)?)?; + let s = String::from_utf8_lossy(s).trim_end_matches('\0').trim().to_string(); + (!s.is_empty()).then_some(s) + } +} + +#[cfg(test)] +thread_local!(static TEXT_DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }); + +/// Reads [`CameraInfo`] from a TIFF-structured EXIF payload (an `Exif\0\0` prefix is skipped). +pub fn read(exif: &[u8]) -> CameraInfo { + let b = exif.strip_prefix(b"Exif\0\0").unwrap_or(exif); + let mut info = CameraInfo::default(); + let le = match b.get(..4) { + Some([b'I', b'I', 42, 0]) => true, + Some([b'M', b'M', 0, 42]) => false, + _ => return info, + }; + let t = Tiff { + b, + order: if le { craft_tiff::ByteOrder::Little } else { craft_tiff::ByteOrder::Big }, + text_left: std::cell::Cell::new(MAX_TEXT_BYTES), + }; + let Some(ifd0) = t.u32(4) else { return info }; + let mut queue = vec![ifd0 as usize]; + let mut seen = Vec::new(); + while let Some(off) = queue.pop() { + if seen.contains(&off) || seen.len() > 8 { + continue; + } + seen.push(off); + for (tag, typ, count, field) in t.ifd(off) { + match tag { + // Duplicate TIFF text tags can point at the same large payload. Keep the first + // recognized value and do not repeatedly decode/copy later duplicates. + 0x010F if info.make.is_none() => info.make = t.text(typ, count, field), + 0x0110 if info.model.is_none() => info.model = t.text(typ, count, field), + 0x829A => info.exposure_time = t.number(typ, count, field), + 0x829D => info.f_number = t.number(typ, count, field), + 0x8827 => info.iso = t.number(typ, count, field), + 0x920A => info.focal_length = t.number(typ, count, field), + 0xA405 => info.focal_length_35mm = t.number(typ, count, field).filter(|v| *v > 0.0), + 0xA434 if info.lens.is_none() => info.lens = t.text(typ, count, field), + 0x9003 if info.date_taken.is_none() => info.date_taken = t.text(typ, count, field), + 0x8769 => { + if let Some(p) = t.u32(field) { + queue.push(p as usize); + } + } + _ => {} + } + } + } + info +} + +/// Build a classic TIFF EXIF block using the shared TIFF writer. +/// Raw date strings and numeric rounding match the camera-field view. Text is +/// bounded to the reader's 1 MiB aggregate budget; oversized inputs return an error. +/// Physical directory placement is not part of this API's contract. +pub fn try_build(info: &CameraInfo) -> craft_tiff::Result<Vec<u8>> { + use craft_tiff::{ByteOrder, IfdBuilder, TiffError, TiffWriter, Value}; + let total = + [&info.make, &info.model, &info.lens, &info.date_taken].into_iter().flatten().try_fold(0usize, |n, s| n.checked_add(s.len())?.checked_add(1)); + if total.is_none_or(|n| n > MAX_TEXT_BYTES) { + return Err(TiffError::Limit("camera EXIF text")); + } + let mut root = IfdBuilder::new(); + let mut exif = IfdBuilder::new(); + for (tag, value) in [(0x010f, &info.make), (0x0110, &info.model)] { + if let Some(value) = value { + root.set(tag, Value::Ascii(value.clone())); + } + } + for (tag, value) in [(0x9003, &info.date_taken), (0xa434, &info.lens)] { + if let Some(value) = value { + exif.set(tag, Value::Ascii(value.clone())); + } + } + for (tag, value) in [(0x829a, info.exposure_time), (0x829d, info.f_number), (0x920a, info.focal_length)] { + if let Some(value) = value { + exif.set(tag, Value::Rational(vec![((value * 10000.0).round() as u32, 10000)])); + } + } + for (tag, value) in [(0x8827, info.iso), (0xa405, info.focal_length_35mm)] { + if let Some(value) = value { + exif.set(tag, Value::Short(vec![value as u16])); + } + } + // Empty child IFDs are valid here; the reader yields absent fields. + root.set_child(0x8769, exif); + TiffWriter::new(ByteOrder::Little, false).write(&[root]) +} + +#[cfg(test)] +fn build(info: &CameraInfo) -> Vec<u8> { + try_build(info).unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_and_survives_garbage() { + let info = CameraInfo { + make: Some("Generic".into()), + model: Some("Camera 1".into()), + lens: Some("24-70mm".into()), + exposure_time: Some(0.004), + f_number: Some(8.0), + iso: Some(200.0), + focal_length: Some(35.0), + focal_length_35mm: Some(52.0), + date_taken: Some("2024:02:17 12:40:19".into()), + }; + let b = build(&info); + let r = read(&b); + assert_eq!(r, info); + assert!((r.exposure_factor().unwrap() - 0.004 * 2.0 / 64.0).abs() < 1e-9); + let mut prefixed = b"Exif\0\0".to_vec(); + prefixed.extend_from_slice(&b); + assert_eq!(read(&prefixed), info); + assert_eq!(read(b"nonsense"), CameraInfo::default()); + for cut in [5, 12, 30, b.len() - 3] { + let _ = read(&b[..cut]); + } + } + + /// Hostile payloads: huge counts, offsets near `u32::MAX`, self-referencing IFDs and random + /// bytes read as `None` fields instead of panicking or overflowing (usize is 32 bits on wasm). + #[test] + fn blank_duplicate_text_tags_share_one_decode_budget() { + // Blank values never fill `make`, so every duplicate would decode the same 1 MiB again; + // the per-read budget stops after the first, so the later real value is not reached. + let blank = MAX_TEXT_BYTES; + let entry = |count: u32, off: u32| { + let mut e = Vec::new(); + e.extend_from_slice(&0x010Fu16.to_le_bytes()); + e.extend_from_slice(&2u16.to_le_bytes()); + e.extend_from_slice(&count.to_le_bytes()); + e.extend_from_slice(&off.to_le_bytes()); + e + }; + let mut b = b"II*\0".to_vec(); + b.extend_from_slice(&8u32.to_le_bytes()); + b.extend_from_slice(&3u16.to_le_bytes()); + b.extend(entry(blank as u32, 50)); + b.extend(entry(blank as u32, 50)); + b.extend(entry(2, u32::from_le_bytes(*b"M\0\0\0"))); + b.extend_from_slice(&0u32.to_le_bytes()); + assert_eq!(b.len(), 50); + b.extend(std::iter::repeat_n(b' ', blank)); + assert_eq!(read(&b).make, None); + } + + #[test] + fn duplicate_text_tags_keep_the_first_value_without_copying_large_duplicates() { + let value = vec![b'X'; 2 * 1024 * 1024]; + let mut b = b"II*\0".to_vec(); + b.extend_from_slice(&8u32.to_le_bytes()); + // IFD0: Make="M", a duplicate Make pointing at a 2 MiB payload, and the Exif IFD link. + b.extend_from_slice(&3u16.to_le_bytes()); + b.extend_from_slice(&0x010Fu16.to_le_bytes()); + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&2u32.to_le_bytes()); + b.extend_from_slice(b"M\0\0\0"); + b.extend_from_slice(&0x010Fu16.to_le_bytes()); + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&(value.len() as u32).to_le_bytes()); + b.extend_from_slice(&80u32.to_le_bytes()); + b.extend_from_slice(&0x8769u16.to_le_bytes()); + b.extend_from_slice(&4u16.to_le_bytes()); + b.extend_from_slice(&1u32.to_le_bytes()); + b.extend_from_slice(&50u32.to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); + // Exif IFD at 50: DateTimeOriginal="D" and the same large duplicate payload at offset 80. + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&0x9003u16.to_le_bytes()); + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&2u32.to_le_bytes()); + b.extend_from_slice(b"D\0\0\0"); + b.extend_from_slice(&0x9003u16.to_le_bytes()); + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&(value.len() as u32).to_le_bytes()); + b.extend_from_slice(&80u32.to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); + b.extend_from_slice(&value); + + TEXT_DECODES.with(|c| c.set(0)); + let info = read(&b); + assert_eq!(info.make.as_deref(), Some("M")); + assert_eq!(info.date_taken.as_deref(), Some("D")); + // One decode per tag: duplicates must be skipped before `text` copies their payload. + assert_eq!(TEXT_DECODES.with(|c| c.get()), 2); + } + + #[test] + fn hostile_payloads_never_panic() { + let entry = |tag: u16, typ: u16, count: u32, value: u32| { + let mut e = tag.to_le_bytes().to_vec(); + e.extend_from_slice(&typ.to_le_bytes()); + e.extend_from_slice(&count.to_le_bytes()); + e.extend_from_slice(&value.to_le_bytes()); + e + }; + let mut b = b"II*\0".to_vec(); + b.extend_from_slice(&8u32.to_le_bytes()); + let entries = [ + entry(0x010F, 2, u32::MAX, 8), // Make: count far past the end + entry(0x0110, 2, 16, u32::MAX - 1), // Model: offset at the top of the range + entry(0x829A, 5, u32::MAX, 20), // ExposureTime: count overflows the size + entry(0x829D, 5, 1, u32::MAX - 3), // FNumber: rational straddles u32::MAX + entry(0x9003, 2, 0x4000_0000, 8), // DateTimeOriginal: size overflow on 32 bits + entry(0x8769, 4, 1, 8), // Exif IFD pointing back at IFD0 + entry(0x8769, 4, 1, u32::MAX), // ... and past the end + ]; + b.extend_from_slice(&(entries.len() as u16 + 3).to_le_bytes()); // claims more entries than exist + for e in entries { + b.extend_from_slice(&e); + } + assert_eq!(read(&b), CameraInfo::default()); + let mut be = b"MM\0*".to_vec(); + be.extend_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(read(&be), CameraInfo::default()); + // Deterministic noise behind a valid header, and every truncation of a real payload. + let mut x = 0x2545_F491u32; + for _ in 0..200 { + let mut n = b"II*\0\x08\0\0\0".to_vec(); + for _ in 0..96 { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + n.push(x as u8); + } + let _ = read(&n); + } + let good = build(&CameraInfo { + make: Some("Make".into()), + date_taken: Some("2024:02:17 12:40:19".into()), + exposure_time: Some(0.004), + ..Default::default() + }); + for cut in 0..good.len() { + let _ = read(&good[..cut]); + } + } +} + +// Keep the previous byte reader only as a test oracle during the shared-span cutover. +#[cfg(test)] +#[path = "camera_fields_legacy_tests.rs"] +mod legacy; + +#[cfg(test)] +mod shared_span_parity { + use super::*; + + fn compare(bytes: &[u8]) { + assert_eq!(format!("{:?}", read(bytes)), format!("{:?}", legacy::read(bytes))); + } + + #[test] + fn shared_writer_matches_legacy_fields_and_rejects_oversized_text() { + for value in [0.0, -1.0, 0.004, 2.8, 65535.0, f64::INFINITY, f64::NAN] { + let camera = CameraInfo { + exposure_time: Some(value), + f_number: Some(value), + iso: Some(value), + focal_length: Some(value), + focal_length_35mm: Some(value), + date_taken: Some("raw date".into()), + make: Some("M".into()), + model: Some("Model".into()), + lens: Some("Lens".into()), + }; + let old = legacy::CameraInfo { + exposure_time: camera.exposure_time, + f_number: camera.f_number, + iso: camera.iso, + focal_length: camera.focal_length, + focal_length_35mm: camera.focal_length_35mm, + date_taken: camera.date_taken.clone(), + make: camera.make.clone(), + model: camera.model.clone(), + lens: camera.lens.clone(), + }; + let bytes = try_build(&camera).unwrap(); + assert_eq!(format!("{:?}", read(&bytes)), format!("{:?}", legacy::read(&legacy::build(&old)))); + } + assert_eq!(read(&try_build(&CameraInfo::default()).unwrap()), CameraInfo::default()); + assert!(try_build(&CameraInfo { make: Some("x".repeat(MAX_TEXT_BYTES)), ..Default::default() }).is_err()); + assert!(try_build(&CameraInfo { make: Some("x".repeat(MAX_TEXT_BYTES - 1)), ..Default::default() }).is_ok()); + } + + #[test] + fn preserves_camera_selection_for_valid_truncated_and_mutated_payloads() { + let bytes = build(&CameraInfo { + make: Some("Maker".into()), + model: Some("Camera".into()), + lens: Some("Lens".into()), + exposure_time: Some(0.125), + f_number: Some(2.8), + iso: Some(200.0), + focal_length: Some(50.0), + focal_length_35mm: Some(75.0), + date_taken: Some("not normalized: original date".into()), + }); + compare(&bytes); + let mut prefixed = b"Exif\0\0".to_vec(); + prefixed.extend_from_slice(&bytes); + compare(&prefixed); + for end in 0..=bytes.len() { + compare(&bytes[..end]); + } + // Exercise offsets, tags, types, counts and payloads independently, not random + // external data. The complete shared span must remain bounded for every edit. + for index in 0..bytes.len() { + for value in [0, 0xff, 0x80] { + let mut changed = bytes.clone(); + changed[index] = value; + compare(&changed); + } + } + } + + #[test] + fn preserves_partial_entry_and_zero_count_semantics_in_both_orders() { + for little in [true, false] { + let u16b = |v: u16| if little { v.to_le_bytes() } else { v.to_be_bytes() }; + let u32b = |v: u32| if little { v.to_le_bytes() } else { v.to_be_bytes() }; + for count in [0u32, 1, 2, u32::MAX] { + let mut bytes = if little { b"II".to_vec() } else { b"MM".to_vec() }; + bytes.extend(u16b(42)); + bytes.extend(u32b(8)); + bytes.extend(u16b(1)); + bytes.extend(u16b(0x8827)); + bytes.extend(u16b(3)); + bytes.extend(u32b(count)); + bytes.extend(u16b(200)); + compare(&bytes); // two inline bytes, no full 12-byte entry/next pointer + bytes.extend(u16b(0)); + compare(&bytes); + } + } + } +} diff --git a/crates/metadata/src/camera_fields_legacy_tests.rs b/crates/metadata/src/camera_fields_legacy_tests.rs new file mode 100644 index 000000000..1b560f91f --- /dev/null +++ b/crates/metadata/src/camera_fields_legacy_tests.rs @@ -0,0 +1,237 @@ +// Frozen differential oracle: PhotoCraft main abb30dff, exif.rs. Test-only, not a production fallback. +#![allow(dead_code)] +// Minimal EXIF reader for the camera settings the photography commands use (exposure, aperture, +// ISO, focal length, camera and lens names). Input is the raw TIFF-structured EXIF payload +// (`II*\0` / `MM\0*`, as stored in `Document.metadata.exif`); malformed data yields `None` +// fields, never a panic. Tag numbers are from the EXIF 2.32 specification (CIPA DC-008). + +/// Camera settings read from EXIF. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CameraInfo { + pub make: Option<String>, + pub model: Option<String>, + pub lens: Option<String>, + /// Seconds. + pub exposure_time: Option<f64>, + pub f_number: Option<f64>, + pub iso: Option<f64>, + /// Millimetres. + pub focal_length: Option<f64>, + /// 35 mm-equivalent focal length in millimetres. + pub focal_length_35mm: Option<f64>, + /// DateTimeOriginal as stored (`YYYY:MM:DD HH:MM:SS`). + pub date_taken: Option<String>, +} + +impl CameraInfo { + /// Linear exposure factor `t · ISO / N²` (relative brightness of the image for one scene). + pub fn exposure_factor(&self) -> Option<f64> { + let t = self.exposure_time?; + let n = self.f_number.unwrap_or(1.0).max(0.1); + Some(t * self.iso.unwrap_or(100.0) / 100.0 / (n * n)) + } +} + +/// Text bytes decoded per EXIF read (real Make/Model/Lens/Date strings are a few dozen bytes). +const MAX_TEXT_BYTES: usize = 1 << 20; + +struct Tiff<'a> { + b: &'a [u8], + le: bool, + /// Text bytes this read may still decode: duplicate tags can share one large blank value. + text_left: std::cell::Cell<usize>, +} + +impl Tiff<'_> { + fn u16(&self, o: usize) -> Option<u16> { + let s = self.b.get(o..o.checked_add(2)?)?; + Some(if self.le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) }) + } + fn u32(&self, o: usize) -> Option<u32> { + let s = self.b.get(o..o.checked_add(4)?)?; + let a = [s[0], s[1], s[2], s[3]]; + Some(if self.le { u32::from_le_bytes(a) } else { u32::from_be_bytes(a) }) + } + /// Entries of the IFD at `off`: (tag, type, count, value offset field position). + fn ifd(&self, off: usize) -> Vec<(u16, u16, u32, usize)> { + let Some(n) = self.u16(off) else { return Vec::new() }; + (0..n as usize) + .filter_map(|k| { + // Checked: offsets come from the file, and usize is 32 bits on wasm. + let e = off.checked_add(2)?.checked_add(k * 12)?; + Some((self.u16(e)?, self.u16(e.checked_add(2)?)?, self.u32(e.checked_add(4)?)?, e.checked_add(8)?)) + }) + .collect() + } + fn data_at(&self, typ: u16, count: u32, field: usize) -> Option<usize> { + let size = match typ { + 1 | 2 | 6 | 7 => 1usize, + 3 | 8 => 2, + 4 | 9 | 11 => 4, + 5 | 10 | 12 => 8, + _ => return None, + } + .checked_mul(usize::try_from(count).ok()?)?; + let at = if size <= 4 { field } else { usize::try_from(self.u32(field)?).ok()? }; + // The whole value must lie inside the payload, not just its first element. + self.b.get(at..at.checked_add(size)?)?; + Some(at) + } + fn number(&self, typ: u16, count: u32, field: usize) -> Option<f64> { + let at = self.data_at(typ, count, field)?; + match typ { + 3 => self.u16(at).map(f64::from), + 4 => self.u32(at).map(f64::from), + 5 => { + let (n, d) = (self.u32(at)?, self.u32(at.checked_add(4)?)?); + (d != 0).then(|| n as f64 / d as f64) + } + 10 => { + let (n, d) = (self.u32(at)? as i32, self.u32(at.checked_add(4)?)? as i32); + (d != 0).then(|| n as f64 / d as f64) + } + _ => None, + } + } + fn text(&self, typ: u16, count: u32, field: usize) -> Option<String> { + #[cfg(test)] + TEXT_DECODES.with(|c| c.set(c.get() + 1)); + if typ != 2 { + return None; + } + let at = self.data_at(typ, count, field)?; + let n = usize::try_from(count).ok()?; + self.text_left.set(self.text_left.get().checked_sub(n)?); + let s = self.b.get(at..at.checked_add(n)?)?; + let s = String::from_utf8_lossy(s).trim_end_matches('\0').trim().to_string(); + (!s.is_empty()).then_some(s) + } +} + +#[cfg(test)] +thread_local!(static TEXT_DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }); + +/// Reads [`CameraInfo`] from a TIFF-structured EXIF payload (an `Exif\0\0` prefix is skipped). +pub fn read(exif: &[u8]) -> CameraInfo { + let b = exif.strip_prefix(b"Exif\0\0").unwrap_or(exif); + let mut info = CameraInfo::default(); + let le = match b.get(..4) { + Some([b'I', b'I', 42, 0]) => true, + Some([b'M', b'M', 0, 42]) => false, + _ => return info, + }; + let t = Tiff { b, le, text_left: std::cell::Cell::new(MAX_TEXT_BYTES) }; + let Some(ifd0) = t.u32(4) else { return info }; + let mut queue = vec![ifd0 as usize]; + let mut seen = Vec::new(); + while let Some(off) = queue.pop() { + if seen.contains(&off) || seen.len() > 8 { + continue; + } + seen.push(off); + for (tag, typ, count, field) in t.ifd(off) { + match tag { + // Duplicate TIFF text tags can point at the same large payload. Keep the first + // recognized value and do not repeatedly decode/copy later duplicates. + 0x010F if info.make.is_none() => info.make = t.text(typ, count, field), + 0x0110 if info.model.is_none() => info.model = t.text(typ, count, field), + 0x829A => info.exposure_time = t.number(typ, count, field), + 0x829D => info.f_number = t.number(typ, count, field), + 0x8827 => info.iso = t.number(typ, count, field), + 0x920A => info.focal_length = t.number(typ, count, field), + 0xA405 => info.focal_length_35mm = t.number(typ, count, field).filter(|v| *v > 0.0), + 0xA434 if info.lens.is_none() => info.lens = t.text(typ, count, field), + 0x9003 if info.date_taken.is_none() => info.date_taken = t.text(typ, count, field), + 0x8769 => { + if let Some(p) = t.u32(field) { + queue.push(p as usize); + } + } + _ => {} + } + } + } + info +} + +/// Builds a little-endian EXIF payload (used by tests and by synthetic fixtures). +pub fn build(info: &CameraInfo) -> Vec<u8> { + // IFD0: Make, Model, ExifIFD pointer; Exif IFD: the rest. Data area after the IFDs. + let mut ifd0: Vec<(u16, u16, u32, Vec<u8>)> = Vec::new(); + let mut exif: Vec<(u16, u16, u32, Vec<u8>)> = Vec::new(); + let text = |s: &str| { + let mut v = s.as_bytes().to_vec(); + v.push(0); + v + }; + let rational = |v: f64| { + let d = 10000u32; + let mut b = ((v * d as f64).round() as u32).to_le_bytes().to_vec(); + b.extend_from_slice(&d.to_le_bytes()); + b + }; + if let Some(s) = &info.make { + ifd0.push((0x010F, 2, s.len() as u32 + 1, text(s))); + } + if let Some(s) = &info.model { + ifd0.push((0x0110, 2, s.len() as u32 + 1, text(s))); + } + if let Some(v) = info.exposure_time { + exif.push((0x829A, 5, 1, rational(v))); + } + if let Some(v) = info.f_number { + exif.push((0x829D, 5, 1, rational(v))); + } + if let Some(v) = info.iso { + exif.push((0x8827, 3, 1, (v as u16).to_le_bytes().to_vec())); + } + if let Some(s) = &info.date_taken { + exif.push((0x9003, 2, s.len() as u32 + 1, text(s))); + } + if let Some(v) = info.focal_length { + exif.push((0x920A, 5, 1, rational(v))); + } + if let Some(v) = info.focal_length_35mm { + exif.push((0xA405, 3, 1, (v as u16).to_le_bytes().to_vec())); + } + if let Some(s) = &info.lens { + exif.push((0xA434, 2, s.len() as u32 + 1, text(s))); + } + let ifd_len = |n: usize| 2 + 12 * n + 4; + let ifd0_off = 8usize; + let n0 = ifd0.len() + 1; + let exif_off = ifd0_off + ifd_len(n0); + let mut data_off = exif_off + ifd_len(exif.len()); + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&(ifd0_off as u32).to_le_bytes()); + let mut data = Vec::new(); + let mut write_ifd = |out: &mut Vec<u8>, entries: &[(u16, u16, u32, Vec<u8>)], extra: Option<u32>| { + let n = entries.len() + usize::from(extra.is_some()); + out.extend_from_slice(&(n as u16).to_le_bytes()); + for (tag, typ, count, bytes) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&typ.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + if bytes.len() <= 4 { + let mut f = bytes.clone(); + f.resize(4, 0); + out.extend_from_slice(&f); + } else { + out.extend_from_slice(&(data_off as u32).to_le_bytes()); + data.extend_from_slice(bytes); + data_off += bytes.len(); + } + } + if let Some(p) = extra { + out.extend_from_slice(&0x8769u16.to_le_bytes()); + out.extend_from_slice(&4u16.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); + out.extend_from_slice(&p.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + }; + write_ifd(&mut out, &ifd0, Some(exif_off as u32)); + write_ifd(&mut out, &exif, None); + out.extend_from_slice(&data); + out +} diff --git a/crates/metadata/src/cr3.rs b/crates/metadata/src/cr3.rs index a7538e88b..4ae189a80 100644 --- a/crates/metadata/src/cr3.rs +++ b/crates/metadata/src/cr3.rs @@ -351,28 +351,70 @@ fn trak(bytes: &[u8], t: &BoxRef, budget: &mut usize) -> Option<Cr3Track> { } } let stbl = stbl?; - let (mut kind, mut size, mut offset) = (None, None, None); + let (mut kind, mut size, mut offset, mut mapping, mut sample_count) = (None, None, None, None, 0); for b in boxes(bytes, stbl.body, stbl.end, budget) { let body = bytes.get(b.body..b.end)?; match &b.kind { // full box: version/flags, entry count, entries b"stsd" if be32(body, 4)? > 0 => kind = boxes(bytes, b.body + 8, b.end, budget).first().map(|e| sample_entry(bytes, e, budget)), + b"stsc" => { + // Only the first sample is exposed. It must map chunk 1 to + // the first sample description; don't trust offsets without + // that mapping, or a damaged/raw track could become a JPEG. + // A malformed mapping invalidates sample data, not the track's + // identity: dropping the largest raw track could select a reduced + // raw successfully and disguise corruption in the main image. + mapping = (|| { + let count = be32(body, 4)? as usize; + if be32(body, 0)? != 0 || count == 0 || count > body.len().saturating_sub(8) / 12 { + return None; + } + Some((be32(body, 8)?, be32(body, 12)?, be32(body, 16)?)) + })(); + } // version/flags, sample_size (0 = per-sample table), count, sizes b"stsz" => { - size = match be32(body, 4)? { - 0 if be32(body, 8)? > 0 => be32(body, 12), - 0 => None, - n if be32(body, 8)? > 0 => Some(n), + // A truncated size table invalidates data without hiding a known track. + sample_count = be32(body, 8).unwrap_or(0); + size = match be32(body, 4) { + // A first entry cannot justify an incomplete per-sample + // table, nor an impossible constant-size sample count. + Some(0) if sample_count > 0 && sample_count as usize <= body.len().saturating_sub(12) / 4 => be32(body, 12), + Some(n) + if n > 0 + && sample_count > 0 + && u64::from(n).checked_mul(u64::from(sample_count)).is_some_and(|total| total <= bytes.len() as u64) => + { + Some(n) + } _ => None, } } - b"co64" if be32(body, 4)? > 0 => offset = be64(body, 8).and_then(|v| usize::try_from(v).ok()), - b"stco" if be32(body, 4)? > 0 => offset = be32(body, 8).map(|v| v as usize), + // Missing or truncated offset-table counts deny sample access, but the known + // track must remain available to the largest-raw-track selector. + b"co64" => { + offset = match be32(body, 4) { + Some(count) if count > 0 && count as usize <= body.len().saturating_sub(8) / 8 => { + be64(body, 8).and_then(|v| usize::try_from(v).ok()) + } + _ => None, + }; + } + b"stco" => { + offset = match be32(body, 4) { + Some(count) if count > 0 && count as usize <= body.len().saturating_sub(8) / 4 => be32(body, 8).map(|v| v as usize), + _ => None, + }; + } _ => {} } } - let data = match (offset, size) { - (Some(o), Some(s)) if o.checked_add(s as usize).is_some_and(|e| e <= bytes.len()) => Some((o, s as usize)), + let data = match (offset, size, mapping) { + (Some(o), Some(s), Some((1, samples, 1))) + if samples > 0 && samples <= sample_count && o.checked_add(s as usize).is_some_and(|e| e <= bytes.len()) => + { + Some((o, s as usize)) + } _ => None, }; Some(Cr3Track { kind: kind?, data }) @@ -495,6 +537,13 @@ mod tests { bx(b"CRAW", &b) } fn trak(entry: Vec<u8>, offset: u64, size: u32) -> Vec<u8> { + let stsc = [1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>(); + trak_with_mapping(entry, offset, size, &stsc) + } + fn trak_with_mapping(entry: Vec<u8>, offset: u64, size: u32, mapping: &[u8]) -> Vec<u8> { + trak_with_table(entry, offset, size, b"stsc", mapping) + } + fn trak_with_table(entry: Vec<u8>, offset: u64, size: u32, table: &[u8; 4], payload: &[u8]) -> Vec<u8> { let mut stsd = 1u32.to_be_bytes().to_vec(); stsd.extend(entry); let mut stsz = 0u32.to_be_bytes().to_vec(); @@ -502,7 +551,15 @@ mod tests { stsz.extend(size.to_be_bytes()); let mut co64 = 1u32.to_be_bytes().to_vec(); co64.extend(offset.to_be_bytes()); - let stbl = [full(b"stsd", &stsd), full(b"stsz", &stsz), full(b"co64", &co64)].concat(); + let stsc = [1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>(); + let offsets = if table == b"stco" { full(b"stco", payload) } else { full(b"co64", if table == b"co64" { payload } else { &co64 }) }; + let stbl = [ + full(b"stsd", &stsd), + full(b"stsc", if table == b"stsc" { payload } else { &stsc }), + full(b"stsz", if table == b"stsz" { payload } else { &stsz }), + offsets, + ] + .concat(); bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &stbl)))) } fn tiff_with(tag: u16, v: craft_tiff::Value) -> Vec<u8> { @@ -543,6 +600,97 @@ mod tests { assert_eq!(c.tracks[1].data, Some((4112, 32))); } + #[test] + fn first_sample_requires_a_complete_valid_sample_to_chunk_mapping() { + let file = |track: Vec<u8>| { + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"moov", &track)); + file.resize(4112, 0); + file + }; + let valid = trak(craw(16, 16, &bx(b"JPEG", &[0; 4])), 4096, 16); + assert_eq!(parse_cr3(&file(valid.clone())).unwrap().tracks[0].data, Some((4096, 16))); + let at = valid.windows(4).position(|bytes| bytes == b"stsc").unwrap(); + // Missing table, impossible first chunk, zero samples, a different + // description and a count that extends beyond this box all deny data. + for (field, value) in [(0, u32::from_be_bytes(*b"xxxx")), (8, 0), (8, 2), (12, 0), (12, 2), (16, 0), (16, 2), (4, u32::MAX)] { + let mut damaged = valid.clone(); + let offset = if field == 0 { at } else { at + 4 + field }; + damaged[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); + let bytes = file(damaged); + let parsed = parse_cr3(&bytes).unwrap(); + assert_eq!(parsed.tracks.len(), 1, "invalid mapping must not erase an identifiable track"); + assert_eq!(parsed.tracks[0].kind, Cr3TrackKind::Jpeg); + assert!(parsed.tracks[0].data.is_none()); + } + for entry in [craw(16, 16, &[]), craw(16, 16, &bx(b"CMP1", &[0xff, 0x10, 0, 0x30]))] { + let bytes = file(trak(entry, 4096, 16)); + let parsed = parse_cr3(&bytes).unwrap(); + assert!(!matches!(parsed.tracks[0].kind, Cr3TrackKind::Jpeg)); + } + } + + #[test] + fn truncated_sample_mapping_preserves_larger_raw_track_identity_and_valid_reduced_track() { + let reduced = trak(craw(4, 4, &bx(b"CMP1", &compression_payload(0))), 4096, 16); + for table in [b"stsc", b"stsz", b"co64", b"stco"] { + for payload in [Vec::new(), vec![0; 4], 1u32.to_be_bytes().to_vec()] { + // full() supplies version/flags; an empty payload leaves only + // those four bytes, with the table's required count missing. + let main = trak_with_table(craw(8, 4, &bx(b"CMP1", &compression_payload(0))), 4112, 32, table, &payload); + for main_first in [false, true] { + let tracks = if main_first { [main.clone(), reduced.clone()].concat() } else { [reduced.clone(), main.clone()].concat() }; + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"moov", &tracks)); + file.resize(4144, 0); + let parsed = parse_cr3(&file).unwrap(); + assert_eq!(parsed.tracks.len(), 2, "truncated {table:?} cannot hide the larger track"); + let (main, reduced) = if main_first { (&parsed.tracks[0], &parsed.tracks[1]) } else { (&parsed.tracks[1], &parsed.tracks[0]) }; + assert!(matches!(reduced.kind, Cr3TrackKind::Raw { width: 4, height: 4, .. })); + assert_eq!(reduced.data, Some((4096, 16))); + assert!(matches!(main.kind, Cr3TrackKind::Raw { width: 8, height: 4, cmp1: Some(_), .. })); + assert!(main.data.is_none()); + assert!(main.compression(&file).is_some(), "only sample location is invalid"); + } + } + let mut offsets = 1u32.to_be_bytes().to_vec(); + offsets.extend(4112u64.to_be_bytes()); + let valid = match table { + b"stsc" => [1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>(), + b"stsz" => [0u32, 1, 32].into_iter().flat_map(u32::to_be_bytes).collect(), + b"stco" => [1u32, 4112].into_iter().flat_map(u32::to_be_bytes).collect(), + _ => offsets, + }; + let main = trak_with_table(craw(8, 4, &bx(b"CMP1", &compression_payload(0))), 4112, 32, table, &valid); + for main_first in [false, true] { + let tracks = if main_first { [main.clone(), reduced.clone()].concat() } else { [reduced.clone(), main.clone()].concat() }; + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"moov", &tracks)); + file.resize(4144, 0); + let parsed = parse_cr3(&file).unwrap(); + assert_eq!(parsed.tracks.len(), 2); + let main = &parsed.tracks[if main_first { 0 } else { 1 }]; + assert_eq!(main.data, Some((4112, 32)), "complete valid {table:?} stays usable"); + } + } + } + + #[test] + fn first_sample_size_requires_a_complete_bounded_sample_table() { + let valid = trak(craw(16, 16, &bx(b"JPEG", &[0; 4])), 4096, 16); + let at = valid.windows(4).position(|bytes| bytes == b"stsz").unwrap(); + for (constant, count, accepted) in [(0u32, 1u32, true), (16, 1, true), (0, 2, false), (0, u32::MAX, false), (16, u32::MAX, false)] { + let mut track = valid.clone(); + track[at + 8..at + 12].copy_from_slice(&constant.to_be_bytes()); + track[at + 12..at + 16].copy_from_slice(&count.to_be_bytes()); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"moov", &track)); + file.resize(4112, 0); + let parsed = parse_cr3(&file).unwrap(); + assert_eq!(parsed.tracks[0].data, accepted.then_some((4096, 16)), "size {constant}, count {count}"); + } + } + #[test] fn hevc_preview_is_distinct_from_an_equal_size_raw_track() { let preview = trak(craw(6000, 4000, &bx(b"HEVC", &[0; 4])), 4096, 16); @@ -714,7 +862,10 @@ mod tests { let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); file.extend(bx(b"moov", &bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &stbl)))))); file.resize(512, 0); - assert!(parse_cr3(&file).unwrap().tracks.is_empty()); + let parsed = parse_cr3(&file).unwrap(); + assert_eq!(parsed.tracks.len(), 1, "a truncated table must not hide the identifiable raw track"); + assert!(matches!(parsed.tracks[0].kind, Cr3TrackKind::Raw { width: 16, height: 16, .. })); + assert!(parsed.tracks[0].data.is_none(), "the empty stsz must not borrow size bytes from the following co64 box"); } #[test] diff --git a/crates/metadata/src/lib.rs b/crates/metadata/src/lib.rs index 1bc9660b8..ff2c530fa 100644 --- a/crates/metadata/src/lib.rs +++ b/crates/metadata/src/lib.rs @@ -19,6 +19,7 @@ //! HEIF, PSD and MRW files are read by their own crates. Put the blocks they return into an //! [`Embedded`] and call [`from_embedded`]. +pub mod camera_fields; mod container; pub mod cr3; mod datetime; diff --git a/crates/midi/README.md b/crates/midi/README.md index fda624de8..584bd567e 100644 --- a/crates/midi/README.md +++ b/crates/midi/README.md @@ -1,6 +1,6 @@ # craft-midi -MIDI file formats. Bytes in, a neutral model out, and back. No file access: callers pass bytes, +MIDI file formats and synchronization wire messages. Bytes in, a neutral model out, and back. No file access: callers pass bytes, so the crate builds for wasm32. | Format | Read | Write | @@ -79,3 +79,17 @@ of two, more than 65535 tracks or a gap beyond the 28-bit delta limit is an erro Written from the public Standard MIDI Files 1.0 specification (the MIDI Association). No other product's code, assets or strings were used. The code comes from SoundCraft's `soundcraft-midi` crate; the tests build every file they read in code, so the crate ships no binary test data. + +## Synchronization wire messages + +`sync` provides MIDI Clock/Start/Continue/Stop and Song Position Pointer parsing, +clamped song-position encoding, and full-frame/quarter-frame MIDI Time Code serialization. +It is allocation-free and contains no port access, clocks, tempo estimation or transport scheduling. +`SyncMessage::parse` accepts a status-first prefix and ignores trailing bytes, matching LoopCraft; +it is not a byte-stream parser. Time code supports only 24/25/30 non-drop fps, not 29.97 drop-frame. + +These wire helpers are extracted from LoopCraft's `crates/midi/src/sync.rs` at +[`18c68c6e`](https://github.com/storytold/loopcraft/blob/18c68c6e18b13d90db3001dd9f95462cdc4b05a8/crates/midi/src/sync.rs). +The source history credits bflatastic. Transport state and scheduling remain app-owned. +Tests cover known wire vectors, truncated/invalid input, all song-position input values and +legacy conversion behavior. No application consumer cutover is claimed by this library addition. diff --git a/crates/midi/src/lib.rs b/crates/midi/src/lib.rs index 2eb947add..aa82e3e01 100644 --- a/crates/midi/src/lib.rs +++ b/crates/midi/src/lib.rs @@ -12,6 +12,7 @@ mod sequence; mod smf; +pub mod sync; pub use sequence::{CtrlEvent, CtrlKind, Note, Sequence}; pub use smf::{LenientRead, MAX_EVENTS, MAX_TRACKS, MAX_WARNINGS, Smf, SmfTrack, read_smf, read_smf_lenient, write_smf}; diff --git a/crates/midi/src/smf.rs b/crates/midi/src/smf.rs index 442e27f0f..fb6683a30 100644 --- a/crates/midi/src/smf.rs +++ b/crates/midi/src/smf.rs @@ -189,13 +189,14 @@ pub const MAX_WARNINGS: usize = 32; /// short is not believed when the track's End of Track says otherwise: the next chunk is looked /// for where the track's events ended; /// - bytes that are no chunk are skipped up to the next `MTrk`, and trailing bytes are ignored; -/// - past [`MAX_TRACKS`] tracks the rest is left out; +/// - past [`MAX_TRACKS`] tracks the rest is left out; this and the event limit set +/// [`LenientRead::over_limit`]; /// - lyrics are counted in a warning (they are not kept); a format-2 file gets a warning that its /// tracks are read side by side. pub fn read_smf_lenient(bytes: &[u8]) -> Result<LenientRead, MidiError> { let mut warnings = Vec::new(); let (smf, extra) = read(bytes, Some(&mut warnings))?; - Ok(LenientRead { smf, warnings, instruments: extra.instruments, end: extra.end }) + Ok(LenientRead { smf, warnings, instruments: extra.instruments, end: extra.end, over_limit: extra.over_limit }) } /// What [`read_smf_lenient`] makes of a file. @@ -209,12 +210,18 @@ pub struct LenientRead { pub instruments: Vec<String>, /// The last tick any track reaches: its End of Track, or where its events stop. pub end: i64, + /// Whether the file goes past [`MAX_EVENTS`] events or [`MAX_TRACKS`] tracks, so what lies past + /// the limit was left out. It is set even when the warnings are already full, so a caller that + /// refuses such files (as [`read_smf`] does) can tell without reading the warnings. + pub over_limit: bool, } -/// What the reader finds beyond [`Smf`]: instrument names per kept track, and the end tick. +/// What the reader finds beyond [`Smf`]: instrument names per kept track, the end tick, and +/// whether a limit left part of the file out. struct Extra { instruments: Vec<String>, end: i64, + over_limit: bool, } fn warn(warnings: &mut Option<&mut Vec<String>>, what: String) { @@ -262,6 +269,7 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec<String>>) -> Result<(Smf, Ex let (mut tracks, mut instruments) = (Vec::new(), Vec::new()); let mut event_budget = MAX_EVENTS; let (mut end, mut seen, mut lyrics) = (0i64, 0usize, 0usize); + let mut over_limit = false; while !cur.is_empty() { let chunk_at = cur.at(); @@ -306,6 +314,7 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec<String>>) -> Result<(Smf, Ex return Err(MidiError::TooManyTracks(MAX_TRACKS)); } warn(&mut warnings, format!("more than {MAX_TRACKS} tracks: the rest was left out")); + over_limit = true; break; } let (body_at, body_start) = (cur.at(), cur.pos); @@ -319,7 +328,10 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec<String>>) -> Result<(Smf, Ex end = end.max(read.end); match read.stop { Some(e) if !lenient => return Err(e), - Some(e) => warn(&mut warnings, format!("track {seen} {}: what came before is kept", stop_reason(&e))), + Some(e) => { + over_limit |= matches!(e, MidiError::TooManyEvents(_)); + warn(&mut warnings, format!("track {seen} {}: what came before is kept", stop_reason(&e))); + } None if !read.ended && lenient => warn(&mut warnings, format!("track {seen} has no End of Track: what came before is kept")), None => {} } @@ -363,7 +375,7 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec<String>>) -> Result<(Smf, Ex Ok(( Smf { format, tracks, tempos: globals.tempos, meters: globals.meters, markers: globals.markers, key_sigs: globals.key_sigs }, - Extra { instruments, end }, + Extra { instruments, end, over_limit }, )) } diff --git a/crates/midi/src/sync.rs b/crates/midi/src/sync.rs new file mode 100644 index 000000000..153c8a77b --- /dev/null +++ b/crates/midi/src/sync.rs @@ -0,0 +1,135 @@ +//! MIDI synchronization wire messages, separate from transport scheduling. +//! +//! Extracted from LoopCraft `crates/midi/src/sync.rs` at +//! `18c68c6e18b13d90db3001dd9f95462cdc4b05a8` (source history credits bflatastic). +//! This module preserves its prefix-parser, clamped song-position and non-drop time-code +//! behavior. It does not parse a byte stream or schedule clocks; hosts retain those policies. +//! +//! Only 24, 25 and 30 non-drop frames per second are represented, not 29.97 drop-frame. + +/// MIDI clock: 24 to the quarter note. +pub const CLOCKS_PER_QUARTER: u32 = 24; +pub const CLOCK: u8 = 0xF8; +pub const START: u8 = 0xFA; +pub const CONTINUE: u8 = 0xFB; +pub const STOP: u8 = 0xFC; +pub const SONG_POSITION: u8 = 0xF2; +pub const QUARTER_FRAME: u8 = 0xF1; +/// The furthest Song Position Pointer reaches, in sixteenth notes (fourteen bits). +pub const MAX_POSITION: u16 = 0x3FFF; + +/// What a device that leads the time sends. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SyncMessage { + Clock, + Start, + Continue, + Stop, + /// Song Position Pointer: sixteenth notes from the start of the song. + Position(u16), +} + +impl SyncMessage { + /// Parse a status-first message prefix; trailing bytes are ignored for compatibility. + /// Returns `None` for an unknown status, truncated song position, or non-seven-bit data. + /// This is not a stream parser and does not remove interleaved real-time messages. + pub fn parse(message: &[u8]) -> Option<SyncMessage> { + Some(match *message { + [CLOCK, ..] => SyncMessage::Clock, + [START, ..] => SyncMessage::Start, + [CONTINUE, ..] => SyncMessage::Continue, + [STOP, ..] => SyncMessage::Stop, + [SONG_POSITION, low, high, ..] if low < 0x80 && high < 0x80 => SyncMessage::Position(u16::from(high) << 7 | u16::from(low)), + _ => return None, + }) + } +} + +/// Song Position Pointer at `sixteenths` from the start, the low seven bits first. +pub fn song_position(sixteenths: u16) -> [u8; 3] { + let at = sixteenths.min(MAX_POSITION); + [SONG_POSITION, (at & 0x7F) as u8, (at >> 7) as u8] +} + +/// The frame rates time code is sent at (non-drop). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Rate { + Fps24, + #[default] + Fps25, + Fps30, +} + +impl Rate { + /// 24 and 30 frames a second are themselves; anything else is 25. + pub fn of(fps: u8) -> Rate { + match fps { + 24 => Rate::Fps24, + 30 => Rate::Fps30, + _ => Rate::Fps25, + } + } + + pub fn fps(self) -> u8 { + match self { + Rate::Fps24 => 24, + Rate::Fps25 => 25, + Rate::Fps30 => 30, + } + } + + /// As the hours byte carries it: 0 for 24, 1 for 25, 3 for 30 non-drop. + fn code(self) -> u8 { + match self { + Rate::Fps24 => 0, + Rate::Fps25 => 1, + Rate::Fps30 => 3, + } + } +} + +/// Hours, minutes, seconds and frames at `secs`; the hours wrap at a day. +fn timecode(secs: f64, rate: Rate) -> [u8; 4] { + let fps = u64::from(rate.fps()); + // `as` saturates: before the start, and NaN, is the start. The nudge keeps a frame's own + // start in it when the sum lands a hair short. + let frames = (secs * fps as f64 + 1e-6) as u64; + let s = frames / fps; + [(s / 3600 % 24) as u8, (s / 60 % 60) as u8, (s % 60) as u8, (frames % fps) as u8] +} + +/// The full-frame message (universal real-time SysEx, all devices) locating to `secs`. +/// +/// Compatibility conversion: negative values and NaN locate to zero; positive overflow +/// saturates the frame count at `u64::MAX`. Hours wrap at 24. No drop-frame conversion. +pub fn full_frame(secs: f64, rate: Rate) -> [u8; 10] { + let [h, m, s, f] = timecode(secs, rate); + [0xF0, 0x7F, 0x7F, 0x01, 0x01, rate.code() << 5 | h, m, s, f, 0xF7] +} + +/// Quarter frame `piece` (0..8) of `time` (hours, minutes, seconds, frames): eight of them, a +/// quarter of a frame apart, carry the whole time, the frames' low nibble first. +fn quarter_frame(time: [u8; 4], rate: Rate, piece: u8) -> [u8; 2] { + let [h, m, s, f] = time; + let piece = piece & 7; + let nibble = match piece { + 0 => f, + 1 => f >> 4, + 2 => s, + 3 => s >> 4, + 4 => m, + 5 => m >> 4, + 6 => h, + _ => h >> 4 | rate.code() << 1, + }; + [QUARTER_FRAME, piece << 4 | nibble & 0x0F] +} + +/// All eight quarter-frame wire messages for a single time-code snapshot, in wire order. +/// +/// This is serialization only: the host must send each piece at the appropriate time and +/// account for transport direction/latency. Seconds use the same conversion as [`full_frame`]. +pub fn quarter_frames(secs: f64, rate: Rate) -> [[u8; 2]; 8] { + let time = timecode(secs, rate); + [0, 1, 2, 3, 4, 5, 6, 7].map(|piece| quarter_frame(time, rate, piece)) +} diff --git a/crates/midi/tests/it/lenient.rs b/crates/midi/tests/it/lenient.rs index 3d02995bc..0556c3859 100644 --- a/crates/midi/tests/it/lenient.rs +++ b/crates/midi/tests/it/lenient.rs @@ -33,8 +33,8 @@ const TWO: &[u8] = &[0x00, 0x91, 62, 100, 0x60, 0x81, 62, 0]; #[test] fn a_sound_file_reads_the_same_either_way_without_warnings() { let good = file(1, 96, &[ONE, TWO]); - let LenientRead { smf, warnings, end, .. } = read_smf_lenient(&good).unwrap(); - assert_eq!((keys(&smf), warnings.len()), (vec![vec![60], vec![62]], 0)); + let LenientRead { smf, warnings, end, over_limit, .. } = read_smf_lenient(&good).unwrap(); + assert_eq!((keys(&smf), warnings.len(), over_limit), (vec![vec![60], vec![62]], 0, false)); assert_eq!(smf, read_smf(&good).unwrap()); assert_eq!(end, 960, "the End of Track tick, at 960 ticks a quarter"); } @@ -122,15 +122,34 @@ fn a_file_of_any_size_is_read_into_a_bounded_number_of_events_and_warnings() { // Three bytes a note-on under running status: more events than are read. let mut body = vec![0x00, 0x90, 60, 100]; body.extend((0..MAX_EVENTS + 1000).flat_map(|i| [0x00, (i % 128) as u8, 1])); - let LenientRead { smf, warnings, .. } = read_smf_lenient(&file(1, 96, &[&body])).unwrap(); + let LenientRead { smf, warnings, over_limit, .. } = read_smf_lenient(&file(1, 96, &[&body])).unwrap(); assert_eq!(smf.tracks[0].sequence.notes.len(), MAX_EVENTS); assert!(warnings.iter().any(|w| w.contains("more events")), "{warnings:?}"); + assert!(over_limit, "the event limit left events out"); // Tracks of nothing, by the thousand: the count stops the reading. - let LenientRead { smf, warnings, .. } = read_smf_lenient(&file(1, 96, &vec![&[][..]; MAX_TRACKS + 5])).unwrap(); + let LenientRead { smf, warnings, over_limit, .. } = read_smf_lenient(&file(1, 96, &vec![&[][..]; MAX_TRACKS + 5])).unwrap(); assert!(smf.tracks.len() < MAX_TRACKS && warnings.iter().any(|w| w.contains("tracks"))); - // Every track damaged: never more than MAX_WARNINGS words. - let LenientRead { warnings, .. } = read_smf_lenient(&file(1, 96, &vec![&[0x00, 60][..]; 100])).unwrap(); + assert!(over_limit, "the track limit left tracks out"); + // Every track damaged: never more than MAX_WARNINGS words, and no limit was reached. + let LenientRead { warnings, over_limit, .. } = read_smf_lenient(&file(1, 96, &vec![&[0x00, 60][..]; 100])).unwrap(); assert_eq!(warnings.len(), MAX_WARNINGS); + assert!(!over_limit); +} + +#[test] +fn a_limit_reached_after_the_warnings_are_full_is_still_reported() { + // MAX_WARNINGS damaged tracks fill the warnings; the track after them holds more events than are + // read, so its warning is dropped, and over_limit is what says the file was cut. + let mut body = vec![0x00, 0x90, 60, 100]; + body.extend((0..MAX_EVENTS + 1000).flat_map(|i| [0x00, (i % 128) as u8, 1])); + let mut tracks = vec![&[0x00, 60][..]; MAX_WARNINGS]; + tracks.push(&body); + let LenientRead { warnings, over_limit, .. } = read_smf_lenient(&file(1, 96, &tracks)).unwrap(); + assert_eq!(warnings.len(), MAX_WARNINGS); + assert!(!warnings.iter().any(|w| w.contains("more events")), "the test needs the limit's warning dropped: {warnings:?}"); + assert!(over_limit); + // The strict reader stops at the first damaged track, before the limit. + assert!(!matches!(read_smf(&file(1, 96, &tracks)), Err(MidiError::TooManyEvents(_)) | Ok(_))); } #[test] diff --git a/crates/midi/tests/it/main.rs b/crates/midi/tests/it/main.rs index 368d7dc71..45f95c70c 100644 --- a/crates/midi/tests/it/main.rs +++ b/crates/midi/tests/it/main.rs @@ -3,3 +3,4 @@ mod lenient; mod sequence; mod smf; +mod sync; diff --git a/crates/midi/tests/it/sync.rs b/crates/midi/tests/it/sync.rs new file mode 100644 index 000000000..0a73faad7 --- /dev/null +++ b/crates/midi/tests/it/sync.rs @@ -0,0 +1,54 @@ +use craft_midi::sync::{CLOCK, CONTINUE, MAX_POSITION, Rate, SONG_POSITION, START, STOP, SyncMessage, full_frame, quarter_frames, song_position}; + +#[test] +fn transport_prefix_compatibility() { + for (status, expected) in [(CLOCK, SyncMessage::Clock), (START, SyncMessage::Start), (CONTINUE, SyncMessage::Continue), (STOP, SyncMessage::Stop)] + { + assert_eq!(SyncMessage::parse(&[status]), Some(expected)); + assert_eq!(SyncMessage::parse(&[status, 0, 0xff]), Some(expected)); + } + for invalid in [&[][..], &[0x90, 60, 127], &[SONG_POSITION], &[SONG_POSITION, 0], &[SONG_POSITION, 0x80, 0], &[SONG_POSITION, 0, 0x80]] { + assert_eq!(SyncMessage::parse(invalid), None); + } +} + +#[test] +fn song_position_preserves_clamping_and_seven_bit_order() { + for value in 0..=u16::MAX { + let bytes = song_position(value); + assert!(bytes[1] < 128 && bytes[2] < 128); + assert_eq!(SyncMessage::parse(&bytes), Some(SyncMessage::Position(value.min(MAX_POSITION)))); + } + assert_eq!(song_position(128), [0xf2, 0, 1]); + assert_eq!(SyncMessage::parse(&[0xf2, 1, 2, 0xff]), Some(SyncMessage::Position(257))); +} + +#[test] +fn full_frame_known_vectors_and_legacy_conversion() { + for (rate, bits) in [(Rate::Fps24, 0), (Rate::Fps25, 0x20), (Rate::Fps30, 0x60)] { + assert_eq!(full_frame(3723.0, rate), [0xf0, 0x7f, 0x7f, 1, 1, bits | 1, 2, 3, 0, 0xf7]); + assert_eq!(full_frame(86400.0, rate), full_frame(0.0, rate)); + assert_eq!(full_frame(-1.0, rate), full_frame(0.0, rate)); + assert_eq!(full_frame(f64::NAN, rate), full_frame(0.0, rate)); + assert_eq!(full_frame(1.0 / f64::from(rate.fps()), rate)[8], 1); + } + assert_eq!(Rate::of(24), Rate::Fps24); + assert_eq!(Rate::of(30), Rate::Fps30); + assert_eq!(Rate::of(29), Rate::Fps25); +} + +#[test] +fn quarter_frames_known_vector() { + assert_eq!( + quarter_frames(3723.04, Rate::Fps25), + [[0xf1, 1], [0xf1, 0x10], [0xf1, 0x23], [0xf1, 0x30], [0xf1, 0x42], [0xf1, 0x50], [0xf1, 0x61], [0xf1, 0x72]] + ); + for rate in [Rate::Fps24, Rate::Fps25, Rate::Fps30] { + for secs in [0.0, 59.99, 3599.99, 86399.99, f64::INFINITY, f64::NEG_INFINITY, f64::NAN] { + for bytes in quarter_frames(secs, rate) { + assert_eq!(bytes[0], 0xf1); + assert!(bytes[1] < 128); + } + } + } +} diff --git a/crates/odf/src/text/tests_more/lossless.rs b/crates/odf/src/text/tests_more/lossless.rs index 645c0b918..7d05e3491 100644 --- a/crates/odf/src/text/tests_more/lossless.rs +++ b/crates/odf/src/text/tests_more/lossless.rs @@ -345,8 +345,14 @@ const SAMPLES: [Sample; 18] = [ /// Whether `xml` is well-formed: every element closed, in order, once. fn well_formed(xml: &[u8]) -> bool { - let limits = - craft_xml::Limits { max_input: usize::MAX, max_depth: usize::MAX, max_nodes: usize::MAX, max_attrs: usize::MAX, max_attrs_total: usize::MAX }; + let limits = craft_xml::Limits { + max_input: usize::MAX, + max_depth: usize::MAX, + max_nodes: usize::MAX, + max_elements: usize::MAX, + max_attrs: usize::MAX, + max_attrs_total: usize::MAX, + }; craft_xml::Options::default().strict().with_limits(limits).parse(xml).is_ok() } diff --git a/crates/odf/src/text/xml.rs b/crates/odf/src/text/xml.rs index ef5a0e0d1..d96ee4917 100644 --- a/crates/odf/src/text/xml.rs +++ b/crates/odf/src/text/xml.rs @@ -45,8 +45,14 @@ pub(super) fn events(xml: &[u8], mut f: impl FnMut(Ev)) { pub(super) fn events_at(xml: &[u8], mut f: impl FnMut(Ev, (usize, usize))) { // Names and attributes as written; no limit but the input's own size (each part is at most a // package entry), and at most 128 attributes kept per element. - let limits = - craft_xml::Limits { max_input: usize::MAX, max_depth: usize::MAX, max_nodes: usize::MAX, max_attrs: usize::MAX, max_attrs_total: usize::MAX }; + let limits = craft_xml::Limits { + max_input: usize::MAX, + max_depth: usize::MAX, + max_nodes: usize::MAX, + max_elements: usize::MAX, + max_attrs: usize::MAX, + max_attrs_total: usize::MAX, + }; let opts = craft_xml::Options::default().with_limits(limits); let mut events = opts.events(xml); // Malformed XML ends the stream. diff --git a/crates/ora/README.md b/crates/ora/README.md index 70cdbd932..488268b3c 100644 --- a/crates/ora/README.md +++ b/crates/ora/README.md @@ -29,6 +29,7 @@ means. `SVG_COMPOSITE_OPS` lists the names the specification defines. | Elements under the root stack | 8192 (`MAX_NODES`) | | `stack.xml` | 16 MiB, 512 levels of nesting, no document type declaration | | An entry | the caller's limit; `MAX_ENTRY` (512 MiB) is the suggested one for a layer image | +| All entries read from one archive | 4 GiB (`MAX_TOTAL`) | ## ZIP diff --git a/crates/ora/src/lib.rs b/crates/ora/src/lib.rs index 69d494d0d..f39d13f06 100644 --- a/crates/ora/src/lib.rs +++ b/crates/ora/src/lib.rs @@ -51,6 +51,10 @@ pub const MAX_STACK_XML: usize = 16 << 20; pub const MAX_ENTRY: usize = 512 << 20; /// Most entries the archive may declare; checked before the archive is indexed. pub const MAX_ENTRIES: u64 = 100_000; +/// Most bytes all the entries read from one archive may expand to together. Each layer image may +/// be [`MAX_ENTRY`] on its own, so without a total a document of many layers could spend far more +/// than one open should. +pub const MAX_TOTAL: u64 = 4 << 30; /// Deepest element nesting of `stack.xml`. pub const MAX_XML_DEPTH: usize = 512; @@ -363,8 +367,13 @@ pub struct Archive<'a> { impl<'a> Archive<'a> { /// Opens the archive, checks its `mimetype` and reads `stack.xml`. pub fn open(bytes: &'a [u8]) -> Result<Archive<'a>> { - let mut zip = - craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes: u64::MAX }).map_err(zip_error)?; + Self::open_with_total(bytes, MAX_TOTAL) + } + + /// [`Archive::open`], allowing the entries read from the archive to expand to + /// `max_total_bytes` together ([`MAX_TOTAL`] is the default). + pub(crate) fn open_with_total(bytes: &'a [u8], max_total_bytes: u64) -> Result<Archive<'a>> { + let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes }).map_err(zip_error)?; // `zip` keeps one entry of a repeated name; which one the writer meant is not known. if zip.has_duplicate_names() { return Err(invalid("two entries of the archive share a name")); diff --git a/crates/ora/src/tests.rs b/crates/ora/src/tests.rs index cfaac7c41..f8773f79c 100644 --- a/crates/ora/src/tests.rs +++ b/crates/ora/src/tests.rs @@ -315,6 +315,19 @@ fn an_archive_declaring_too_many_entries_is_refused_before_it_is_indexed() { ); } +/// Every entry read is charged to one document-wide total, so an archive of many individually +/// allowed entries cannot spend an unbounded amount of memory in one open. +#[test] +fn entries_are_charged_to_one_document_wide_total() { + let stack = "<image w='1' h='1'><stack/></image>"; + let bytes = archive(stack, &[("a.png", vec![1; 100]), ("b.png", vec![2; 100])]); + // Room for `stack.xml` and one image, not two. + let mut a = Archive::open_with_total(&bytes, stack.len() as u64 + 120).unwrap(); + assert_eq!(a.entry("a.png", MAX_ENTRY).unwrap().unwrap(), vec![1; 100]); + let err = a.entry("b.png", MAX_ENTRY).unwrap_err(); + assert!(matches!(&err, Error::Invalid(m) if m.contains("b.png") && m.contains("may expand to")), "{err:?}"); +} + /// Two entries of one name: `zip` keeps one, and which one the writer meant is not known. #[test] fn two_entries_of_one_name_are_refused() { diff --git a/crates/pcraft-bundle/src/lib.rs b/crates/pcraft-bundle/src/lib.rs index acbe739b6..1368fa747 100644 --- a/crates/pcraft-bundle/src/lib.rs +++ b/crates/pcraft-bundle/src/lib.rs @@ -370,7 +370,8 @@ impl DirectoryBundleWriter { /// Saves an entry set incrementally. Existing objects are reused only after a hash check; /// unchanged file signatures may skip checks until they enter the rolling verification /// window. The manifest is atomically published last, then stale previews and objects are - /// collected while the bundle lock is held. + /// collected while the bundle lock is held. Collection is best-effort after publication: + /// inaccessible or unsafe leftovers cannot turn a committed save into a reported failure. pub fn save_directory(&mut self, root: &Path, bundle: ZipBundleWriter) -> Result<DirectoryStats> { if !bundle.entries.contains_key(craft_pcraft_format::MANIFEST) { return Err(Error::InvalidBundle("manifest not set".into())); @@ -401,6 +402,10 @@ impl DirectoryBundleWriter { Err(std::fs::TryLockError::Error(_)) => break None, } }; + // A known unsafe manifest cannot be published. Refuse it before writing objects or + // previews, and still recheck immediately before publication below. + let manifest_path = root.join(craft_pcraft_format::MANIFEST); + refuse_symlink(&manifest_path)?; self.generation = self.generation.saturating_add(1); let generation = self.generation; let recheck = self.rolling_recheck(&bundle.entries); @@ -449,43 +454,33 @@ impl DirectoryBundleWriter { } let manifest = bundle.entries.get(craft_pcraft_format::MANIFEST).ok_or_else(|| Error::InvalidBundle("manifest not set".into()))?; - let manifest_path = root.join(craft_pcraft_format::MANIFEST); refuse_symlink(&manifest_path)?; craft_atomic::atomic_write(&manifest_path, manifest).map_err(io_error)?; stats.written = stats.written.saturating_add(1); - let mut removed_paths = Vec::new(); + // The durable manifest is the commit boundary. Cleanup owns only canonical regular + // object files and previews; leave unsafe, inaccessible or locked leftovers for later. for kind in [craft_pcraft_format::TILES_DIR, craft_pcraft_format::BLOBS_DIR] { let dir = root.join(kind); - if !dir.exists() { + if !cleanup_directory(&dir) { continue; } - refuse_symlink(&dir)?; - for entry in fs::read_dir(&dir).map_err(io_error)? { - let entry = entry.map_err(io_error)?; + let Ok(entries) = fs::read_dir(&dir) else { continue }; + for entry in entries { + let Ok(entry) = entry else { continue }; let name = entry.file_name(); let path = format!("{kind}/{}", name.to_string_lossy()); - if is_object_path(&path) && !bundle.entries.contains_key(&path) { - let metadata = fs::symlink_metadata(entry.path()).map_err(io_error)?; - if metadata.file_type().is_symlink() || !metadata.is_file() { - return Err(Error::InvalidBundle(format!("refusing to collect non-file object {path}"))); - } - fs::remove_file(entry.path()).map_err(io_error)?; - removed_paths.push(path); + if is_object_path(&path) && !bundle.entries.contains_key(&path) && remove_cleanup_file(&entry.path()) { stats.removed = stats.removed.saturating_add(1); } } } for path in [craft_pcraft_format::THUMB, craft_pcraft_format::COMPOSITE, craft_pcraft_format::FULL_COMPOSITE] { if !bundle.entries.contains_key(path) { - let target = root.join(path); - refuse_symlink(&target)?; - if fs::symlink_metadata(&target).is_ok() { - fs::remove_file(&target).map_err(io_error)?; - } + let _ = remove_cleanup_file(&root.join(path)); } } - self.verified.retain(|path, _| bundle.entries.contains_key(path) && !removed_paths.contains(path)); + self.verified.retain(|path, _| bundle.entries.contains_key(path)); Ok(stats) } @@ -510,7 +505,32 @@ impl DirectoryBundleWriter { } fn is_object_path(path: &str) -> bool { - path.starts_with("tiles/") || path.starts_with("blobs/") + valid_object_path(path) +} + +/// Do not traverse symlinked object/preview directories, including Windows junctions. +fn cleanup_directory(path: &Path) -> bool { + fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_dir() && !cleanup_link(&metadata)) +} + +fn cleanup_link(metadata: &fs::Metadata) -> bool { + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + metadata.file_attributes() & 0x400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT includes junctions. + } + #[cfg(not(windows))] + { + metadata.file_type().is_symlink() + } +} + +/// Cleanup never follows or removes a directory/link and never reports a post-commit failure. +fn remove_cleanup_file(path: &Path) -> bool { + if path.parent().is_none_or(|parent| !cleanup_directory(parent)) { + return false; + } + fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_file() && !cleanup_link(&metadata)) && fs::remove_file(path).is_ok() } fn file_signature(path: &Path) -> Result<Option<FileSignature>> { diff --git a/crates/pcraft-bundle/tests/directory_cleanup.rs b/crates/pcraft-bundle/tests/directory_cleanup.rs new file mode 100644 index 000000000..29015bd23 --- /dev/null +++ b/crates/pcraft-bundle/tests/directory_cleanup.rs @@ -0,0 +1,344 @@ +//! Publication succeeds independently of best-effort cleanup of the previous entry set. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use craft_pcraft_bundle::{DirectoryBundle, DirectoryBundleWriter, Limits, ObjectKind, ZipBundleWriter}; +use craft_pcraft_format::{COMPOSITE, FULL_COMPOSITE, MANIFEST, THUMB}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +const OLD: &[u8] = br#"{"revision":1}"#; +const NEW: &[u8] = br#"{"revision":2}"#; + +struct Temporary(PathBuf); + +impl Temporary { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!("craft-bundle-cleanup-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + fs::create_dir(&path).unwrap(); + Self(path) + } + + fn bundle(&self) -> PathBuf { + self.0.join("document.pcraft") + } +} + +impl Drop for Temporary { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn entries(manifest: &[u8]) -> ZipBundleWriter { + let mut bundle = ZipBundleWriter::default(); + bundle.set_manifest(manifest.to_vec()).unwrap(); + bundle +} + +fn assert_manifest(root: &Path, expected: &[u8]) { + assert_eq!(fs::read(root.join(MANIFEST)).unwrap(), expected); + assert_eq!(DirectoryBundle::open(root, Limits::default()).unwrap().manifest().unwrap(), expected); +} + +#[test] +fn non_file_stale_object_does_not_fail_the_committed_save() { + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + let stuck = root.join("tiles").join(format!("{}.zst", "0".repeat(64))); + fs::create_dir_all(stuck.join("inner")).unwrap(); + fs::write(stuck.join("inner/keep"), b"not an object file").unwrap(); + + let stats = writer.save_directory(&root, entries(NEW)).expect("cleanup cannot fail after manifest publication"); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 0); + assert_eq!(fs::read(stuck.join("inner/keep")).unwrap(), b"not an object file"); +} + +#[test] +fn cleanup_removes_only_canonical_stale_regular_objects_and_reuses_current_objects() { + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + let mut first = entries(OLD); + let retained = first.add_object(ObjectKind::Tile, b"still referenced").unwrap(); + let stale = first.add_object(ObjectKind::Blob, b"old blob").unwrap(); + for preview in [THUMB, COMPOSITE, FULL_COMPOSITE] { + first.set_preview(preview, b"old preview".to_vec()).unwrap(); + } + writer.save_directory(&root, first).unwrap(); + let retained_bytes = fs::read(root.join(&retained)).unwrap(); + let unrelated = [ + "tiles/personal-notes.zst".to_string(), + "blobs/012345.zst".to_string(), + format!("blobs/{}.zst", "A".repeat(64)), + format!("tiles/{}.zst.backup", "b".repeat(64)), + ]; + for path in &unrelated { + fs::write(root.join(path), b"unrelated").unwrap(); + } + let nested = root.join("blobs/not-an-object-folder"); + fs::create_dir(&nested).unwrap(); + fs::write(nested.join(format!("{}.zst", "c".repeat(64))), b"unrelated nested file").unwrap(); + let mut second = entries(NEW); + assert_eq!(second.add_object(ObjectKind::Tile, b"still referenced").unwrap(), retained); + let stats = writer.save_directory(&root, second).unwrap(); + + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 1); + assert_eq!(stats.reused, 1); + assert_eq!(stats.reused_objects.as_slice(), std::slice::from_ref(&retained)); + assert!(stats.written_objects.is_empty()); + assert!(!root.join(stale).exists()); + assert_eq!(fs::read(root.join(retained)).unwrap(), retained_bytes); + for path in unrelated { + assert_eq!(fs::read(root.join(path)).unwrap(), b"unrelated"); + } + assert!(nested.is_dir()); + for preview in [THUMB, COMPOSITE, FULL_COMPOSITE] { + assert!(!root.join(preview).exists()); + } +} + +#[test] +fn stale_preview_directories_are_preserved_after_commit() { + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + for preview in [THUMB, COMPOSITE, FULL_COMPOSITE] { + fs::create_dir_all(root.join(preview)).unwrap(); + fs::write(root.join(preview).join("keep"), b"directory contents").unwrap(); + } + let stats = writer.save_directory(&root, entries(NEW)).unwrap(); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 0); + for preview in [THUMB, COMPOSITE, FULL_COMPOSITE] { + assert_eq!(fs::read(root.join(preview).join("keep")).unwrap(), b"directory contents"); + } +} + +#[test] +fn required_non_file_objects_and_previews_fail_before_manifest_publication() { + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + let mut changed = entries(NEW); + let object = changed.add_object(ObjectKind::Tile, b"required object").unwrap(); + fs::create_dir_all(root.join(&object)).unwrap(); + assert!(writer.save_directory(&root, changed).is_err()); + assert_manifest(&root, OLD); + + for preview in [THUMB, COMPOSITE] { + fs::create_dir_all(root.join(preview)).unwrap(); + let mut changed = entries(NEW); + changed.set_preview(preview, b"required preview".to_vec()).unwrap(); + assert!(writer.save_directory(&root, changed).is_err()); + assert_manifest(&root, OLD); + } +} + +#[cfg(windows)] +#[test] +fn locked_stale_object_and_preview_do_not_fail_commit_and_are_collected_on_retry() { + use std::fs::OpenOptions; + use std::os::windows::fs::OpenOptionsExt; + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + let mut first = entries(OLD); + let stale = first.add_object(ObjectKind::Tile, b"locked stale tile").unwrap(); + first.set_preview(FULL_COMPOSITE, b"locked preview".to_vec()).unwrap(); + writer.save_directory(&root, first).unwrap(); + let tile_lock = OpenOptions::new().read(true).share_mode(0).open(root.join(&stale)).unwrap(); + let preview_lock = OpenOptions::new().read(true).share_mode(0).open(root.join(FULL_COMPOSITE)).unwrap(); + let stats = writer.save_directory(&root, entries(NEW)).unwrap(); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 0); + assert!(root.join(&stale).exists()); + assert!(root.join(FULL_COMPOSITE).exists()); + drop(tile_lock); + drop(preview_lock); + let retry = writer.save_directory(&root, entries(NEW)).unwrap(); + assert_manifest(&root, NEW); + assert_eq!(retry.removed, 1); + assert!(!root.join(stale).exists()); + assert!(!root.join(FULL_COMPOSITE).exists()); +} + +#[cfg(unix)] +#[test] +fn cleanup_preserves_symlinks_and_does_not_traverse_linked_directories() { + use std::os::unix::fs::symlink; + let temp = Temporary::new(); + let root = temp.bundle(); + let outside = temp.0.join("outside"); + fs::create_dir(&outside).unwrap(); + let object_name = format!("{}.zst", "d".repeat(64)); + fs::write(outside.join(&object_name), b"outside object").unwrap(); + fs::write(outside.join("preview.png"), b"outside preview").unwrap(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + symlink(&outside, root.join("blobs")).unwrap(); + symlink(&outside, root.join("composite")).unwrap(); + symlink(outside.join("preview.png"), root.join(THUMB)).unwrap(); + fs::create_dir(root.join("tiles")).unwrap(); + let linked_object = root.join("tiles").join(&object_name); + symlink(outside.join(&object_name), &linked_object).unwrap(); + let stats = writer.save_directory(&root, entries(NEW)).unwrap(); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 0); + assert_eq!(fs::read(outside.join(object_name)).unwrap(), b"outside object"); + assert_eq!(fs::read(outside.join("preview.png")).unwrap(), b"outside preview"); + for link in [root.join("blobs"), root.join("composite"), root.join(THUMB), linked_object] { + assert!(fs::symlink_metadata(link).unwrap().file_type().is_symlink()); + } +} + +#[cfg(unix)] +#[test] +fn required_symlink_objects_and_previews_still_fail_before_commit() { + use std::os::unix::fs::symlink; + let temp = Temporary::new(); + let root = temp.bundle(); + let outside = temp.0.join("outside-file"); + fs::write(&outside, b"unchanged outside bytes").unwrap(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + let mut changed = entries(NEW); + let object = changed.add_object(ObjectKind::Tile, b"required object").unwrap(); + fs::create_dir(root.join("tiles")).unwrap(); + symlink(&outside, root.join(object)).unwrap(); + assert!(writer.save_directory(&root, changed).is_err()); + assert_manifest(&root, OLD); + symlink(&outside, root.join(THUMB)).unwrap(); + let mut changed = entries(NEW); + changed.set_preview(THUMB, b"new preview".to_vec()).unwrap(); + assert!(writer.save_directory(&root, changed).is_err()); + assert_manifest(&root, OLD); + assert_eq!(fs::read(outside).unwrap(), b"unchanged outside bytes"); +} + +#[cfg(windows)] +#[test] +fn cleanup_does_not_traverse_windows_directory_junctions() { + use std::os::windows::process::CommandExt; + struct Junction(PathBuf); + impl Drop for Junction { + fn drop(&mut self) { + let _ = fs::remove_dir(&self.0); + } + } + fn junction(link: PathBuf, target: &Path) -> Junction { + // Fixture-owned absolute paths only; junctions require no symlink privilege. + assert!(link.is_absolute() && target.is_absolute()); + let output = std::process::Command::new("cmd") + .args(["/C", "mklink", "/J"]) + .arg(&link) + .arg(target) + .creation_flags(0x0800_0000) // CREATE_NO_WINDOW + .output() + .unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + Junction(link) + } + let temp = Temporary::new(); + let root = temp.bundle(); + let outside = temp.0.join("outside"); + fs::create_dir(&outside).unwrap(); + let object_name = format!("{}.zst", "e".repeat(64)); + fs::write(outside.join(&object_name), b"outside object").unwrap(); + fs::write(outside.join("preview.png"), b"outside preview").unwrap(); + fs::write(outside.join("full.png"), b"outside full preview").unwrap(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + let _objects = junction(root.join("blobs"), &outside); + let _previews = junction(root.join("composite"), &outside); + let stats = writer.save_directory(&root, entries(NEW)).unwrap(); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 0); + assert_eq!(fs::read(outside.join(object_name)).unwrap(), b"outside object"); + assert_eq!(fs::read(outside.join("preview.png")).unwrap(), b"outside preview"); + assert_eq!(fs::read(outside.join("full.png")).unwrap(), b"outside full preview"); + assert!(root.join("blobs").exists()); + assert!(root.join("composite").exists()); +} + +#[cfg(any(unix, windows))] +#[test] +fn manifest_symlink_is_refused_before_writing_any_objects_or_previews() { + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + assert_manifest(&root, OLD); // Ordinary publication remains supported. + let external = temp.0.join("external-manifest.json"); + fs::write(&external, b"unchanged external manifest").unwrap(); + fs::remove_file(root.join(MANIFEST)).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(&external, root.join(MANIFEST)).unwrap(); + #[cfg(windows)] + if let Err(error) = std::os::windows::fs::symlink_file(&external, root.join(MANIFEST)) { + if error.raw_os_error() == Some(1314) || error.kind() == std::io::ErrorKind::Unsupported { + eprintln!("SKIP manifest symlink fixture: {error}"); + return; + } + panic!("create manifest symlink fixture: {error}"); + } + let mut changed = entries(NEW); + changed.add_object(ObjectKind::Tile, b"must not write tile").unwrap(); + changed.add_object(ObjectKind::Blob, b"must not write blob").unwrap(); + changed.set_preview(THUMB, b"must not write thumbnail".to_vec()).unwrap(); + changed.set_preview(FULL_COMPOSITE, b"must not write composite".to_vec()).unwrap(); + assert!(writer.save_directory(&root, changed).is_err()); + assert_eq!(fs::read(&external).unwrap(), b"unchanged external manifest"); + assert!(fs::symlink_metadata(root.join(MANIFEST)).unwrap().file_type().is_symlink()); + for unwritten in ["tiles", "blobs", THUMB, "composite"] { + assert!(!root.join(unwritten).exists(), "manifest refusal must precede {unwritten} publication"); + } +} + +#[cfg(unix)] +#[test] +fn chosen_root_symlink_cleanup_works_with_search_only_root_and_composite_permissions() { + use std::os::unix::fs::{PermissionsExt, symlink}; + struct Restore(PathBuf, fs::Permissions); + impl Restore { + fn restrict(path: &Path) -> Self { + let old = fs::metadata(path).unwrap().permissions(); + fs::set_permissions(path, fs::Permissions::from_mode(0o300)).unwrap(); + Self(path.to_path_buf(), old) + } + } + impl Drop for Restore { + fn drop(&mut self) { + let _ = fs::set_permissions(&self.0, self.1.clone()); + } + } + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + let mut first = entries(OLD); + let stale = first.add_object(ObjectKind::Blob, b"stale blob").unwrap(); + first.set_preview(THUMB, b"stale thumbnail".to_vec()).unwrap(); + first.set_preview(COMPOSITE, b"stale preview".to_vec()).unwrap(); + writer.save_directory(&root, first).unwrap(); + let chosen = temp.0.join("chosen.pcraft"); + symlink(&root, &chosen).unwrap(); + let composite_mode = Restore::restrict(&root.join("composite")); + let root_mode = Restore::restrict(&root); + let result = writer.save_directory(&chosen, entries(NEW)); + drop(root_mode); + drop(composite_mode); + let stats = result.expect("chosen root resolves before cleanup; traversal does not require directory read permission"); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 1); + assert!(!root.join(stale).exists()); + assert!(!root.join(THUMB).exists()); + assert!(!root.join(COMPOSITE).exists()); + assert!(fs::symlink_metadata(chosen).unwrap().file_type().is_symlink()); +} diff --git a/crates/pcraft-format/Cargo.toml b/crates/pcraft-format/Cargo.toml index ce1d6873f..f54bb0c82 100644 --- a/crates/pcraft-format/Cargo.toml +++ b/crates/pcraft-format/Cargo.toml @@ -16,3 +16,6 @@ serde = { workspace = true } # the nesting against `Limits::max_depth` before parsing. serde_json = { workspace = true, features = ["unbounded_depth"] } thiserror = { workspace = true } + +# Same pure-Rust backend as the PhotoCraft source codec. MIT OR Apache-2.0. +flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } diff --git a/crates/pcraft-format/README.md b/crates/pcraft-format/README.md index 5d8869b74..f5b0dfa73 100644 --- a/crates/pcraft-format/README.md +++ b/crates/pcraft-format/README.md @@ -5,7 +5,7 @@ references, the entry paths, the limits for reading a manifest, and the runner f migrations. The document model stays in PhotoCraft and is a type parameter here. The crate does not read ZIP archives, open files or decode tiles. No `unsafe`, no panics on malformed input, and it builds for `wasm32-unknown-unknown`. The dependencies are `serde`, `serde_json` -and `thiserror`. +`thiserror`, and `flate2`. ```toml craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "<commit>" } @@ -120,3 +120,15 @@ limits.max_manifest_bytes = 16 << 20; `.github/workflows/pcraft-format.yml` runs fmt, clippy and the tests on Linux and Windows, and a `wasm32-unknown-unknown` check. + +## Brush-tip envelope + +`tip::encode`, `tip::decode` and `tip::decode_with_max_side` share PhotoCraft's PCTIP1 +brush-tip codec: a six-byte magic, one-byte depth, little-endian width/height and zlib +samples. Eight-bit-compatible samples use 8 bits, otherwise 16-bit little-endian. +Dimensions, sample count, exact inflated length and caller preview side limits are checked. +Preset group schemas, tip hashes and storage policy remain application-owned. + +Ported from `storytold/photocraft` commit `19aec5eb44131de44361189d64910e7b3e19e57c`, +`crates/engine/src/preset_store.rs`. Original codec by Brandon Thomas (PhotoCraft #82), +with later bounds/backend/storage changes by David Mann and FinnNk, under MIT OR Apache-2.0. diff --git a/crates/pcraft-format/src/lib.rs b/crates/pcraft-format/src/lib.rs index 18868da2d..f12bc5213 100644 --- a/crates/pcraft-format/src/lib.rs +++ b/crates/pcraft-format/src/lib.rs @@ -36,6 +36,9 @@ mod limits; mod migrate; mod read; +/// Lossless brush-tip envelope used by PhotoCraft preset libraries. +pub mod tip; + use serde::{Deserialize, Serialize}; pub use limits::{ diff --git a/crates/pcraft-format/src/tip.rs b/crates/pcraft-format/src/tip.rs new file mode 100644 index 000000000..9b971f5d9 --- /dev/null +++ b/crates/pcraft-format/src/tip.rs @@ -0,0 +1,102 @@ +//! PhotoCraft's PCTIP1 brush-tip envelope and lossless grayscale sample serialization. +//! +//! Extracted from PhotoCraft preset_store.rs at 19aec5eb44131de44361189d64910e7b3e19e57c. +//! Original implementation: Brandon Thomas; subsequent codec changes: David Mann and FinnNk. +//! Group schemas, file naming, content hashes and storage policy remain with the application. + +/// Largest accepted tip side. +pub const MAX_SIDE: u32 = 16384; +/// Largest accepted sample count. +pub const MAX_SAMPLES: u64 = 1 << 26; +const TIP_MAGIC: &[u8; 6] = b"PCTIP1"; +const TIP_HEADER: usize = 6 + 1 + 4 + 4; + +/// Decoded grayscale samples. Eight-bit samples expand losslessly by multiplication by 257. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Tip { + pub width: u32, + pub height: u32, + pub data: Vec<u16>, +} + +/// `PCTIP1`, bits (8|16), width, height (u32 LE), then the zlib-deflated samples. +/// Returns an empty vector for invalid dimensions/sample counts or compression failure. +pub fn encode(width: u32, height: u32, data: &[u16]) -> Vec<u8> { + use std::io::Write; + let count = u64::from(width) * u64::from(height); + if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE || count > MAX_SAMPLES || count != data.len() as u64 { + return Vec::new(); + } + let eight = data.iter().all(|v| v % 257 == 0); + let mut out = Vec::with_capacity(TIP_HEADER + data.len() / 4); + out.extend_from_slice(TIP_MAGIC); + out.push(if eight { 8 } else { 16 }); + out.extend_from_slice(&width.to_le_bytes()); + out.extend_from_slice(&height.to_le_bytes()); + // Level 3: zlib-rs level 1 writes static Huffman blocks only, 13-30% bigger than miniz's level 1. + let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::new(3)); + let mut buf = Vec::with_capacity(8192); + let mut ok = true; + for chunk in data.chunks(4096) { + buf.clear(); + if eight { + buf.extend(chunk.iter().map(|v| (v / 257) as u8)); + } else { + for v in chunk { + buf.extend_from_slice(&v.to_le_bytes()); + } + } + ok &= z.write_all(&buf).is_ok(); + } + match z.finish() { + Ok(v) if ok => v, + _ => Vec::new(), + } +} + +/// Inverse of [`encode`]; any malformed, truncated or oversized input is an error. +pub fn decode(bytes: &[u8]) -> Result<Tip, String> { + decode_with_max_side(bytes, MAX_SIDE) +} + +/// [`decode`] refusing (before inflating anything) a bitmap with a side over `max_side`. +pub fn decode_with_max_side(bytes: &[u8], max_side: u32) -> Result<Tip, String> { + let head = bytes.get(..TIP_HEADER).ok_or("truncated tip header")?; + if &head[..6] != TIP_MAGIC { + return Err("not a PhotoCraft tip".into()); + } + let bits = head[6]; + let u32_at = |i: usize| u32::from_le_bytes([head[i], head[i + 1], head[i + 2], head[i + 3]]); + let (w, h) = (u32_at(7), u32_at(11)); + if w == 0 || h == 0 || w > MAX_SIDE.min(max_side) || h > MAX_SIDE.min(max_side) { + return Err(format!("bad tip size {w}×{h}")); + } + let n = u64::from(w) * u64::from(h); + if n > MAX_SAMPLES { + return Err(format!("tip too large ({w}×{h})")); + } + let bytes_per = match bits { + 8 => 1u64, + 16 => 2, + b => return Err(format!("unsupported tip depth {b}")), + }; + let want = n * bytes_per; + // One byte beyond the declared size detects overlong output, without allocating for + // an attacker-controlled expansion. Require the zlib trailer, not merely enough samples. + let mut raw = Vec::with_capacity(want as usize + 1); + let status = flate2::Decompress::new(true) + .decompress_vec(&bytes[TIP_HEADER..], &mut raw, flate2::FlushDecompress::Finish) + .map_err(|e| format!("tip data: {e}"))?; + if status != flate2::Status::StreamEnd { + return Err("tip data: truncated or oversized zlib stream".into()); + } + if raw.len() as u64 != want { + return Err(format!("tip data has {} bytes, expected {want}", raw.len())); + } + let data: Vec<u16> = if bits == 8 { + raw.iter().map(|&v| u16::from(v) * 257).collect() + } else { + raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect() + }; + Ok(Tip { width: w, height: h, data }) +} diff --git a/crates/pcraft-format/tests/tip.rs b/crates/pcraft-format/tests/tip.rs new file mode 100644 index 000000000..e54b44ac8 --- /dev/null +++ b/crates/pcraft-format/tests/tip.rs @@ -0,0 +1,58 @@ +use craft_pcraft_format::tip::{MAX_SAMPLES, MAX_SIDE, decode, decode_with_max_side, encode}; +use std::io::Write; + +fn fixture(bits: u8, width: u32, height: u32, samples: &[u8]) -> Vec<u8> { + let mut out = b"PCTIP1".to_vec(); + out.push(bits); + out.extend(width.to_le_bytes()); + out.extend(height.to_le_bytes()); + let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::new(3)); + z.write_all(samples).unwrap(); + z.finish().unwrap() +} + +#[test] +fn legacy_eight_and_sixteen_bit_fixtures_and_roundtrips() { + for (bits, raw, samples) in [(8, vec![0, 128, 255], vec![0, 32896, 65535]), (16, vec![1, 0, 52, 18, 255, 255], vec![1, 0x1234, 65535])] { + let legacy = fixture(bits, 3, 1, &raw); + let tip = decode(&legacy).unwrap(); + assert_eq!((tip.width, tip.height), (3, 1)); + assert_eq!(tip.data, samples); + let encoded = encode(3, 1, &samples); + assert_eq!(&encoded[..15], &legacy[..15]); + assert_eq!(decode(&encoded).unwrap(), tip); + } +} + +#[test] +fn checks_headers_limits_and_sample_lengths() { + let good = fixture(8, 1, 1, &[255]); + for n in 0..good.len() { + assert!(decode(&good[..n]).is_err(), "truncation at {n}"); + } + let mut bad = good.clone(); + bad[0] = b'X'; + assert!(decode(&bad).is_err()); + for (bits, w, h) in [(7, 1, 1), (8, 0, 1), (8, 1, 0), (8, MAX_SIDE + 1, 1), (8, MAX_SIDE, MAX_SIDE)] { + assert!(decode(&fixture(bits, w, h, &[])).is_err()); + } + assert!(MAX_SAMPLES < u64::from(MAX_SIDE) * u64::from(MAX_SIDE)); + for raw in [vec![], vec![0, 1], vec![0; 10000]] { + assert!(decode(&fixture(8, 1, 1, &raw)).is_err()); + } + assert!(decode(&fixture(16, 1, 1, &[1])).is_err()); + let mut checksum = good; + *checksum.last_mut().unwrap() ^= 1; + assert!(decode(&checksum).is_err()); + assert!(encode(0, 1, &[]).is_empty()); + assert!(encode(1, 1, &[]).is_empty()); + assert!(encode(MAX_SIDE + 1, 1, &[0]).is_empty()); +} + +#[test] +fn preview_side_limit_is_checked_before_inflation() { + let good = encode(2, 1, &[0, 65535]); + assert!(decode_with_max_side(&good, 1).is_err()); + assert!(decode_with_max_side(&good, 2).is_ok()); + assert!(decode_with_max_side(&good, 0).is_err()); +} diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index b370416ab..266297f42 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -17,7 +17,9 @@ interpret = ["read", "dep:hayro-interpret"] paths = ["interpret", "dep:kurbo"] raster = ["interpret", "dep:hayro", "dep:bytemuck"] write = ["dep:krilla", "dep:thiserror"] +write-svg = ["write", "dep:craft-svg", "dep:krilla-svg", "dep:usvg", "craft-svg/tree-text"] write-pdf = ["write", "krilla/pdf"] +write-raster = ["dep:flate2", "dep:roxmltree"] write-simple-text = ["write", "krilla/simple-text"] filters = ["dep:craft-stream-codecs", "dep:flate2", "dep:thiserror"] cos = ["crypt", "filters", "dep:chrono", "dep:js-sys", "dep:wasm-bindgen"] @@ -29,10 +31,14 @@ hayro-interpret = { workspace = true, optional = true } hayro = { workspace = true, optional = true } bytemuck = { workspace = true, optional = true } krilla = { workspace = true, optional = true } +craft-svg = { workspace = true, optional = true } +krilla-svg = { version = "=0.8.1", optional = true } +usvg = { version = "=0.47.0", features = ["text"], optional = true } thiserror = { workspace = true, optional = true } +flate2 = { version = "1.1", default-features = false, features = ["zlib-rs"], optional = true } +roxmltree = { version = "0.21", optional = true } # The filter chain (`filters`). flate2 with zlib-rs, the backend the chain's Flate prices were measured on. craft-stream-codecs = { workspace = true, optional = true } -flate2 = { version = "1.1", default-features = false, features = ["zlib-rs"], optional = true } # The standard security handler (`crypt`): pure Rust, MIT OR Apache-2.0, builds for wasm. aes = { version = "0.9", optional = true } md-5 = { version = "0.11", optional = true } diff --git a/crates/pdf/README.md b/crates/pdf/README.md index 18d3d25a9..210b79849 100644 --- a/crates/pdf/README.md +++ b/crates/pdf/README.md @@ -10,6 +10,7 @@ No feature is enabled by default. | `interpret` | `read` plus an app-owned Device interpreter, fonts and CMaps | | `raster` | `interpret` plus premultiplied RGBA8 rendering | | `write` | Guarded Krilla authoring; no shared reader dependency | +| `write-svg` | `write` plus bounded SVG-to-PDF vector drawing | | `write-pdf` | `write` plus Krilla's embedded-PDF support | | `write-simple-text` | `write` plus Krilla's optional text shaper and `draw_text` | | `filters` | The `/Filter` chain for editing and writing PDF files: decode and encode, with limits and accounting. No reader or writer dependency | @@ -201,9 +202,12 @@ PDF files. The reader decrypts on its own and does not use it. It covers revisio block is ignored and bad padding is left in. - `permissions()` gives the `/P` flags; for R5/R6 a permission counts only when `/Perms` grants it too. Owners have every permission. -- `create(&NewEncryption, id0)` builds the `/Encrypt` values for RC4-40, RC4-128, AES-128 or - AES-256. The caller supplies 32 bytes of entropy (`seed`), so the module needs no OS access - and builds for the web. `file_id` derives a file identifier from the same seed. +- `create(&NewEncryption, id0)` builds the `/Encrypt` values for AES-128 or AES-256. It refuses + the legacy RC4-40 and RC4-128 schemes, because RC4 is broken (RFC 7465); `create_legacy` + writes those, for a file that must stay readable by an old reader. `Document::set_encryption` + refuses them too, with `set_encryption_legacy` as the explicit way in. The caller supplies 32 + bytes of entropy (`seed`), so the module needs no OS access and builds for the web. `file_id` + derives a file identifier from the same seed. - `EncryptDict` holds the dictionary's values. The caller reads them from, and writes them to, its own object model; the module does not parse PDF syntax. Keys and prepared passwords are zeroized when dropped. @@ -240,6 +244,9 @@ serialization uses the same backend version as before extraction. It provides: refuses it. Apps build URI links with it instead of `backend::action::LinkAction`, so a link target from someone else's document becomes a PDF link only when it is an `http`/`https` URL with a host or a `mailto` address. A refused target writes no link annotation. +- `write::svg` (feature `write-svg`): bounded SVG/SVGZ text preflight, data-only image + resolution, and vector drawing through krilla-svg. Callers provide font and fallback options; + the adapter enforces input, nesting, embedded-image, destination-area and filter budgets. - `safe_url` (crate root, any feature): the same rule, for apps that open links themselves, such as a slide show. diff --git a/crates/pdf/examples/cos_protect.rs b/crates/pdf/examples/cos_protect.rs index c40bccdce..b12c700cf 100644 --- a/crates/pdf/examples/cos_protect.rs +++ b/crates/pdf/examples/cos_protect.rs @@ -22,7 +22,8 @@ fn main() { _ => craft_pdf::cos::Algorithm::Aes256, }; let mut doc = craft_pdf::cos::Document::open(std::sync::Arc::new(std::fs::read(input).unwrap())).unwrap(); - doc.set_encryption(&craft_pdf::cos::NewEncryption { + // `rc4-40` and `rc4-128` are the legacy schemes, which `set_encryption` refuses. + doc.set_encryption_legacy(&craft_pdf::cos::NewEncryption { algorithm, user_password: user, owner_password: owner, diff --git a/crates/pdf/src/cos/document/open.rs b/crates/pdf/src/cos/document/open.rs index 46a6423a9..4991412ce 100644 --- a/crates/pdf/src/cos/document/open.rs +++ b/crates/pdf/src/cos/document/open.rs @@ -414,7 +414,20 @@ impl Document { /// Protect the document with a password (§7.6.4). Takes effect on the next save, which is /// always a full rewrite. Returns the handler (authenticated as owner). + /// + /// The legacy RC4 schemes are refused (RC4 is broken, `RFC 7465`): [`Self::set_encryption_legacy`] + /// writes them for a file an old reader must open. pub fn set_encryption(&mut self, params: &crate::crypt::NewEncryption) -> Result<(), CosError> { + self.set_encryption_with(params, false) + } + + /// [`Self::set_encryption`] with the legacy RC4-40 and RC4-128 schemes allowed. Pass it only + /// for a file that must stay readable by a reader without AES. + pub fn set_encryption_legacy(&mut self, params: &crate::crypt::NewEncryption) -> Result<(), CosError> { + self.set_encryption_with(params, true) + } + + fn set_encryption_with(&mut self, params: &crate::crypt::NewEncryption, legacy: bool) -> Result<(), CosError> { // The file identifier is part of the key; make sure it exists and keep it. let id = self.trailer.get(b"ID").map(|id| self.resolve(id)); let id0 = match id.as_deref() { @@ -426,7 +439,8 @@ impl Document { id } }; - let h = crate::crypt::create(params, &id0).map_err(|e| CosError::Security(e.to_string()))?; + let built = if legacy { crate::crypt::create_legacy(params, &id0) } else { crate::crypt::create(params, &id0) }; + let h = built.map_err(|e| CosError::Security(e.to_string()))?; let d = h.dict(); let s = |b: &[u8]| Object::String(crate::cos::PdfString { bytes: b.to_vec(), hex: true }); let mut e = Dict::new(); diff --git a/crates/pdf/src/crypt.rs b/crates/pdf/src/crypt.rs index 069627db9..c516fa86e 100644 --- a/crates/pdf/src/crypt.rs +++ b/crates/pdf/src/crypt.rs @@ -283,7 +283,7 @@ impl SecurityHandler { /// different key is refused too. pub fn authenticate_owner(&self, id0: &[u8], password: &str) -> Result<Self, CryptError> { let owner = Self::open(self.dict.clone(), id0, Some(password))?; - if owner.auth != Auth::Owner || owner.key != self.key { + if owner.auth != Auth::Owner || !same(owner.key.as_slice(), self.key.as_slice()) { return Err(CryptError::WrongPassword); } Ok(owner) @@ -539,6 +539,12 @@ fn u_value_r4(d: &EncryptDict, id0: &[u8], key: &[u8]) -> Vec<u8> { x } +/// Whether `a` and `b` are equal, in time that depends only on their lengths: password-derived +/// digests, keys and verifiers are compared without stopping at the first differing byte. +fn same(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + /// Algorithm 6: authenticate a user password; returns the file key. /// /// Some producers ignore `/EncryptMetadata false` when deriving the key (they omit the @@ -549,7 +555,7 @@ fn user_key_r4(d: &EncryptDict, id0: &[u8], pw: &[u8]) -> Option<Zeroizing<Vec<u let key = file_key_r4(d, id0, pw); let u = u_value_r4(d, id0, &key); let n = if d.r == 2 { 32 } else { 16 }; - (d.u.len() >= n && u[..n] == d.u[..n]).then_some(key) + (d.u.len() >= n && same(&u[..n], &d.u[..n])).then_some(key) }; check(d).or_else(|| (d.r >= 4 && !d.encrypt_metadata).then(|| check(&EncryptDict { encrypt_metadata: true, ..d.clone() })).flatten()) } @@ -636,7 +642,8 @@ fn key_r6(d: &EncryptDict, pw: &[u8], owner: bool) -> Result<Option<Zeroizing<Ve return Err(CryptError::Malformed("/O and /U must be 48 bytes for R5/R6".into())); } let (hashed, encrypted, udata) = if owner { (&d.o[..48], &d.oe, &d.u[..48]) } else { (&d.u[..48], &d.ue, &[][..]) }; - if *hash_r6(d.r, pw, &hashed[32..40], udata) != hashed[..32] { + let verifier = hash_r6(d.r, pw, &hashed[32..40], udata); + if !same(verifier.as_slice(), &hashed[..32]) { return Ok(None); } if encrypted.len() < 32 { @@ -651,9 +658,9 @@ fn key_r6(d: &EncryptDict, pw: &[u8], owner: bool) -> Result<Option<Zeroizing<Ve /// Which encryption to create. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Algorithm { - /// R2, 40-bit RC4 (legacy; for tests and compatibility only). + /// R2, 40-bit RC4 (legacy: [`create`] refuses it, [`create_legacy`] writes it). Rc4_40, - /// R3, 128-bit RC4. + /// R3, 128-bit RC4 (legacy: [`create`] refuses it, [`create_legacy`] writes it). Rc4_128, /// R4, AES-128 crypt filters. Aes128, @@ -661,6 +668,14 @@ pub enum Algorithm { Aes256, } +impl Algorithm { + /// Whether this is one of the broken legacy ciphers: read for compatibility, and refused for + /// new encryption by [`create`]. + pub fn is_legacy(self) -> bool { + matches!(self, Algorithm::Rc4_40 | Algorithm::Rc4_128) + } +} + /// A password as [`create`] prepares it: for R2–R4 its PDFDocEncoding (characters it lacks /// dropped), at most 32 bytes; for R6 its SASLprep (RFC 4013: soft hyphens and the like removed, /// other spaces made plain, then NFKC; the password as given if SASLprep refuses it), in UTF-8, @@ -725,7 +740,23 @@ pub fn file_id(seed: &[u8; 32]) -> Vec<u8> { } /// Build the `/Encrypt` values and an authenticated (owner) handler for a new encryption. +/// +/// The legacy RC4 schemes are refused, because RC4 is broken (`RFC 7465`) and a file written with +/// it protects nothing: [`create_legacy`] is the explicit way to write them. pub fn create(params: &NewEncryption, id0: &[u8]) -> Result<SecurityHandler, CryptError> { + if params.algorithm.is_legacy() { + return Err(CryptError::Unsupported("RC4 encryption is legacy (RFC 7465); use create_legacy for a file an old reader must open".into())); + } + create_any(params, id0) +} + +/// [`create`] without the RC4 gate: writes RC4-40 and RC4-128 too. For a file that must stay +/// readable by a reader without AES, and for tests that read and write every algorithm. +pub fn create_legacy(params: &NewEncryption, id0: &[u8]) -> Result<SecurityHandler, CryptError> { + create_any(params, id0) +} + +fn create_any(params: &NewEncryption, id0: &[u8]) -> Result<SecurityHandler, CryptError> { // R2 reserves bits 7-32; later revisions reserve bits 7-8 and 13-32. // Reserved bits must be 1, and bits 1-2 must be 0 (§7.6.4.2). let reserved = if params.algorithm == Algorithm::Rc4_40 { !0x3F } else { !0xFFF | 0xC0 }; diff --git a/crates/pdf/src/crypt/tests.rs b/crates/pdf/src/crypt/tests.rs index 04bb7c61e..08878c8be 100644 --- a/crates/pdf/src/crypt/tests.rs +++ b/crates/pdf/src/crypt/tests.rs @@ -52,13 +52,45 @@ fn aes_padding_is_added_and_tolerantly_removed() { const ID: &[u8] = b"0123456789abcdef"; fn new(alg: Algorithm, user: &str, owner: &str, perms: i32) -> SecurityHandler { - create( + // These tests read and write every algorithm, RC4 included. + create_legacy( &NewEncryption { algorithm: alg, user_password: user, owner_password: owner, permissions: perms, encrypt_metadata: true, seed: [42; 32] }, ID, ) .unwrap() } +/// New files are not written with RC4: `create` refuses it, and the explicitly named +/// `create_legacy` is the only way to write it. +#[test] +fn create_refuses_rc4_unless_asked() { + let params = |algorithm| NewEncryption { + algorithm, + user_password: "user", + owner_password: "owner", + permissions: -1, + encrypt_metadata: true, + seed: [42; 32], + }; + for (alg, revision) in [(Algorithm::Rc4_40, 2), (Algorithm::Rc4_128, 3)] { + assert!(matches!(create(&params(alg), ID), Err(CryptError::Unsupported(_))), "{alg:?}"); + assert_eq!(create_legacy(&params(alg), ID).unwrap().dict().r, revision, "{alg:?}"); + } + for alg in [Algorithm::Aes128, Algorithm::Aes256] { + assert!(create(&params(alg), ID).is_ok(), "AES is not legacy: {alg:?}"); + } +} + +/// Every verifier check goes through this comparison: it reads both sides in full and a value +/// that merely starts the same never matches. +#[test] +fn verifier_comparison_reads_every_byte() { + assert!(super::same(b"", b"")); + assert!(super::same(b"0123456789abcdef", b"0123456789abcdef")); + assert!(!super::same(b"0123456789abcdef", b"0123456789abcdee"), "difference in the last byte"); + assert!(!super::same(b"0123456789abcdef", b"0123456789abcde"), "shorter value"); +} + const ALL: [Algorithm; 4] = [Algorithm::Rc4_40, Algorithm::Rc4_128, Algorithm::Aes128, Algorithm::Aes256]; #[test] diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index ed9f21a79..cae3117d9 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -27,3 +27,6 @@ pub mod paths; pub mod raster; #[cfg(feature = "write")] pub mod write; +#[cfg(feature = "write-raster")] +#[path = "write/raster.rs"] +pub mod write_raster; diff --git a/crates/pdf/src/paths.rs b/crates/pdf/src/paths.rs index bbb93942e..0ed5dce8b 100644 --- a/crates/pdf/src/paths.rs +++ b/crates/pdf/src/paths.rs @@ -145,6 +145,7 @@ fn import_selected(bytes: &[u8], limits: Limits, selected: Option<usize>) -> Res #[derive(Default)] struct Collector { paths: Vec<BezPath>, + last_fill_path: Option<BezPath>, omitted_text: usize, omitted_images: usize, clips_seen: usize, @@ -157,26 +158,37 @@ struct Collector { impl Device<'_> for Collector { fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {} fn set_blend_mode(&mut self, _: BlendMode) {} - fn draw_path(&mut self, path: &BezPath, transform: Affine, _: &Paint<'_>, _: &PathDrawMode) { + fn draw_path(&mut self, path: &BezPath, transform: Affine, _: &Paint<'_>, mode: &PathDrawMode) { if path.is_empty() { return; } + let path = transform * path.clone(); + match mode { + PathDrawMode::Fill(_) => self.last_fill_path = Some(path.clone()), + PathDrawMode::Stroke(_) => { + if self.last_fill_path.take().as_ref() == Some(&path) { + return; + } + } + } let count = path.elements().len(); if self.paths.len() >= self.max_paths || self.elements.saturating_add(count) > self.max_elements { self.exceeded = true; return; } self.elements = self.elements.saturating_add(count); - self.paths.push(transform * path.clone()); + self.paths.push(path); } fn push_clip_path(&mut self, _: &ClipPath) { self.clips_seen = self.clips_seen.saturating_add(1); } fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {} fn draw_glyph(&mut self, _: &Glyph<'_>, _: Affine, _: Affine, _: &Paint<'_>, _: &GlyphDrawMode) { + self.last_fill_path = None; self.omitted_text = self.omitted_text.saturating_add(1); } fn draw_image(&mut self, _: Image<'_, '_>, _: Affine) { + self.last_fill_path = None; self.omitted_images = self.omitted_images.saturating_add(1); } fn pop_clip_path(&mut self) {} diff --git a/crates/pdf/src/write.rs b/crates/pdf/src/write.rs index 8114327d4..924910e25 100644 --- a/crates/pdf/src/write.rs +++ b/crates/pdf/src/write.rs @@ -15,6 +15,8 @@ const _: bool = backend::CRAFT_PRINT_COLOR; const _: bool = backend::CRAFT_OPTIONAL_CONTENT; pub mod print; +#[cfg(feature = "write-svg")] +pub mod svg; use backend::configure::{Archival, Configuration, ConfigurationBuilder, ConfigurationError, PdfVersion}; use backend::text::{Font, Tag}; diff --git a/crates/pdf/src/write/raster.rs b/crates/pdf/src/write/raster.rs new file mode 100644 index 000000000..1aa64ec3c --- /dev/null +++ b/crates/pdf/src/write/raster.rs @@ -0,0 +1,676 @@ +//! Low-level raster and spot-plate PDF serialization. +//! +//! Callers map their page and color models to these neutral records. This module owns PDF object +//! layout, image streams, ICC/Separation resources, page labels, marks, xref and trailer syntax. + +use std::collections::BTreeSet; +use std::fmt::Write as _; +use std::io::Write as _; + +/// An 8-bit interleaved image placed on one page: gray, RGB or CMYK. +#[derive(Clone, Debug, Default)] +pub struct Image { + pub width: u32, + pub height: u32, + pub channels: usize, + pub data: Vec<u8>, + pub icc: Option<Vec<u8>>, +} + +/// One spot plate with 8-bit ink density and an alternate CMYK preview color. +#[derive(Clone, Debug, Default)] +pub struct SpotPlate { + pub name: String, + pub cmyk: [f32; 4], + /// CIE L*a*b* ink color for a caller's metadata packet. + pub lab: [f32; 3], + /// Encoded sRGB ink color for a caller's metadata packet. + pub srgb: [f32; 3], + /// Spot ink solidity in the inclusive range 0..=1. + pub solidity: f32, + pub width: u32, + pub height: u32, + pub data: Vec<u8>, +} + +/// Crop and registration marks around a page's image rectangle. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Marks { + pub corner_crop: bool, + pub center_crop: bool, + pub registration: bool, +} + +/// A neutral PDF page and its raster/spot resources. +#[derive(Clone, Debug, Default)] +pub struct Page { + pub paper: (f64, f64), + pub image: Option<Image>, + pub rect: (f64, f64, f64, f64), + pub marks: Marks, + pub description: Option<String>, + pub label: Option<String>, + pub page_label: Option<String>, + pub plates: Vec<SpotPlate>, +} + +/// A device color used by neutral vector content. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum DeviceColor { + Gray(f64), + Rgb([f64; 3]), + Cmyk([f64; 4]), +} + +/// The fill rule for a neutral vector path. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ContentFillRule { + NonZero, + EvenOdd, +} + +/// Path geometry independent of a drawing application's model. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PathElement { + MoveTo([f64; 2]), + LineTo([f64; 2]), + CubicTo([f64; 2], [f64; 2], [f64; 2]), + Close, +} + +/// A centered, device-space stroke on a vector path. +#[derive(Clone, Debug, PartialEq)] +pub struct ContentStroke { + pub color: DeviceColor, + pub width: f64, + pub cap: u8, + pub join: u8, + pub miter_limit: f64, + pub dashes: Vec<f64>, + pub dash_offset: f64, +} + +/// One path whose fill and stroke are emitted by the shared PDF writer. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ContentPath { + pub elements: Vec<PathElement>, + pub fill: Option<(DeviceColor, ContentFillRule)>, + pub stroke: Option<ContentStroke>, +} + +/// Typed vector/text content. Callers provide model geometry and text spans; this crate alone +/// turns the commands into PDF content-stream syntax. +#[derive(Clone, Debug, PartialEq)] +pub enum ContentOp { + Save, + Restore, + Concat([f64; 6]), + Path(ContentPath), + BeginSelectionLine, + SelectionText { actual_text: String, encoded: String, matrix: [f64; 6] }, + EndSelectionLine, +} + +/// Vector and selectable-text commands layered over a raster page. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct VectorContent { + pub operations: Vec<ContentOp>, +} + +/// Serialize typed vector content to a PDF content stream. `None` means a number or operator +/// parameter was invalid; malformed commands are never written into the document. +pub fn encode_vector_content(content: &VectorContent) -> Option<String> { + let mut out = String::new(); + for operation in &content.operations { + match operation { + ContentOp::Save => out.push_str("q\n"), + ContentOp::Restore => out.push_str("Q\n"), + ContentOp::Concat(matrix) => { + finite(matrix)?; + writeln!(out, "{} {} {} {} {} {} cm", matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]).ok()?; + } + ContentOp::Path(path) => write_content_path(&mut out, path)?, + ContentOp::BeginSelectionLine => out.push_str("BT\n3 Tr\n/FSelect 1 Tf\n"), + ContentOp::SelectionText { actual_text, encoded, matrix } => { + finite(matrix)?; + writeln!(out, "/Span << /ActualText <{}> >> BDC", actual_text_hex(actual_text)).ok()?; + writeln!(out, "{} {} {} {} {} {} Tm", matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]).ok()?; + writeln!(out, "<{encoded}> Tj\nEMC").ok()?; + } + ContentOp::EndSelectionLine => out.push_str("ET\n"), + } + } + Some(out) +} + +/// Serialize pages with typed vector content. Invalid vector commands return `None`. +pub fn write_pages_with_vector_content( + pages: &[Page], + vectors: &[VectorContent], + selection_font: &SelectionFont, + xmp: Option<&str>, +) -> Option<Vec<u8>> { + let encoded: Option<Vec<String>> = vectors.iter().map(encode_vector_content).collect(); + encoded.map(|content| write_pages(pages, &content, selection_font, xmp)) +} + +fn finite(values: &[f64]) -> Option<()> { + values.iter().all(|value| value.is_finite()).then_some(()) +} + +fn write_content_path(out: &mut String, path: &ContentPath) -> Option<()> { + if let Some((color, _)) = path.fill { + write_device_color(out, color, false)?; + } + if let Some(stroke) = &path.stroke { + write_device_color(out, stroke.color, true)?; + finite(&[stroke.width, stroke.miter_limit, stroke.dash_offset])?; + finite(&stroke.dashes)?; + writeln!(out, "{} w {} J {} j {} M", stroke.width, stroke.cap, stroke.join, stroke.miter_limit).ok()?; + out.push('['); + for dash in &stroke.dashes { + write!(out, "{dash} ").ok()?; + } + writeln!(out, "] {} d", stroke.dash_offset).ok()?; + } + for element in &path.elements { + match element { + PathElement::MoveTo(point) => { + finite(point)?; + writeln!(out, "{} {} m", point[0], point[1]).ok()?; + } + PathElement::LineTo(point) => { + finite(point)?; + writeln!(out, "{} {} l", point[0], point[1]).ok()?; + } + PathElement::CubicTo(a, b, c) => { + finite(a)?; + finite(b)?; + finite(c)?; + writeln!(out, "{} {} {} {} {} {} c", a[0], a[1], b[0], b[1], c[0], c[1]).ok()?; + } + PathElement::Close => out.push_str("h\n"), + } + } + match (path.fill, path.stroke.is_some()) { + (Some((_, ContentFillRule::NonZero)), false) => out.push_str("f\n"), + (Some((_, ContentFillRule::EvenOdd)), false) => out.push_str("f*\n"), + (None, true) => out.push_str("S\n"), + (Some((_, ContentFillRule::NonZero)), true) => out.push_str("B\n"), + (Some((_, ContentFillRule::EvenOdd)), true) => out.push_str("B*\n"), + (None, false) => return None, + } + Some(()) +} + +fn write_device_color(out: &mut String, color: DeviceColor, stroke: bool) -> Option<()> { + match color { + DeviceColor::Gray(value) => { + finite(&[value])?; + writeln!(out, "{value} {}", if stroke { "G" } else { "g" }).ok()?; + } + DeviceColor::Rgb(values) => { + finite(&values)?; + for value in values { + write!(out, "{value} ").ok()?; + } + writeln!(out, "{}", if stroke { "RG" } else { "rg" }).ok()?; + } + DeviceColor::Cmyk(values) => { + finite(&values)?; + for value in values { + write!(out, "{value} ").ok()?; + } + writeln!(out, "{}", if stroke { "K" } else { "k" }).ok()?; + } + } + Some(()) +} + +fn actual_text_hex(text: &str) -> String { + let mut hex = String::from("FEFF"); + for code in text.encode_utf16() { + let _ = write!(hex, "{code:04X}"); + } + hex +} + +/// The RDF namespace used by PDF XMP packets. +pub const RDF_NAMESPACE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + +/// PhotoCraft spot-plate metadata namespace. The packet encoder is shared so applications pass +/// neutral plate facts instead of assembling XML inside a PDF export path. +pub const SPOT_PLATES_NAMESPACE: &str = "http://ns.getartcraft.com/photocraft/spot-plates/1.0/"; + +/// Add spot-plate metadata to a PDF XMP packet. An unparseable caller packet is preserved as-is; +/// with no caller packet a complete XMP packet is created. An empty plate list returns the +/// caller packet unchanged, or `None` when there is no metadata to write. +pub fn xmp_with_spot_plates(doc_xmp: Option<&str>, plates: &[SpotPlate]) -> Option<String> { + if plates.is_empty() { + return doc_xmp.map(str::to_owned); + } + let mut description = format!( + " <rdf:Description rdf:about=\"\" xmlns:rdf=\"{RDF_NAMESPACE}\" xmlns:pcsp=\"{SPOT_PLATES_NAMESPACE}\">\n <pcsp:plates>\n <rdf:Seq>\n" + ); + let two = |value: f32| { + let value = (value * 100.0).round() / 100.0; + if value == 0.0 { 0.0 } else { value } + }; + for (index, plate) in plates.iter().enumerate() { + let hex = plate.srgb.map(|value| format!("{:02X}", (value.clamp(0.0, 1.0) * 255.0).round() as u8)).concat(); + description.push_str(&format!( + " <rdf:li rdf:parseType=\"Resource\">\n <pcsp:index>{index}</pcsp:index>\n <pcsp:name>{}</pcsp:name>\n <pcsp:labL>{:.2}</pcsp:labL>\n <pcsp:labA>{:.2}</pcsp:labA>\n <pcsp:labB>{:.2}</pcsp:labB>\n <pcsp:srgb>#{hex}</pcsp:srgb>\n <pcsp:solidity>{}</pcsp:solidity>\n </rdf:li>\n", + xml_text(&plate.name), two(plate.lab[0]), two(plate.lab[1]), two(plate.lab[2]), (plate.solidity * 100.0).round() as u32 + )); + } + description.push_str(" </rdf:Seq>\n </pcsp:plates>\n </rdf:Description>\n"); + if let Some(xmp) = doc_xmp { + let Some((at, self_closing)) = rdf_insertion(xmp) else { return Some(xmp.to_owned()) }; + let tail_at = if self_closing.is_some() { at + 2 } else { at }; + let (Some(head), Some(tail)) = (xmp.get(..at), xmp.get(tail_at..)) else { return Some(xmp.to_owned()) }; + let mut out = String::with_capacity(xmp.len() + description.len() + 16); + out.push_str(head); + match self_closing { + Some(name) => { + out.push('>'); + out.push('\n'); + out.push_str(&description); + out.push_str(" </"); + out.push_str(name); + out.push('>'); + } + None => out.push_str(&description), + } + out.push_str(tail); + return Some(out); + } + Some(format!( + "<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"{RDF_NAMESPACE}\">\n{description} </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>" + )) +} + +fn xml_text(value: &str) -> String { + let mut escaped = String::with_capacity(value.len()); + for ch in value.chars() { + match ch { + '&' => escaped.push_str("&amp;"), + '<' => escaped.push_str("&lt;"), + '>' => escaped.push_str("&gt;"), + '"' => escaped.push_str("&quot;"), + ch => escaped.push(ch), + } + } + escaped +} + +fn rdf_insertion(xmp: &str) -> Option<(usize, Option<&str>)> { + let bom = xmp.strip_prefix('\u{feff}').map_or(0, |_| '\u{feff}'.len_utf8()); + let body = xmp.get(bom..)?; + let doc = roxmltree::Document::parse(body).ok()?; + let rdf = + doc.descendants().find(|node| node.is_element() && node.tag_name().namespace() == Some(RDF_NAMESPACE) && node.tag_name().name() == "RDF")?; + let range = rdf.range(); + let text = body.get(range.clone())?; + if let Some(open) = text.strip_suffix("/>") { + let name = open.get(1..)?; + let end = name.find(|ch: char| ch.is_whitespace() || ch == '/').unwrap_or(name.len()); + return Some((bom + range.end - 2, Some(name.get(..end)?))); + } + Some((bom + range.start + text.rfind("</")?, None)) +} + +/// A one-byte Unicode map for invisible, selectable text layered over vector outlines. +#[derive(Default)] +pub struct SelectionFont { + chars: BTreeSet<char>, +} + +impl SelectionFont { + /// Collect distinct characters until the one-byte code space is exceeded. + pub fn new<'a>(texts: impl Iterator<Item = &'a str>) -> Self { + let mut chars = BTreeSet::new(); + 'texts: for text in texts { + for ch in text.chars() { + chars.insert(ch); + if chars.len() > 255 { + break 'texts; + } + } + } + Self { chars } + } + /// Encode text as hex character codes in this font's Unicode map. + pub fn encode(&self, text: &str) -> Option<String> { + if self.chars.len() > 255 { + return None; + } + let mut encoded = String::new(); + for ch in text.chars() { + let code = self.chars.iter().position(|c| *c == ch)?.checked_add(1)?; + write!(encoded, "{code:02X}").ok()?; + } + Some(encoded) + } + fn objects(&self, base: usize) -> Vec<Vec<u8>> { + let count = self.chars.len().min(255); + let mut differences = String::new(); + let mut procs = String::new(); + let mut cmap = String::from( + "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /PhotoCraftUnicode def\n/CMapType 2 def\n1 begincodespacerange\n<00> <FF>\nendcodespacerange\n", + ); + let chars: Vec<_> = self.chars.iter().take(count).collect(); + for (block, chunk) in chars.chunks(100).enumerate() { + let _ = writeln!(cmap, "{} beginbfchar", chunk.len()); + for (i, ch) in chunk.iter().enumerate() { + let code = block * 100 + i + 1; + let mut buf = [0; 2]; + let unicode = ch.encode_utf16(&mut buf).iter().map(|u| format!("{u:04X}")).collect::<String>(); + let _ = writeln!(cmap, "<{code:02X}> <{unicode}>"); + } + cmap.push_str("endbfchar\n"); + } + cmap.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n"); + for code in 1..=count { + let _ = write!(differences, " /c{code}"); + let _ = write!(procs, " /c{code} {} 0 R", base + 1); + } + let widths = "1000 ".repeat(count.max(1)); + let font = format!( + "<< /Type /Font /Subtype /Type3 /Name /FSelect /FontBBox [0 -250 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs <<{procs} >> /Encoding << /Type /Encoding /Differences [1{differences}] >> /FirstChar 1 /LastChar {} /Widths [{widths}] /Resources << >> /ToUnicode {} 0 R >>", + count.max(1), + base + 2 + ); + let stream = |data: &str| format!("<< /Length {} >>\nstream\n{data}endstream", data.len()).into_bytes(); + vec![font.into_bytes(), stream("1000 0 0 -250 1000 1000 d1\n"), stream(&cmap)] + } +} + +fn pdf_string(s: &str) -> String { + let mut o = String::from("("); + for c in s.chars() { + match c { + '(' | ')' | '\\' => { + o.push('\\'); + o.push(c); + } + c if c.is_ascii() && !c.is_ascii_control() => o.push(c), + _ => o.push('?'), + } + } + o.push(')'); + o +} + +/// A PDF text string with UTF-16BE hex (the Unicode-capable form, byte-order mark included). +fn pdf_unicode_string(s: &str) -> String { + let mut o = String::from("<FEFF"); + for u in s.encode_utf16() { + o.push_str(&format!("{u:04X}")); + } + o.push('>'); + o +} + +/// `s` as a PDF name object (ISO 32000-1 §7.3.5): `/` then the UTF-8 bytes, every byte outside +/// the regular printable ASCII range, `#` and the delimiters as `#xx`. An empty name would be +/// the bare `/`, which some readers reject, so it becomes `/Spot`. +fn pdf_name(s: &str) -> String { + let mut o = String::from("/"); + for b in s.bytes() { + let regular = (0x21..=0x7e).contains(&b) && !matches!(b, b'#' | b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%'); + if regular { + o.push(char::from(b)); + } else { + o.push_str(&format!("#{b:02X}")); + } + } + if o.len() == 1 { + o.push_str("Spot"); + } + o +} + +fn deflate(data: &[u8]) -> Vec<u8> { + // Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static + // Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger + // than miniz's level 1 was, at about twice its time. + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(3)); + let _ = e.write_all(data); + e.finish().unwrap_or_default() +} + +/// Vector marks around `(x, y, w, h)`. +fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String { + let mut s = String::from("q 0 G 0.3 w\n"); + let (gap, len) = (6.0, 18.0); + let line = |s: &mut String, x0: f64, y0: f64, x1: f64, y1: f64| s.push_str(&format!("{x0:.2} {y0:.2} m {x1:.2} {y1:.2} l S\n")); + if m.corner_crop { + for (cx, cy, dx, dy) in [(x, y, -1.0, -1.0), (x + w, y, 1.0, -1.0), (x, y + h, -1.0, 1.0), (x + w, y + h, 1.0, 1.0)] { + line(&mut s, cx + dx * gap, cy, cx + dx * (gap + len), cy); + line(&mut s, cx, cy + dy * gap, cx, cy + dy * (gap + len)); + } + } + if m.center_crop { + let (mx, my) = (x + w / 2.0, y + h / 2.0); + line(&mut s, mx, y - gap, mx, y - gap - len); + line(&mut s, mx, y + h + gap, mx, y + h + gap + len); + line(&mut s, x - gap, my, x - gap - len, my); + line(&mut s, x + w + gap, my, x + w + gap + len, my); + } + if m.registration { + let r = 5.0; + let off = gap + len / 2.0; + for (cx, cy) in [(x + w / 2.0, y - off), (x + w / 2.0, y + h + off), (x - off, y + h / 2.0), (x + w + off, y + h / 2.0)] { + // Circle (four Béziers) plus crosshair. + let k = 0.5523 * r; + s.push_str(&format!( + "{:.2} {cy:.2} m {:.2} {:.2} {:.2} {:.2} {cx:.2} {:.2} c {:.2} {:.2} {:.2} {:.2} {:.2} {cy:.2} c {:.2} {:.2} {:.2} {:.2} {cx:.2} {:.2} c {:.2} {:.2} {:.2} {:.2} {:.2} {cy:.2} c S\n", + cx + r, cx + r, cy + k, cx + k, cy + r, cy + r, cx - k, cy + r, cx - r, cy + k, cx - r, cx - r, cy - k, cx - k, cy - r, cy - r, cx + k, cy - r, cx + r, cy - k, cx + r + )); + line(&mut s, cx - r * 1.6, cy, cx + r * 1.6, cy); + line(&mut s, cx, cy - r * 1.6, cx, cy + r * 1.6); + } + } + s.push_str("Q\n"); + s +} + +/// An image XObject dictionary and its Flate-compressed samples, as one object body. +fn image_object(width: u32, height: u32, colour_space: &str, data: &[u8]) -> Vec<u8> { + let z = deflate(data); + let mut body = format!( + "<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /ColorSpace {colour_space} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", + z.len() + ) + .into_bytes(); + body.extend_from_slice(&z); + body.extend_from_slice(b"\nendstream"); + body +} + +/// A PDF with one page per entry; `vectors[i]` (when present) is drawn over page `i`, after its +/// image and before its plates and marks (the top layers kept as paths and selectable text), and +/// the selection font their text refers to is `/FSelect`. `xmp` is the packet of the catalog's +/// `/Metadata` stream, if any. +/// +/// Objects: 1 catalog, 2 pages, then per page its page, contents, image and one XObject per +/// plate; then the shared font, ICC profile, overprint ExtGState and XMP metadata stream, each +/// only when present, the selection font's three objects, and last the page-label tree. +pub fn write_pages(pages: &[Page], vectors: &[String], selection_font: &SelectionFont, xmp: Option<&str>) -> Vec<u8> { + if pages.is_empty() { + return Vec::new(); + } + let mut out: Vec<u8> = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(); + let mut offsets: Vec<usize> = Vec::new(); + let mut obj = |out: &mut Vec<u8>, body: &[u8]| { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", offsets.len()).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + }; + let n = pages.len(); + // A label tree is written only for a non-empty name: an all-empty tree would be `/Nums []`, + // and filtering the first empty name away would start the tree at page index 1, not 0. + let labels_on = pages.iter().any(|p| p.page_label.as_deref().is_some_and(|label| !label.is_empty())); + // Object numbers, handed out in the order the objects are written. + let mut next = 3usize; + let mut take = |present: bool| { + let o = present.then_some(next); + next += usize::from(present); + o + }; + struct PageObjects { + page: usize, + contents: usize, + image: Option<usize>, + plates: Vec<usize>, + } + // Field initialisers run in this order. + let page_objects: Vec<PageObjects> = pages + .iter() + .map(|p| PageObjects { + page: take(true).unwrap_or_default(), + contents: take(true).unwrap_or_default(), + image: take(p.image.is_some()), + plates: p.plates.iter().filter_map(|_| take(true)).collect(), + }) + .collect(); + let font_obj = take(true).unwrap_or_default(); + // The profile is the document's, shared by every page's image. + let icc = pages.iter().find_map(|p| p.image.as_ref().and_then(|i| i.icc.as_ref().map(|icc| (icc, i.channels)))); + let icc_obj = take(icc.is_some()); + let gs_obj = take(pages.iter().any(|p| !p.plates.is_empty())); + let xmp_obj = take(xmp.is_some()); + let selection_base = next; + let selection_objects = selection_font.objects(selection_base); + let labels_obj = labels_on.then_some(selection_base + selection_objects.len()); + + let metadata = xmp_obj.map(|o| format!(" /Metadata {o} 0 R")).unwrap_or_default(); + let page_labels = labels_obj.map(|o| format!(" /PageLabels {o} 0 R")).unwrap_or_default(); + obj(&mut out, format!("<< /Type /Catalog /Pages 2 0 R{metadata}{page_labels} >>").as_bytes()); + let kids = page_objects.iter().map(|p| format!("{} 0 R", p.page)).collect::<Vec<_>>().join(" "); + obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes()); + for (i, (page, objects)) in pages.iter().zip(&page_objects).enumerate() { + let (pw, ph) = page.paper; + let (x, y, w, h) = page.rect; + let mut xobjects = String::new(); + if let Some(o) = objects.image { + xobjects.push_str(&format!("/Im0 {o} 0 R ")); + } + for (k, o) in objects.plates.iter().enumerate() { + xobjects.push_str(&format!("/Sp{k} {o} 0 R ")); + } + let ext_gstate = match gs_obj { + Some(o) if !page.plates.is_empty() => format!("/ExtGState << /GS0 {o} 0 R >> "), + _ => String::new(), + }; + obj( + &mut out, + format!( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << {xobjects}>> {ext_gstate}/Font << /F1 {font_obj} 0 R /FSelect {selection_base} 0 R >> >> /Contents {} 0 R >>", + objects.contents + ) + .as_bytes(), + ); + // An explicit white page, so every viewer (and rasteriser) shows paper, not transparency. + let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\n"); + if objects.image.is_some() { + content.push_str(&format!("q {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n")); + } + if let Some(v) = vectors.get(i) { + content.push_str(v); + } + // Each plate overprints what is already on the page: with `/OP true` a Separation paints + // its own colorant only, leaving the others (and the composite) as they are. + for k in 0..page.plates.len() { + content.push_str(&format!("q /GS0 gs {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Sp{k} Do Q\n")); + } + content.push_str(&marks_ops(page.marks, page.rect)); + let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration; + let pad = if any_marks { 30.0 } else { 6.0 }; + if let Some(l) = page.label.as_deref().filter(|l| !l.is_empty()) { + content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y + h + pad, pdf_string(l))); + } + if let Some(d) = page.description.as_deref().filter(|d| !d.is_empty()) { + content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y - pad - 8.0, pdf_string(d))); + } + let c = deflate(content.as_bytes()); + let mut body = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", c.len()).into_bytes(); + body.extend_from_slice(&c); + body.extend_from_slice(b"\nendstream"); + obj(&mut out, &body); + if let Some(img) = &page.image { + let device = match img.channels { + 1 => "/DeviceGray", + 4 => "/DeviceCMYK", + _ => "/DeviceRGB", + }; + let cs = match icc_obj { + Some(o) if img.icc.is_some() => format!("[/ICCBased {o} 0 R]"), + _ => device.to_string(), + }; + obj(&mut out, &image_object(img.width, img.height, &cs, &img.data)); + } + for p in &page.plates { + // A tint transform from the colorant's density to its alternate: 0 → paper, 1 → `cmyk` + // (an exponential interpolation function with N = 1 is linear). + let cmyk = p.cmyk.map(|v| format!("{:.4}", v.clamp(0.0, 1.0))).join(" "); + let cs = format!("[/Separation {} /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [{cmyk}] /N 1 >>]", pdf_name(&p.name)); + // No mask on the plate: where it has no ink it paints "0" of its own colorant, which a + // separating RIP reads as no ink and overprint keeps the other plates under. (A stencil + // or colour-key mask would let plain viewers show every plate, but Illustrator reports + // an explicit image mask as an unknown imaging construct, and Quartz draws nothing for a + // colour-key-masked Separation image.) + obj(&mut out, &image_object(p.width, p.height, &cs, &p.data)); + } + } + obj(&mut out, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"); + if let Some((icc, channels)) = icc { + let device = match channels { + 1 => "/DeviceGray", + 4 => "/DeviceCMYK", + _ => "/DeviceRGB", + }; + let z = deflate(icc); + let mut body = format!("<< /N {channels} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", z.len()).into_bytes(); + body.extend_from_slice(&z); + body.extend_from_slice(b"\nendstream"); + obj(&mut out, &body); + } + if gs_obj.is_some() { + obj(&mut out, b"<< /Type /ExtGState /OP true /op true /OPM 1 >>"); + } + if let Some(xmp) = xmp { + // Unfiltered, as the XMP specification asks of a packet in a PDF, so a reader can find it + // by scanning for the packet header. + let mut body = format!("<< /Type /Metadata /Subtype /XML /Length {} >>\nstream\n", xmp.len()).into_bytes(); + body.extend_from_slice(xmp.as_bytes()); + body.extend_from_slice(b"\nendstream"); + obj(&mut out, &body); + } + for body in &selection_objects { + obj(&mut out, body); + } + if labels_obj.is_some() { + // Every page gets an entry: a number-tree range runs until the next key, so omitting an + // empty name would make that page inherit the previous page's label. An empty + // dictionary gives the page the default (decimal) label instead. + let nums = pages + .iter() + .enumerate() + .map(|(i, p)| match p.page_label.as_deref().filter(|label| !label.is_empty()) { + Some(label) => format!("{i} << /P {} >>", pdf_unicode_string(label)), + None => format!("{i} << >>"), + }) + .collect::<Vec<_>>() + .join(" "); + obj(&mut out, format!("<< /Nums [{nums}] >>").as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); + for o in &offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes()); + out +} diff --git a/crates/pdf/src/write/svg.rs b/crates/pdf/src/write/svg.rs new file mode 100644 index 000000000..eb6542c0a --- /dev/null +++ b/crates/pdf/src/write/svg.rs @@ -0,0 +1,176 @@ +//! Bounded SVG parsing and vector drawing on a PDF surface. +//! +//! This adapter owns the usvg version required by krilla-svg. Callers pass their font and +//! fallback options, while this module checks input, embedded SVGs, and output/filter budgets +//! before converting SVG to PDF drawing operations. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use krilla_svg::SurfaceExt; + +pub use krilla_svg::SvgSettings; +pub use usvg; + +/// Resource limits for parsing SVG and drawing it to PDF. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// Maximum decoded bytes in one SVG document. + pub input_bytes: usize, + /// Maximum SVG element and reference depth. + pub depth: usize, + /// Maximum XML nodes in one document. + pub xml_nodes: u32, + /// Maximum total decoded bytes of embedded SVGs. + pub embedded_svg_bytes: usize, + /// Maximum number of embedded SVG documents nested within one another. + pub embedded_svg_depth: usize, + /// Maximum encoded bytes retained for embedded raster images. + pub embedded_image_bytes: usize, + /// Maximum PDF surface area, measured in 96 dpi pixels. + pub vector_pixels: u64, + /// Maximum raster pixels used by filters after `filter_scale` is applied. + pub filter_pixels: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { + input_bytes: 16 * 1024 * 1024, + depth: 64, + xml_nodes: 100_000, + embedded_svg_bytes: 32 * 1024 * 1024, + embedded_svg_depth: 4, + embedded_image_bytes: 32 * 1024 * 1024, + vector_pixels: 256_000_000, + filter_pixels: 256_000_000, + } + } +} + +/// Why an SVG could not be parsed or drawn within its limits. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The bounded SVG text/XML preflight refused the input. + #[error("SVG preflight failed: {0}")] + Preflight(String), + /// usvg could not construct the SVG tree. + #[error("SVG parsing failed: {0}")] + Parse(String), + /// The requested PDF area or filter raster exceeds its budget. + #[error("SVG drawing exceeds the PDF area or filter budget")] + DrawLimit, + /// krilla-svg refused to draw the parsed tree. + #[error("krilla-svg could not draw the parsed tree")] + Draw, +} + +/// An SVG tree parsed within [`Limits`], ready to draw as PDF vectors. +pub struct Document { + tree: usvg::Tree, + limits: Limits, +} + +impl Document { + /// Parse SVG/SVGZ bytes after bounded shared preflight. `options` controls the caller's font + /// database, family selection, and fallback policy; its file-reading and image resolvers are + /// replaced with a data-only resolver governed by `limits`. + pub fn parse<'a>(bytes: &[u8], limits: Limits, mut options: usvg::Options<'a>) -> Result<Self, Error> { + let text = bounded_text(bytes, limits.input_bytes, limits).map_err(|e| Error::Preflight(e.to_string()))?; + options.image_href_resolver = image_resolver(limits); + let tree = usvg::Tree::from_str(&text, &options).map_err(|e| Error::Parse(e.to_string()))?; + Ok(Self { tree, limits }) + } + + /// Draw the parsed tree as PDF vectors. The limits account for the destination size and the + /// renderer's filter scale before krilla-svg allocates filter rasters. + pub fn draw(&self, surface: &mut krilla::surface::Surface<'_>, size: krilla::geom::Size, settings: SvgSettings) -> Result<(), Error> { + let width = f64::from(size.width()); + let height = f64::from(size.height()); + let scale = f64::from(settings.filter_scale); + if !width.is_finite() || !height.is_finite() || !scale.is_finite() || width <= 0.0 || height <= 0.0 || scale <= 0.0 { + return Err(Error::DrawLimit); + } + let area = width * height * (96.0_f64 / 72.0).powi(2); + let filter_area = area * scale * scale; + if !area.is_finite() || !filter_area.is_finite() || area > self.limits.vector_pixels as f64 || filter_area > self.limits.filter_pixels as f64 + { + return Err(Error::DrawLimit); + } + surface.draw_svg(&self.tree, size, settings).ok_or(Error::Draw) + } +} + +#[derive(Default)] +struct Usage { + svg_bytes: AtomicUsize, + svg_depth: AtomicUsize, + image_bytes: AtomicUsize, +} + +fn shared_limits(bytes: usize, limits: Limits) -> craft_svg::tree::Limits { + craft_svg::tree::Limits { + bytes, + depth: limits.depth, + tree_depth: limits.depth, + refuse_entity_markup: true, + xml_nodes: limits.xml_nodes, + embedded_bytes: limits.embedded_svg_bytes, + embedded_depth: limits.embedded_svg_depth, + ..Default::default() + } +} + +fn bounded_text(bytes: &[u8], byte_limit: usize, limits: Limits) -> Result<std::borrow::Cow<'_, str>, craft_svg::tree::Error> { + craft_svg::tree::text(bytes, &shared_limits(byte_limit, limits)) +} + +fn reserve(counter: &AtomicUsize, amount: usize, limit: usize) -> bool { + counter.try_update(Ordering::Relaxed, Ordering::Relaxed, |used| used.checked_add(amount).filter(|next| *next <= limit)).is_ok() +} + +fn embedded_svg(usage: &Usage, limits: Limits, bytes: &[u8], options: &usvg::Options<'_>) -> Option<usvg::ImageKind> { + let used = usage.svg_bytes.load(Ordering::Relaxed); + let remaining = limits.embedded_svg_bytes.saturating_sub(used); + let text = bounded_text(bytes, remaining.min(limits.input_bytes), limits).ok()?; + if !reserve(&usage.svg_bytes, text.len(), limits.embedded_svg_bytes) { + return None; + } + let depth = usage.svg_depth.fetch_add(1, Ordering::Relaxed); + if depth >= limits.embedded_svg_depth { + usage.svg_depth.fetch_sub(1, Ordering::Relaxed); + return None; + } + let parsed = usvg::Tree::from_str(&text, options).ok(); + usage.svg_depth.fetch_sub(1, Ordering::Relaxed); + parsed.map(usvg::ImageKind::SVG) +} + +fn image_resolver(limits: Limits) -> usvg::ImageHrefResolver<'static> { + let usage = Arc::new(Usage::default()); + let default_data = usvg::ImageHrefResolver::default_data_resolver(); + usvg::ImageHrefResolver { + resolve_data: Box::new(move |mime, bytes, options| { + if mime == "image/svg+xml" || (mime == "text/plain" && (craft_svg::sniff::is_svg(&bytes) || craft_svg::sniff::is_svgz(&bytes))) { + return embedded_svg(&usage, limits, &bytes, options); + } + if !reserve(&usage.image_bytes, bytes.len(), limits.embedded_image_bytes) { + return None; + } + default_data(mime, bytes, options) + }), + resolve_string: Box::new(|_, _| None), + } +} + +#[cfg(test)] +mod tests { + use super::{Limits, shared_limits}; + + #[test] + fn shared_depth_limit_also_bounds_svg_references() { + let limits = shared_limits(1024, Limits { depth: 7, ..Limits::default() }); + assert_eq!(limits.depth, 7); + assert_eq!(limits.tree_depth, 7); + } +} diff --git a/crates/pdf/tests/cos/bounded_writer.rs b/crates/pdf/tests/cos/bounded_writer.rs index b8fe79370..5677ca542 100644 --- a/crates/pdf/tests/cos/bounded_writer.rs +++ b/crates/pdf/tests/cos/bounded_writer.rs @@ -139,7 +139,8 @@ fn full_rewrites_preserve_graph_across_multiple_object_streams_and_evictions() { } fn protect(doc: &mut Document, algorithm: Algorithm) { - doc.set_encryption(&NewEncryption { + // Every algorithm, RC4 included, has to survive a rewrite. + doc.set_encryption_legacy(&NewEncryption { algorithm, user_password: "user", owner_password: "owner", diff --git a/crates/pdf/tests/cos/encryption.rs b/crates/pdf/tests/cos/encryption.rs index 923b04e39..2ac53cb69 100644 --- a/crates/pdf/tests/cos/encryption.rs +++ b/crates/pdf/tests/cos/encryption.rs @@ -39,9 +39,11 @@ fn fixture_with(extra: &str) -> Vec<u8> { out } +/// Every algorithm, RC4-40 and RC4-128 included: those two are the legacy schemes, which +/// `set_encryption` refuses. fn protect(alg: Algorithm, user: &str, owner: &str, permissions: i32) -> Vec<u8> { let mut doc = Document::open(Arc::new(fixture())).unwrap(); - doc.set_encryption(&NewEncryption { + doc.set_encryption_legacy(&NewEncryption { algorithm: alg, user_password: user, owner_password: owner, @@ -287,7 +289,7 @@ fn signature_contents_stay_unencrypted() { c.set(b"Test".to_vec(), Object::Array(vec![Object::Ref(sig), Object::Ref(untyped), Object::Ref(note)])) }) .unwrap(); - doc.set_encryption(&NewEncryption { + doc.set_encryption_legacy(&NewEncryption { algorithm: alg, user_password: "", owner_password: "owner", @@ -423,7 +425,7 @@ fn an_earlier_revision_opens_with_the_documents_own_credentials() { // Another file, encrypted with other keys: the document's key is no use, and it says so. let other = { let mut doc = Document::open(Arc::new(fixture())).unwrap(); - doc.set_encryption(&NewEncryption { + doc.set_encryption_legacy(&NewEncryption { algorithm: alg, user_password: "user", owner_password: "owner", @@ -444,7 +446,7 @@ fn an_earlier_revision_opens_with_the_documents_own_credentials() { /// instead of as an indirect object. fn protect_inline(alg: Algorithm, user: &str, owner: &str) -> Vec<u8> { let mut doc = Document::open(Arc::new(fixture())).unwrap(); - doc.set_encryption(&NewEncryption { + doc.set_encryption_legacy(&NewEncryption { algorithm: alg, user_password: user, owner_password: owner, diff --git a/crates/pdf/tests/cos/file_identifier.rs b/crates/pdf/tests/cos/file_identifier.rs index 551db4ebd..5ca0f0f54 100644 --- a/crates/pdf/tests/cos/file_identifier.rs +++ b/crates/pdf/tests/cos/file_identifier.rs @@ -122,7 +122,8 @@ fn caller_entropy_makes_the_new_identifier_reproducible() { fn an_encrypted_rewrite_keeps_the_first_identifier_string_its_key_depends_on() { for algorithm in [Algorithm::Rc4_128, Algorithm::Aes128, Algorithm::Aes256] { let mut doc = reopen(source(true)); - doc.set_encryption(&NewEncryption { + // The loop covers RC4-128, which `set_encryption` refuses. + doc.set_encryption_legacy(&NewEncryption { algorithm, user_password: "user", owner_password: "owner", @@ -160,7 +161,7 @@ fn unusable_ids() -> Vec<(&'static str, Option<Object>)> { /// An encrypted file whose key is derived from the empty string, with its trailer `/ID` replaced by `id`. fn protected_with_id(algorithm: Algorithm, id: Option<Object>) -> Vec<u8> { let mut doc = reopen(source_with(Some("/ID [<> <>]"))); - doc.set_encryption(&NewEncryption { + doc.set_encryption_legacy(&NewEncryption { algorithm, user_password: "user", owner_password: "owner", diff --git a/crates/pdf/tests/crypt/permissions_revision.rs b/crates/pdf/tests/crypt/permissions_revision.rs index 06a5a5b98..a58868637 100644 --- a/crates/pdf/tests/crypt/permissions_revision.rs +++ b/crates/pdf/tests/crypt/permissions_revision.rs @@ -3,7 +3,7 @@ //! //! Bit n has the mask `1 << (n - 1)`. Readers use bits 3 to 6 and 9 to 12 and ignore the rest. -use craft_pdf::crypt::{Algorithm, Auth, NewEncryption, Permissions, SecurityHandler, create}; +use craft_pdf::crypt::{Algorithm, Auth, NewEncryption, Permissions, SecurityHandler, create_legacy}; const ID: &[u8] = b"0123456789abcdef"; const T: bool = true; @@ -18,7 +18,7 @@ fn cells(p: &Permissions) -> [bool; 8] { /// Creates a file with `flags` at revision `revision`, opens it with the user password, and /// returns the user's permissions. fn user_view(alg: Algorithm, revision: i64, flags: i32) -> Permissions { - let made = create( + let made = create_legacy( &NewEncryption { algorithm: alg, user_password: "user", owner_password: "owner", permissions: flags, encrypt_metadata: true, seed: [42; 32] }, ID, ) @@ -56,7 +56,7 @@ fn revision_three_rows_hold_through_a_created_and_reopened_file() { #[test] fn owner_access_gives_every_flag() { - let made = create( + let made = create_legacy( &NewEncryption { algorithm: Algorithm::Rc4_128, user_password: "user", diff --git a/crates/pdf/tests/crypt/proptests.rs b/crates/pdf/tests/crypt/proptests.rs index a81808ab9..7b9ede4d3 100644 --- a/crates/pdf/tests/crypt/proptests.rs +++ b/crates/pdf/tests/crypt/proptests.rs @@ -19,7 +19,7 @@ use craft_pdf::crypt::{ Algorithm, Auth, CryptError, Method, NewEncryption, PADDING, SecurityHandler, StreamKind, aes_cbc_decrypt, aes_cbc_encrypt, create, - effective_password, pdfdoc_byte, rc4, + create_legacy, effective_password, pdfdoc_byte, rc4, }; use proptest::prelude::*; @@ -92,8 +92,12 @@ fn expected_auth(algorithm: Algorithm, user_target: &[u8], owner_target: &[u8], } fn make(algorithm: Algorithm, user: &str, owner: &str) -> SecurityHandler { - create(&NewEncryption { algorithm, user_password: user, owner_password: owner, permissions: -1, encrypt_metadata: true, seed: [0x5e; 32] }, ID) - .unwrap() + // These properties read and write every algorithm, RC4 included. + create_legacy( + &NewEncryption { algorithm, user_password: user, owner_password: owner, permissions: -1, encrypt_metadata: true, seed: [0x5e; 32] }, + ID, + ) + .unwrap() } proptest! { @@ -457,7 +461,7 @@ proptest! { } // Revisions below 4 always encrypt metadata, whatever the caller asked for. - let legacy = create(&NewEncryption { algorithm: Algorithm::Rc4_128, user_password: "user", owner_password: "owner", permissions: -1, encrypt_metadata: false, seed: [0x5e; 32] }, ID).unwrap(); + let legacy = create_legacy(&NewEncryption { algorithm: Algorithm::Rc4_128, user_password: "user", owner_password: "owner", permissions: -1, encrypt_metadata: false, seed: [0x5e; 32] }, ID).unwrap(); prop_assert!(legacy.dict().encrypt_metadata && legacy.encrypts_metadata(), "V<4 always encrypts metadata, as create() documents"); } diff --git a/crates/pkcs7/src/pkcs12.rs b/crates/pkcs7/src/pkcs12.rs index f14b2297e..ee245f380 100644 --- a/crates/pkcs7/src/pkcs12.rs +++ b/crates/pkcs7/src/pkcs12.rs @@ -184,6 +184,12 @@ impl Cipher { } } +/// Whether `a` and `b` are equal, in time that depends only on their lengths: the MAC is derived +/// from the password, so it is compared without stopping at the first differing byte. +fn same(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + fn hmac(alg: DigestAlg, key: &[u8], data: &[u8]) -> Result<Vec<u8>, Error> { fn run<D: hmac::EagerHash>(key: &[u8], data: &[u8]) -> Result<Vec<u8>, Error> where @@ -411,7 +417,8 @@ pub fn open(bytes: &[u8], password: &str) -> Result<DigitalId, Error> { let key_len = alg.digest(&[]).len(); let iterations = budget.spend(alg, iterations, key_len)?; let key = pkcs12_kdf(alg, &bmp(password), &salt, 3, iterations, key_len); - if hmac(alg, &key, &content)? != *expected { + let computed = hmac(alg, &key, &content)?; + if !same(&computed, &expected) { return Err(Error::WrongPassword); } } diff --git a/crates/prc/src/bits.rs b/crates/prc/src/bits.rs index 837d281f3..b6897e56f 100644 --- a/crates/prc/src/bits.rs +++ b/crates/prc/src/bits.rs @@ -69,7 +69,6 @@ impl<'a> BitReader<'a> { } /// Array elements this reader may still decode. - #[cfg(test)] pub(crate) fn elements_left(&self) -> usize { self.budget.elements } diff --git a/crates/prc/src/tess.rs b/crates/prc/src/tess.rs index c9bffb30f..a7614b0a5 100644 --- a/crates/prc/src/tess.rs +++ b/crates/prc/src/tess.rs @@ -2,12 +2,14 @@ //! (172) with its `TESS_Face`s (174), `TESS_3D_Wire` (175), `TESS_Markup` (176) and //! `TESS_3D_Compressed` (173) [WD 7.3.7, 7.8]. //! -//! `TESS_3D_Compressed` is read field by field to its end [WD 7.8.9.7] so the entities after -//! it decode; its triangles are not rebuilt. +//! `TESS_3D_Compressed` is read field by field to its end [WD 7.8.9.7]. One whose normals are +//! recalculated is rebuilt into triangles ([`compressed`]); one that stores its normals, or +//! whose arrays do not fit the traversal, is not. //! //! The schema runs after the fields of each concrete type read here (201, 172, 173, 174, 175, //! 176, 305), not for the abstract levels (`PRCBase`, `TESS`). +mod compressed; mod triangulate; use crate::arrays; @@ -49,7 +51,8 @@ pub enum Tessellation { Wire(Vec<Vec<[f64; 3]>>), /// A `TESS_Markup` (PMI drawing), read past but not decoded. Markup, - /// A `TESS_3D_Compressed` mesh, read past but not rebuilt. + /// A `TESS_3D_Compressed` mesh, read past but not rebuilt: it stores its normals, or its + /// arrays do not fit the traversal. One that is rebuilt is a [`Tessellation::Mesh`]. #[non_exhaustive] Compressed { /// The entity's triangle count. @@ -65,7 +68,8 @@ pub struct TriangleMesh { /// The coordinate array as points. pub positions: Vec<[f64; 3]>, /// Counter-clockwise triangles seen from the outside, as indices into - /// [`Self::positions`] [WD 7.8.5.2]. + /// [`Self::positions`] [WD 7.8.5.2]. A rebuilt `TESS_3D_Compressed` keeps its traversal's + /// winding, which is not oriented. pub triangles: Vec<[u32; 3]>, /// `triangles` split by `TESS_Face`: face `i` is `triangles[faces[i].clone()]`. pub faces: Vec<std::ops::Range<usize>>, @@ -136,7 +140,7 @@ impl Ctx<'_, '_> { self.markup()?; Tessellation::Markup } - TESS_3D_COMPRESSED => Tessellation::Compressed { triangles: self.tess_3d_compressed()? }, + TESS_3D_COMPRESSED => self.tess_3d_compressed()?, t => return Err(malformed(format!("entity type {t} in the tessellation array"))), }); } @@ -295,23 +299,25 @@ impl Ctx<'_, '_> { self.schema.skip_added_fields(TESS_MARKUP, &mut self.r) } - /// `TESS_3D_Compressed` (173) after its type code [WD 7.8.9.7], read past; returns its - /// triangle count. prc-rs: the field order and version gates follow its schema. + /// `TESS_3D_Compressed` (173) after its type code [WD 7.8.9.7]: rebuilt into a mesh when + /// its normals are recalculated and its arrays fit, else read past to its end. prc-rs: the + /// field order and version gates follow its schema. /// /// Sizes the WD leaves unstated: the face count is the largest face index + 1, /// `normal_is_reversed` is one bit per triangle, and the point-reference array's /// compressed flag is implicit (more than three references). - fn tess_3d_compressed(&mut self) -> Result<usize, PrcError> { + fn tess_3d_compressed(&mut self) -> Result<Tessellation, PrcError> { let r = &mut self.r; r.bit()?; // is_calculated r.bit()?; // has_faces - r.double()?; // tolerance + let tolerance = r.double()?; + let mut origin = [0.0f64; 3]; if self.version >= ORIGIN_FROM { - for _ in 0..3 { - r.float_as_bytes()?; + for o in &mut origin { + *o = f64::from(r.float_as_bytes()?); } } - arrays::compressed_integer_array(r)?; // point_array + let points = arrays::compressed_integer_array(r)?; // point_array let edge_status = arrays::character_array(r, 2, None, false)?; let face_of = arrays::compressed_indice_array(r, None)?; let t = face_of.len(); @@ -320,42 +326,50 @@ impl Ctx<'_, '_> { } let faces = face_of.iter().max().map_or(0, |&m| (m as usize).saturating_add(1)); let n = r.unsigned_integer()? as usize; - let references = arrays::bool_array(r, n)?.iter().filter(|&&b| b).count(); - let refs = arrays::compressed_indice_array(r, Some(references > 3))?; - if refs.len() != references { - return Err(malformed(format!("{} point references for {references} flagged points", refs.len()))); + let is_reference = arrays::bool_array(r, n)?; + let flagged = is_reference.iter().filter(|&&b| b).count(); + let references = arrays::compressed_indice_array(r, Some(flagged > 3))?; + if references.len() != flagged { + return Err(malformed(format!("{} point references for {flagged} flagged points", references.len()))); } - self.compressed_normals(t, faces)?; - let r = &mut self.r; - if r.bit()? { - arrays::bool_array(r, faces)?; // is_point_color_on_face - arrays::character_array(r, 8, None, false)?; // point_color_array + let recalc = self.compressed_normals(t, faces)?; + let attributes = self.compressed_attributes(faces)?; + if !recalc { + return Ok(Tessellation::Compressed { triangles: t }); } - if r.bit()? { - arrays::bool_array(r, faces)?; // is_multiple_line_attribute_on_face - } - arrays::short_array(r, 16)?; // line_attributes - if !r.bit()? { - self.compressed_texture_parameter()?; - if !self.r.bit()? { - arrays::bool_array(&mut self.r, faces)?; // face_has_texture - } - } - if self.r.bit()? { - arrays::character_array(&mut self.r, 8, None, false)?; // behaviours - } - self.schema.skip_added_fields(TESS_3D_COMPRESSED, &mut self.r)?; - Ok(t) + let arrays = compressed::Arrays { + tolerance, + origin, + points: &points, + edge_status: &edge_status, + triangles: t, + is_reference: &is_reference, + references: &references, + limit: self.r.elements_left(), + }; + // A walk that would outgrow the allowance left stops there, and the arrays stay + // compressed, as do arrays the walk does not fit. + let Ok(m) = compressed::rebuild(&arrays) else { + return Ok(Tessellation::Compressed { triangles: t }); + }; + // The rebuilt triangles, their styles and every face range are charged once the arrays + // fit and before any of them is made, so arrays that do not fit spend nothing. + let styled = attributes.styled(faces); + let kept = m.triangles.len().saturating_mul(triangle_elements(false, 0, styled)); + self.r.take_elements(kept.saturating_add(faces.saturating_mul(RANGE_ELEMENTS)))?; + let styles = if styled { attributes.styles(&face_of, faces) } else { Vec::new() }; + Ok(Tessellation::Mesh(by_face(m, &face_of, faces, &styles))) } - /// A compressed tessellation's normals, from `must_recalculate_normals` on, read past. - fn compressed_normals(&mut self, triangles: usize, faces: usize) -> Result<(), PrcError> { + /// A compressed tessellation's normals, from `must_recalculate_normals` on, read past; + /// returns whether they are recalculated. + fn compressed_normals(&mut self, triangles: usize, faces: usize) -> Result<bool, PrcError> { let r = &mut self.r; if r.bit()? { arrays::bool_array(r, triangles)?; // normal_is_reversed r.double()?; // crease_angle r.character()?; // normal_recalculation_flags - return Ok(()); + return Ok(true); } let angle_bits = u32::from(r.character()?); if angle_bits > MAX_ANGLE_BITS { @@ -365,7 +379,29 @@ impl Ctx<'_, '_> { arrays::bool_array(r, n)?; // is_binary_normal arrays::short_array(r, angle_bits)?; // normal angles arrays::bool_array(r, faces)?; // is_face_planar - Ok(()) + Ok(false) + } + + /// A compressed tessellation's colours, line attributes, texture and behaviours, through + /// its added schema fields; returns what its faces' styles are made from. + fn compressed_attributes(&mut self, faces: usize) -> Result<FaceAttributes, PrcError> { + let r = &mut self.r; + if r.bit()? { + arrays::bool_array(r, faces)?; // is_point_color_on_face + arrays::character_array(r, 8, None, false)?; // point_color_array + } + // is_multiple_line_attribute_on_face + let multi = if r.bit()? { arrays::bool_array(r, faces)? } else { Vec::new() }; + let line_attributes = arrays::short_array(r, 16)?; + if !r.bit()? { + self.compressed_texture_parameter()?; + if !self.r.bit()? { + arrays::bool_array(&mut self.r, faces)?; // face_has_texture + } + } + let behaviours = if self.r.bit()? { arrays::character_array(&mut self.r, 8, None, false)? } else { Vec::new() }; + self.schema.skip_added_fields(TESS_3D_COMPRESSED, &mut self.r)?; + Ok(FaceAttributes { multi, line_attributes, behaviours }) } /// `CompressedTextureParameter` [WD 7.8.9.8-7.8.9.9; pdf-issues #729, #749], read past. @@ -387,6 +423,71 @@ impl Ctx<'_, '_> { } } +/// Budget elements one face range (`Range<usize>`) takes. +const RANGE_ELEMENTS: usize = std::mem::size_of::<std::ops::Range<usize>>().div_ceil(8); + +/// What a compressed tessellation's faces are styled from [WD 7.8.9.5]: with no face flagged +/// `is_multiple_line_attribute_on_face` (`multi`), `line_attributes` holds one style index + 1 +/// per face (0 keeps the owner's graphics) and `behaviours` one behaviour byte per face. +struct FaceAttributes { + multi: Vec<bool>, + line_attributes: Vec<i32>, + behaviours: Vec<i32>, +} + +impl FaceAttributes { + /// Whether the faces give their triangles styles. The one-per-triangle layout of a flagged + /// face is not established, so such a tessellation keeps its owner's graphics, as does one + /// whose attributes and behaviours are all 0. + fn styled(&self, faces: usize) -> bool { + let behaviours = self.behaviours.len() == faces && self.behaviours.iter().any(|&b| b != 0); + !self.multi.iter().any(|&b| b) && self.line_attributes.len() == faces && (behaviours || self.line_attributes.iter().any(|&a| a != 0)) + } + + /// Per triangle, the style its face gives it; call only when [`Self::styled`]. + fn styles(&self, face_of: &[u32], faces: usize) -> Vec<TriangleStyle> { + let behaviour = |f: usize| { + if self.behaviours.len() == faces { self.behaviours.get(f).and_then(|&b| u16::try_from(b).ok()).unwrap_or(0) } else { 0 } + }; + face_of + .iter() + .map(|&f| { + let f = f as usize; + TriangleStyle { style: self.line_attributes.get(f).and_then(|&a| u32::try_from(a).ok()).unwrap_or(0), behaviour: behaviour(f) } + }) + .collect() + } +} + +/// A rebuilt compressed mesh with its triangles grouped by face, in walk order within each, +/// so face `i` is `triangles[faces[i].clone()]` as for a `TESS_3D`. `faces` is charged to the +/// element budget by the caller. +fn by_face(m: compressed::Rebuilt, face_of: &[u32], faces: usize, styles: &[TriangleStyle]) -> TriangleMesh { + let mut order: Vec<usize> = (0..m.triangles.len()).collect(); + order.sort_by_key(|&i| face_of.get(i).copied().unwrap_or(0)); + let mut mesh = TriangleMesh { positions: m.positions, normals_recalculated: true, ..TriangleMesh::default() }; + mesh.faces = Vec::with_capacity(faces); + for &i in &order { + let f = face_of.get(i).map_or(0, |&f| f as usize); + while mesh.faces.len() <= f { + let at = mesh.triangles.len(); + mesh.faces.push(at..at); + } + if let (Some(&t), Some(r)) = (m.triangles.get(i), mesh.faces.last_mut()) { + mesh.triangles.push(t); + r.end = mesh.triangles.len(); + } + if let Some(&s) = styles.get(i) { + mesh.triangle_styles.push(s); + } + } + while mesh.faces.len() < faces { + let at = mesh.triangles.len(); + mesh.faces.push(at..at); + } + mesh +} + /// The normal array and each triangle's corner normals, or both empty when any slot fails to /// name a normal: a mesh shades from its stored normals wholly or not at all. fn stored_normals(coords: &[f64], slots: &[[u32; 3]], triangles: usize) -> (Vec<[f64; 3]>, Vec<[u32; 3]>) { diff --git a/crates/prc/src/tess/compressed.rs b/crates/prc/src/tess/compressed.rs new file mode 100644 index 000000000..53e082b4d --- /dev/null +++ b/crates/prc/src/tess/compressed.rs @@ -0,0 +1,353 @@ +//! Triangle reconstruction for a `TESS_3D_Compressed` (173) whose normals are recalculated +//! [WD 7.8.9, 7.8.9.2, 7.8.9.7]. +//! +//! The WD names the arrays but not the traversal that wrote them; the rules below are the ones +//! the arrays fit when every slot, reference and point is consumed exactly. They are inferred +//! from compressed tessellations and are not WD text. +//! +//! Traversal. A component starts with a seed triangle of three slots; every later triangle +//! takes one slot, its apex. A slot flagged in `point_is_reference` takes the next +//! `point_reference_array` value, a vertex number; any other slot makes the next vertex from +//! the next `point_array` triple. Triangle `[A B C]`, entered across `[A B]`, reads +//! `edge_status & 3`: bit 1 continues across `[C B]`, bit 0 across `[A C]`; with both, +//! `[C B]` is taken and `[A C]` pushed. With neither, pushed edges are popped, skipping any +//! already shared by two triangles; an empty stack starts the next component. A triangle +//! whose continuation edge is already shared by two triangles, while the other edge is open, +//! continues across the open one. +//! +//! Geometry, in units of `tolerance`: +//! - seed: `V0 = origin + d`, `V1 = V0 + d`, `V2 = mid(V0, V1) + d`; +//! - apex across `[P Q]` with the triangle's third vertex `W` [WD 7.8.9.2]: with +//! `O = (P + Q) * 0.5`, `L` and `H` the lower- and higher-numbered of `P`, `Q`, +//! `X = unitize(L - H)`, `Z = unitize((W - O) x X)` and `Y = unitize(Z x X)`, the apex is +//! `((O + d.x X) - d.y Y) - d.z Z`. +//! +//! Arithmetic. The encoder frames each apex on the points it already approximated [WD 7.8.9], +//! so the decoder repeats the encoder's floating point: a last-bit difference compounds from +//! apex to apex. `unitize` therefore matches the WD's `PrcPt::Unitize` pseudocode [WD 12.3] as +//! read, whose length is not exact, and the operations keep the order above. +//! +//! Fold. A triangle folded against its parent swaps bits 1 and 0 for its own continuation. +//! Without stored normals to orient it, a new apex lying in its parent's plane on the parent's +//! side (`d.z == 0`, `d.y > 0`) is folded. A component that does not fit is rewound and walked +//! again with the fold inverted at its second triangle, where an apex that is a reference +//! leaves no other trace of its fold. +//! +//! Only the three-statuses-per-triangle `edge_status` form is reconstructed (the first `T` +//! are read); the one-per-triangle form walks differently. + +use std::collections::HashMap; + +type V = [f64; 3]; + +/// The arrays of one `TESS_3D_Compressed` the walk reads. +pub(super) struct Arrays<'a> { + pub(super) tolerance: f64, + pub(super) origin: V, + pub(super) points: &'a [i64], + pub(super) edge_status: &'a [i32], + pub(super) triangles: usize, + pub(super) is_reference: &'a [bool], + pub(super) references: &'a [u32], + /// Budget elements the walk may hold at once (see [`Walk::held`]). + pub(super) limit: usize, +} + +/// The rebuilt vertices and triangles, in walk order. +#[derive(Debug)] +pub(super) struct Rebuilt { + pub(super) positions: Vec<V>, + pub(super) triangles: Vec<[u32; 3]>, +} + +/// Rebuilds the mesh, or says why the arrays do not fit the traversal. +pub(super) fn rebuild(a: &Arrays<'_>) -> Result<Rebuilt, &'static str> { + if a.edge_status.len() != a.triangles.saturating_mul(3) { + return Err("the one-status-per-triangle edge form is not reconstructed"); + } + let mut w = Walk::new(a.triangles, a.limit); + w.walk(a)?; + if w.slot != a.is_reference.len() || w.ri != a.references.len() || w.pi != a.points.len() { + return Err("the decoded triangles do not use up the stored arrays"); + } + Ok(Rebuilt { positions: w.pos, triangles: w.tris }) +} + +fn add(a: V, b: V) -> V { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} +fn sub(a: V, b: V) -> V { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} +fn scale(a: V, s: f64) -> V { + a.map(|c| c * s) +} +fn dot(a: V, b: V) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} +fn cross(a: V, b: V) -> V { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} +fn key(a: u32, b: u32) -> (u32, u32) { + if a < b { (a, b) } else { (b, a) } +} + +/// `PrcPt::Length` [WD 12.3]: the squared length summed in `f64` and rounded to `f32`, then +/// Newton's square root in `f64`, seeded with that `f32` with its exponent halved. The printed +/// loop never advances its iterate; it is read as iterating until two successive values are +/// equal, `None` (the WD's -1) when 100 steps do not settle. +fn wd_length(a: V) -> Option<f64> { + let squared = (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]) as f32; + let bits = squared.to_bits(); + let exponent = (bits >> 23) & 0xff; + let seed = if exponent > 127 { f32::from_bits((bits & !(0xff << 23)) | (((exponent - 127) / 2 + 127) << 23)) } else { squared }; + let squared = f64::from(squared); + let mut x = f64::from(seed); + for _ in 0..100 { + let next = 0.5 * (x + squared / x); + if next == x { + return Some(next); + } + x = next; + } + None +} + +/// `PrcPt::Unitize` [WD 12.3]: each component divided by [`wd_length`]; `None` below +/// `FLT_EPSILON`. +fn unitize(a: V) -> Option<V> { + let l = wd_length(a).filter(|&l| l >= f64::from(f32::EPSILON))?; + Some([a[0] / l, a[1] / l, a[2] / l]) +} + +/// The `Z` of `PrcPt::MakeOrthoRep` [WD 12.3] on `X`: `unitize(X x (0, 1, 0))`, or +/// `X x (1, 0, 0)` when that is null, from `X` unitized again as the pseudocode does. +fn make_ortho_rep_z(x: V) -> Option<V> { + let x = unitize(x)?; + unitize(cross(x, [0.0, 1.0, 0.0])).or_else(|| unitize(cross(x, [1.0, 0.0, 0.0]))) +} + +/// The apex across `[lo hi]` (`lo` the lower-numbered vertex) opposite `w`, `d` already scaled +/// by the tolerance [WD 7.8.9.2]. A null `Z` or `Y` takes `MakeOrthoRep(X)`'s `Z` as the WD +/// prescribes, with `Y = unitize(Z x X)` from the frame's own `X` (not the copy `MakeOrthoRep` +/// unitized again, whose last bits differ), turned a half-turn about `X` when the residue of +/// `(W - O) x X` points against that `Z`. A null `X`, an edge the WD's non-degeneracy rule +/// excludes, is used as it is. +fn apex(lo: V, hi: V, w: V, d: V) -> V { + let o = scale(add(lo, hi), 0.5); + let x = sub(lo, hi); + let x = unitize(x).unwrap_or(x); + let residue = cross(sub(w, o), x); + let (y, z) = unitize(residue) + .and_then(|z| Some((unitize(cross(z, x))?, z))) + .or_else(|| { + let z = make_ortho_rep_z(x)?; + let y = unitize(cross(z, x))?; + Some(if dot(residue, z) < 0.0 { (scale(y, -1.0), scale(z, -1.0)) } else { (y, z) }) + }) + .unwrap_or_default(); + sub(sub(add(o, scale(x, d[0])), scale(y, d[1])), scale(z, d[2])) +} + +/// Traversal state; `log` records every edge-count increment so a component can be rewound. +/// Everything it holds is checked against [`Arrays::limit`] after each triangle. +#[derive(Default)] +struct Walk { + pos: Vec<V>, + tris: Vec<[u32; 3]>, + edges: HashMap<(u32, u32), u8>, + log: Vec<(u32, u32)>, + stack: Vec<(u32, u32, u32)>, + next: Option<(u32, u32, u32)>, + slot: usize, + ri: usize, + pi: usize, +} + +/// Where a component starts, to rewind to. +#[derive(Clone, Copy)] +struct Mark { + tri: usize, + pos: usize, + log: usize, + slot: usize, + ri: usize, + pi: usize, +} + +impl Walk { + /// Reserves room for `t` triangles, no more than `limit` elements' worth (two each). + fn new(t: usize, limit: usize) -> Self { + Walk { tris: Vec::with_capacity(t.min(limit / 2).min(1 << 20)), ..Walk::default() } + } + + fn mark(&self, tri: usize) -> Mark { + Mark { tri, pos: self.pos.len(), log: self.log.len(), slot: self.slot, ri: self.ri, pi: self.pi } + } + + fn rewind(&mut self, m: Mark) { + for k in self.log.drain(m.log..) { + if let Some(n) = self.edges.get_mut(&k) { + *n = n.saturating_sub(1); + } + } + self.pos.truncate(m.pos); + self.tris.truncate(m.tri); + self.stack.clear(); + self.next = None; + (self.slot, self.ri, self.pi) = (m.slot, m.ri, m.pi); + } + + /// One slot: `Some(v)` a reference to vertex `v`, `None` a new point. + fn take(&mut self, a: &Arrays<'_>) -> Result<Option<u32>, &'static str> { + let flagged = *a.is_reference.get(self.slot).ok_or("slots run out")?; + self.slot = self.slot.saturating_add(1); + if !flagged { + return Ok(None); + } + let v = *a.references.get(self.ri).ok_or("references run out")?; + self.ri = self.ri.saturating_add(1); + self.get(v)?; + Ok(Some(v)) + } + + fn point(&mut self, a: &Arrays<'_>) -> Result<V, &'static str> { + let Some(&[x, y, z]) = a.points.get(self.pi..self.pi.saturating_add(3)) else { + return Err("points run out"); + }; + self.pi = self.pi.saturating_add(3); + let tol = a.tolerance; + Ok([x as f64 * tol, y as f64 * tol, z as f64 * tol]) + } + + fn get(&self, v: u32) -> Result<V, &'static str> { + self.pos.get(v as usize).copied().ok_or("a triangle refers to a vertex not yet decoded") + } + + fn push(&mut self, p: V) -> Result<u32, &'static str> { + let id = u32::try_from(self.pos.len()).map_err(|_| "too many vertices")?; + self.pos.push(p); + Ok(id) + } + + /// The next triangle and its default fold: the seed, or the apex across the edge to + /// continue from. + fn triangle(&mut self, a: &Arrays<'_>) -> Result<([u32; 3], bool), &'static str> { + if let Some((p, q, w)) = self.next.take() { + if let Some(r) = self.take(a)? { + return Ok(([p, q, r], false)); + } + let (pp, qq, ww) = (self.get(p)?, self.get(q)?, self.get(w)?); + let (lo, hi) = if p < q { (pp, qq) } else { (qq, pp) }; + let fold = matches!(a.points.get(self.pi..self.pi.saturating_add(3)), Some(&[_, dy, 0]) if dy > 0); + let d = self.point(a)?; + let r = self.push(apex(lo, hi, ww, d))?; + return Ok(([p, q, r], fold)); + } + let mut v = [0u32; 3]; + for k in 0..3 { + let id = match self.take(a)? { + Some(r) => r, + None => { + let d = self.point(a)?; + let p = match k { + 0 => add(a.origin, d), + 1 => add(self.get(v[0])?, d), + _ => add(scale(add(self.get(v[0])?, self.get(v[1])?), 0.5), d), + }; + self.push(p)? + } + }; + if let Some(s) = v.get_mut(k) { + *s = id; + } + } + Ok((v, false)) + } + + /// Budget elements (8 bytes each) the walk's arrays hold, by length: growth can add up to + /// as much again in spare capacity. + fn held(&self) -> usize { + let pos = self.pos.len().saturating_mul(3); + let tris = self.tris.len().saturating_mul(2); + let edges = self.edges.len().saturating_mul(2); + let stack = self.stack.len().saturating_mul(2); + pos.saturating_add(tris).saturating_add(edges).saturating_add(self.log.len()).saturating_add(stack) + } + + fn closed(&self, e: (u32, u32, u32)) -> bool { + self.edges.get(&key(e.0, e.1)).copied().unwrap_or(0) >= 2 + } + + /// Adds one triangle; `flip` inverts its fold. + fn step(&mut self, a: &Arrays<'_>, status: i32, flip: bool) -> Result<(), &'static str> { + let ([ta, tb, tc], fold) = self.triangle(a)?; + for (x, y) in [(ta, tb), (tb, tc), (tc, ta)] { + let n = self.edges.entry(key(x, y)).or_insert(0); + *n = n.saturating_add(1); + let shared = *n; + self.log.push(key(x, y)); + if shared > 2 { + return Err("an edge is shared by more than two triangles"); + } + } + self.tris.push([ta, tb, tc]); + if self.held() > a.limit { + return Err("the rebuild needs more than the decoded-element allowance left"); + } + let (mut left, mut right) = ((tc, tb, ta), (ta, tc, tb)); + if fold != flip { + std::mem::swap(&mut left, &mut right); + } + let (taken, other) = if status & 2 != 0 { (left, right) } else { (right, left) }; + if status & 3 != 0 && self.closed(taken) && !self.closed(other) { + std::mem::swap(&mut left, &mut right); + } + match (status & 2 != 0, status & 1 != 0) { + (true, true) => { + self.next = Some(left); + self.stack.push(right); + } + (true, false) => self.next = Some(left), + (false, true) => self.next = Some(right), + (false, false) => {} + } + while self.next.is_none() { + let Some(e) = self.stack.pop() else { break }; + if !self.closed(e) { + self.next = Some(e); + } + } + Ok(()) + } + + /// Walks every component. One that fails is rewound and walked once more with the fold + /// inverted at its second triangle, so the walk is at most twice the triangle count. + fn walk(&mut self, a: &Arrays<'_>) -> Result<(), &'static str> { + let mut start = self.mark(0); + let mut flip_at = None; + let mut i = 0; + while i < a.triangles { + if self.next.is_none() && !(flip_at.is_some() && i == start.tri) { + start = self.mark(i); + flip_at = None; + } + let status = a.edge_status.get(i).copied().unwrap_or(0); + match self.step(a, status, flip_at == Some(i)) { + Ok(()) => i = i.saturating_add(1), + Err(e) => { + if flip_at.is_some() || i == start.tri { + return Err(e); + } + self.rewind(start); + flip_at = Some(start.tri.saturating_add(1)); + i = start.tri; + } + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/prc/src/tess/compressed/tests.rs b/crates/prc/src/tess/compressed/tests.rs new file mode 100644 index 000000000..d174ff657 --- /dev/null +++ b/crates/prc/src/tess/compressed/tests.rs @@ -0,0 +1,299 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; + +const S: f64 = std::f64::consts::SQRT_2; + +fn run(points: &[i64], status: &[i32], t: usize, is_ref: &[bool], refs: &[u32]) -> Result<Rebuilt, &'static str> { + rebuild(&Arrays { + tolerance: 0.5, + origin: [10.0, 0.0, 0.0], + points, + edge_status: status, + triangles: t, + is_reference: is_ref, + references: refs, + limit: usize::MAX, + }) +} + +fn close(a: V, b: V) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() < 1e-9) +} + +/// Seed `[0 1 2]`, then the apex across `[2 1]`: `X` runs from vertex 2 to vertex 1, and +/// each of `d`'s three components lands on its own axis with its own sign. Tolerance 0.5 +/// halves every step. +#[test] +fn a_seed_and_one_apex_rebuild() { + let pts = [0, 0, 0, 4, 0, 0, -2, 4, 0, 2, -6, 2]; + let m = run(&pts, &[2, 0, 0, 0, 0, 0], 2, &[false; 4], &[]).unwrap(); + assert_eq!(m.triangles, [[0, 1, 2], [2, 1, 3]]); + let p: Vec<V> = m.positions.iter().map(|v| [v[0] - 10.0, v[1], v[2]]).collect(); + assert!(close(p[0], [0.0, 0.0, 0.0]) && close(p[1], [2.0, 0.0, 0.0])); + assert!(close(p[2], [0.0, 2.0, 0.0]), "{:?}", p[2]); + assert!(close(p[3], [1.0 + 2.0 * S, 1.0 + S, -1.0]), "{:?}", p[3]); +} + +/// The walk stops once its arrays would hold more than `limit` elements: the seed-and-apex +/// pair ends holding four vertices (12), two triangles (4), five edges (10) and six logged +/// edges (6), 32 in all. +#[test] +fn a_walk_past_its_limit_stops() { + let pts = [0, 0, 0, 4, 0, 0, -2, 4, 0, 2, -6, 2]; + let with = |limit| { + rebuild(&Arrays { + tolerance: 0.5, + origin: [0.0; 3], + points: &pts, + edge_status: &[2, 0, 0, 0, 0, 0], + triangles: 2, + is_reference: &[false; 4], + references: &[], + limit, + }) + }; + assert_eq!(with(32).unwrap().triangles.len(), 2); + assert_eq!(with(31).unwrap_err(), "the rebuild needs more than the decoded-element allowance left"); +} + +/// The triangles reserved up front fit the limit too. +#[test] +fn the_walk_reserves_within_its_limit() { + assert!(Walk::new(1 << 20, 10).tris.capacity() < 1 << 20); + assert!(Walk::new(1 << 20, 10).tris.capacity() <= 5); + assert!(Walk::new(4, usize::MAX).tris.capacity() >= 4); +} + +/// Bit 0 alone continues across `[A C]`, keeping `W = B`. +#[test] +fn the_right_edge_is_entered_from_a_to_c() { + let pts = [0, 0, 0, 4, 0, 0, -2, 4, 0, 0, -2, 0]; + let m = run(&pts, &[1, 0, 0, 0, 0, 0], 2, &[false; 4], &[]).unwrap(); + assert_eq!(m.triangles[1], [0, 2, 3]); +} + +/// A reference slot reuses a vertex; a closed pushed edge is skipped and the next component +/// starts from a fresh seed. +#[test] +fn references_and_components() { + let pts = [0; 9 + 9]; + let is_ref = [false, false, false, true, false, false, false]; + let m = run(&pts, &[3, 0, 0, 0, 0, 0, 0, 0, 0], 3, &is_ref, &[0]).unwrap(); + assert_eq!(m.triangles, [[0, 1, 2], [2, 1, 0], [3, 4, 5]]); +} + +/// A double-sided panel: four coplanar vertices, four triangles. The second triangle's apex +/// folds back onto the seed's side, so its own continuation takes `[A C]` first; the last two +/// apexes are the seed's first two vertices. +#[test] +fn a_folded_apex_swaps_its_continuation() { + let is_ref = [false, false, false, false, true, true]; + let status = [3, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let m = run(&[0, 0, 0, 4, 0, 0, -2, 4, 0, 1, 3, 0], &status, 4, &is_ref, &[0, 1]).unwrap(); + assert_eq!(m.triangles, [[0, 1, 2], [2, 1, 3], [2, 3, 0], [0, 3, 1]]); + // The same panel unfolded is rescued by the component retry. + let m = run(&[0, 0, 0, 4, 0, 0, -2, 4, 0, 1, -3, 0], &status, 4, &is_ref, &[0, 1]).unwrap(); + assert_eq!(m.triangles, [[0, 1, 2], [2, 1, 3], [2, 3, 0], [0, 3, 1]]); +} + +/// The fourth apex `(1, 3, 0)` lies in its parent's plane on the parent's side, so its +/// triangle folds and continues across `[A C]` to the reference. +#[test] +fn a_fold_past_the_retry_point_is_detected() { + let pts = [0, 0, 0, 4, 0, 0, -2, 4, 0, 0, -3, 1, 1, 3, 0]; + let is_ref = [false, false, false, false, false, true]; + let m = run(&pts, &[3, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0], 4, &is_ref, &[0]).unwrap(); + assert_eq!(m.triangles[3], [3, 4, 0]); +} + +/// A panel whose fold apex is a reference carries no fold signal: the unfolded walk closes an +/// edge it still needs, so the component is rewound and walked again folded at its second +/// triangle. +#[test] +fn a_reference_fold_is_found_by_retrying_the_component() { + let pts: Vec<i64> = (1..=30).collect(); + let mut is_ref = vec![false; 9]; + is_ref.extend([true, true, false, true, true, true]); + let mut status = vec![0; 21]; + status[3..7].copy_from_slice(&[3, 3, 2, 0]); + let m = run(&pts, &status, 7, &is_ref, &[0, 3, 6, 0, 3]).unwrap(); + assert_eq!(m.triangles[3..], [[0, 3, 9], [9, 3, 6], [9, 6, 0], [0, 6, 3]]); +} + +/// A tetrahedron closed by two references: after `[3 1 0]` the continuation edge `[0 1]` is +/// already shared twice, so the walk takes the open `[3 0]` instead. +#[test] +fn a_closed_continuation_edge_gives_way_to_the_open_one() { + let pts = [0, 0, 0, 4, 0, 0, -2, 4, 0, 0, 0, 4]; + let mut status = [0; 12]; + status[..3].copy_from_slice(&[2, 2, 2]); + let mut is_ref = [false; 6]; + is_ref[4..].copy_from_slice(&[true, true]); + let m = run(&pts, &status, 4, &is_ref, &[0, 2]).unwrap(); + assert_eq!(m.triangles, [[0, 1, 2], [2, 1, 3], [3, 1, 0], [3, 0, 2]]); +} + +#[test] +fn arrays_that_do_not_fit_are_refused() { + let pts = [0; 9]; + let ok = [false; 3]; + assert!(run(&pts, &[0, 0, 0], 1, &ok, &[]).is_ok()); + assert!(run(&pts, &[0], 1, &ok, &[]).is_err(), "T form"); + assert!(run(&[0; 12], &[0, 0, 0], 1, &ok, &[]).is_err(), "points left"); + assert!(run(&[0; 6], &[0, 0, 0], 1, &ok, &[]).is_err(), "points short"); + assert!(run(&pts, &[0, 0, 0], 1, &[false; 4], &[]).is_err(), "slots left"); + assert!(run(&[0; 6], &[0, 0, 0], 1, &[false, false, true], &[7]).is_err(), "forward reference"); + assert!(run(&[0; 9], &[0, 0, 0], 1, &[false, false, false, true], &[0]).is_err(), "references left"); + // A third triangle on the seed's edge [0 1], each apex a reference. + let three = [false, false, false, true, true]; + let shared = run(&[0; 9], &[2, 2, 0, 0, 0, 0, 0, 0, 0], 3, &three, &[0, 0]).map(|_| ()); + assert_eq!(shared, Err("an edge is shared by more than two triangles")); +} + +/// `PrcPt::Length` rounds the squared length to `f32` and takes Newton's root from a halved +/// exponent, which can settle an ulp off the correctly rounded root; `Unitize` refuses +/// lengths below `FLT_EPSILON` [WD 12.3]. +#[test] +fn length_and_unitize_follow_the_wd_pseudocode() { + assert_eq!(wd_length([3.0, 4.0, 0.0]), Some(5.0)); + let newton = f64::from_bits(S.to_bits() - 1); + assert_eq!(wd_length([1.0, 1.0, 0.0]), Some(newton)); + let long = 1.0 + 2f64.powi(-30); + assert_eq!(wd_length([long, 0.0, 0.0]), Some(1.0)); + assert_eq!(unitize([0.0, long, 0.0]), Some([0.0, long, 0.0])); + assert_eq!(unitize([1e-8, 0.0, 0.0]), None); + assert_eq!(unitize([0.0; 3]), None); +} + +/// A `W` on the edge's line leaves `Z` null, so the frame comes from `MakeOrthoRep(X)`: `Z` +/// from `X x (0, 1, 0)`, or from `X x (1, 0, 0)` when `X` is along `Y` [WD 7.8.9.2, 12.3]. +#[test] +fn a_null_z_takes_the_ortho_rep_of_x() { + let d = [1.0, 2.0, 3.0]; + assert_eq!(apex([0.0; 3], [-2.0, 0.0, 0.0], [5.0, 0.0, 0.0], d), [0.0, -2.0, -3.0]); + assert_eq!(apex([0.0; 3], [0.0, -2.0, 0.0], [0.0, 5.0, 0.0], d), [-2.0, 0.0, 3.0]); +} + +/// A degenerate frame is turned a half-turn about `X` when the sub-epsilon residue of +/// `(W - O) x X` points against `MakeOrthoRep`'s `Z`, and kept when it points along it. +#[test] +fn a_degenerate_frame_follows_its_residue() { + let (lo, hi, d) = ([0.0; 3], [-2.0, 0.0, 0.0], [1.0, 2.0, 3.0]); + assert_eq!(apex(lo, hi, [5.0, 1e-9, 0.0], d), [0.0, 2.0, 3.0]); + assert_eq!(apex(lo, hi, [5.0, -1e-9, 0.0], d), [0.0, -2.0, -3.0]); +} + +/// A degenerate frame's `Y` comes from the frame's own `X`, whose length `unitize` left off by +/// a few 1e-8, not from the copy `MakeOrthoRep` unitized again: the two differ by that much, +/// and the walk would carry the difference into later apexes. +#[test] +fn a_degenerate_frame_takes_y_from_its_own_x() { + let (lo, hi) = ([0.1, 0.2, 0.3], [0.7, -0.4, 0.9]); + let o = scale(add(lo, hi), 0.5); + let x = unitize(sub(lo, hi)).unwrap(); + let w = add(o, scale(x, 0.37)); + let d = [1.0, 2.0, 3.0]; + let z = make_ortho_rep_z(x).unwrap(); + let p = apex(lo, hi, w, d); + let own = unitize(cross(z, x)).unwrap(); + let again = unitize(cross(z, unitize(x).unwrap())).unwrap(); + assert_ne!(own, again, "the probe must tell the two Ys apart"); + let sign = if dot(cross(sub(w, o), x), z) < 0.0 { -1.0 } else { 1.0 }; + let expect = |y: V| sub(sub(add(o, scale(x, d[0])), scale(y, sign * d[1])), scale(z, sign * d[2])); + assert_eq!(p, expect(own)); + assert_ne!(p, expect(again)); +} + +/// A strip of thin, non-planar triangles compressed by an encoder written out from the WD: +/// each point is expressed in the frame of the working mesh, rounded to the tolerance and +/// reinjected [WD 7.8.9, 7.8.9.2], with `PrcPt::Length` and `Unitize` transcribed from the +/// pseudocode [WD 12.3] as read. The decoder must land exactly on that working mesh, which +/// keeps every vertex within the rounding bound of its source. +#[test] +fn a_strip_decodes_onto_the_encoders_working_mesh() { + fn length(v: V) -> f64 { + let f = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) as f32; + let mut bits = f.to_bits(); + let exponent = (bits >> 23) & 0xff; + if exponent > 127 { + bits = (bits & 0x807f_ffff) | (((exponent - 127) / 2 + 127) << 23); + } + let (squared, mut x0) = (f64::from(f), f64::from(f32::from_bits(bits))); + for _ in 0..100 { + let xi = 0.5 * (x0 + squared / x0); + if xi == x0 { + return xi; + } + x0 = xi; + } + -1.0 + } + fn unitized(v: V) -> V { + let l = length(v); + assert!(l >= f64::from(f32::EPSILON), "null axis"); + [v[0] / l, v[1] / l, v[2] / l] + } + let (tol, n) = (1e-4, 48); + let mut state = 0x9e37_79b9_7f4a_7c15_u64; + let mut jitter = |scale: f64| { + state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + ((state >> 11) as f64 / (1u64 << 53) as f64 - 0.5) * scale + }; + // Two rails 4 apart, 0.05 between a rail's points, 0.02 of relief. + let source: Vec<V> = (0..n) + .map(|i| { + let (along, rail) = (i as f64 * 0.025, (i % 2) as f64 * 4.0); + [along + jitter(0.01), rail + jitter(0.01), jitter(0.02)] + }) + .collect(); + let round = |v: f64| (v / tol).round() as i64; + let (mut points, mut work) = (Vec::new(), Vec::<V>::new()); + for (i, target) in source.iter().take(3).enumerate() { + let base = match i { + 0 => [0.0; 3], + 1 => work[0], + _ => scale(add(work[0], work[1]), 0.5), + }; + let d = [0, 1, 2].map(|c| round(target[c] - base[c])); + points.extend(d); + work.push(add(base, d.map(|c| c as f64 * tol))); + } + // Triangle k enters across vertices k and k + 1, opposite k - 1, and continues right on + // odd k, left on even k, unless it folds. + let mut status = vec![0; 3 * (n - 2)]; + status[0] = 2; + for k in 1..n - 2 { + let (lo, hi, w) = (work[k], work[k + 1], work[k - 1]); + let o = scale(add(hi, lo), 0.5); + let x = unitized(sub(lo, hi)); + let z = unitized(cross(sub(w, o), x)); + let y = unitized(cross(z, x)); + let r = sub(source[k + 2], o); + let d = [round(dot(r, x)), round(-dot(r, y)), round(-dot(r, z))]; + points.extend(d); + let [dx, dy, dz] = d.map(|c| c as f64 * tol); + work.push(sub(sub(add(o, scale(x, dx)), scale(y, dy)), scale(z, dz))); + if k < n - 3 { + let fold = d[2] == 0 && d[1] > 0; + status[k] = if (k % 2 == 1) != fold { 1 } else { 2 }; + } + } + let m = rebuild(&Arrays { + tolerance: tol, + origin: [0.0; 3], + points: &points, + edge_status: &status, + triangles: n - 2, + is_reference: &vec![false; n], + references: &[], + limit: usize::MAX, + }) + .unwrap(); + assert_eq!(m.triangles[1..4], [[2, 1, 3], [2, 3, 4], [4, 3, 5]]); + assert_eq!(m.positions, work); + for (p, s) in m.positions.iter().zip(&source) { + let off = dot(sub(*p, *s), sub(*p, *s)).sqrt() / tol; + assert!(off < 0.87, "{off} tolerances off"); + } +} diff --git a/crates/prc/src/tess/tests.rs b/crates/prc/src/tess/tests.rs index 26219f286..253e1c9d5 100644 --- a/crates/prc/src/tess/tests.rs +++ b/crates/prc/src/tess/tests.rs @@ -529,12 +529,281 @@ fn a_compressed_mesh_is_read_to_its_end() { let schema = Schema::default(); let mut ctx = Ctx::new(BitReader::new(&bytes), &schema, v); let t = ctx.file_structure_tessellation().unwrap(); - assert!(matches!(t[..], [Tessellation::Compressed { triangles: 1, .. }, Tessellation::Mesh(_)]), "full={full} v={v}: {t:?}"); assert_eq!(ctx.r.position(), w.len(), "full={full} v={v}"); + assert!(matches!(t[1], Tessellation::Mesh(_)), "full={full} v={v}: {t:?}"); + // Stored normals and the one-status-per-triangle form are not rebuilt; the + // recalculated 3T seed is. + if full || !three_t { + assert!(matches!(t[0], Tessellation::Compressed { triangles: 1, .. }), "full={full} v={v}: {t:?}"); + } else { + let m = mesh(&t[0]); + assert_eq!((m.triangles.as_slice(), m.faces.as_slice()), ([[0, 1, 2]].as_slice(), std::slice::from_ref(&(0..1))), "v={v}"); + assert!(m.normals_recalculated && m.normals.is_empty()); + assert_eq!(m.triangle_styles, [TriangleStyle { style: 1, behaviour: 0 }]); + // Each point component is 1, in units of the 0.001 tolerance, from the origin 0. + let want = [0.001, 0.002, 0.0025]; + assert!(m.positions.iter().zip(want).all(|(p, c)| p.iter().all(|x| (x - c).abs() < 1e-12)), "{:?}", m.positions); + } } } } +/// A `TESS_3D_Compressed` (authoring version 8137, origin 0) whose normals are recalculated, +/// with `points` in units of `tolerance`, the 3T `status`, each triangle's face, the slots' +/// reference flags, the references and one line attribute per face; every other optional +/// branch absent. +struct Packed<'a> { + tolerance: f64, + points: &'a [i64], + status: &'a [u8], + face_of: &'a [u32], + /// The width of each face index; 8 unless an index needs more. + face_bits: u32, + is_ref: &'a [bool], + refs: &'a [u32], + line_attributes: &'a [u16], +} + +/// A `CompressedIndiceArray` [WD 11.9] of `bits`-wide deltas, `implicit` with no compressed +/// flag. +fn indices(w: &mut W, v: &[u32], implicit: bool, bits: u32) { + if !implicit { + w.bit(false); + } + w.uint(u32::try_from(v.len()).unwrap()); + for i in 0..v.len() { + w.put(if i == 0 { u64::from(bits) } else { 0 }, 8); + } + let mut prev = 0i64; + for &x in v { + let d = i64::from(x) - prev; + w.bit(d < 0).put(d.unsigned_abs(), bits - 1); + prev = i64::from(x); + } +} + +fn packed(w: &mut W, c: &Packed<'_>) { + w.uint(173).bit(false).bit(true).double(c.tolerance); + w.put(0, 32).put(0, 32).put(0, 32); + // point_array: 8-bit sign-magnitude integers. + w.bit(false).uint(u32::try_from(c.points.len()).unwrap()); + for _ in c.points { + w.put(8, 8); + } + for &p in c.points { + w.bit(p < 0).put(p.unsigned_abs(), 7); + } + w.bit(false).uint(u32::try_from(c.status.len()).unwrap()); + for &e in c.status { + w.put(u64::from(e), 8); + } + indices(w, c.face_of, false, c.face_bits); + w.uint(u32::try_from(c.is_ref.len()).unwrap()); + for &b in c.is_ref { + w.bit(b); + } + assert!(c.refs.len() <= 3, "more than three references are Huffman-coded"); + indices(w, c.refs, true, 8); + // must_recalculate_normals, normal_is_reversed, crease angle, flags; no colours, no + // multiple line attributes. + w.bit(true); + for _ in c.face_of { + w.bit(false); + } + w.double(0.5).put(0, 8).bit(false).bit(false); + w.bit(false).uint(u32::try_from(c.line_attributes.len()).unwrap()); + for &a in c.line_attributes { + w.put(u64::from(a & 0xff), 8).put(u64::from(a >> 8), 8); + } + // No texture, no behaviours. + w.bit(true).bit(false); +} + +/// A double-sided panel of two faces packed in walk order, its fold apex and its last two +/// apexes references: rebuilt into a mesh grouped by face, each triangle styled by its face. +#[test] +fn a_recalculated_compressed_mesh_is_rebuilt_by_face() { + let mut b = W::default(); + packed( + &mut b, + &Packed { + tolerance: 0.5, + points: &[0, 0, 0, 4, 0, 0, -2, 4, 0, 1, 3, 0], + status: &[3, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0], + face_of: &[1, 0, 1, 0], + face_bits: 8, + is_ref: &[false, false, false, false, true, true], + refs: &[0, 1], + line_attributes: &[3, 0], + }, + ); + let w = section(1, &b); + let bytes = w.bytes(); + let schema = Schema::default(); + let mut ctx = Ctx::new(BitReader::new(&bytes), &schema, 8137); + let t = ctx.file_structure_tessellation().unwrap(); + assert_eq!(ctx.r.position(), w.len()); + let m = mesh(&t[0]); + // Walk order [0 1 2] [2 1 3] [2 3 0] [0 3 1]; faces 1, 0, 1, 0. + assert_eq!(m.triangles, [[2, 1, 3], [0, 3, 1], [0, 1, 2], [2, 3, 0]]); + assert_eq!(m.faces, [0..2, 2..4]); + assert_eq!(m.positions[..3], [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0]]); + let style = |style| TriangleStyle { style, behaviour: 0 }; + assert_eq!(m.triangle_styles, [style(3), style(3), style(0), style(0)]); + assert!(m.normals_recalculated); +} + +/// Arrays the walk cannot fit stay a [`Tessellation::Compressed`], read to their end. +#[test] +fn a_compressed_mesh_that_does_not_fit_is_left_compressed() { + let mut b = W::default(); + // One point too many for a lone seed. + let c = Packed { + tolerance: 0.5, + points: &[0; 12], + status: &[0, 0, 0], + face_of: &[0], + face_bits: 8, + is_ref: &[false; 3], + refs: &[], + line_attributes: &[0], + }; + packed(&mut b, &c); + let w = section(1, &b); + let t = decode(&w, &Schema::default(), 8137).unwrap(); + assert!(matches!(t[..], [Tessellation::Compressed { triangles: 1, .. }]), "{t:?}"); +} + +/// A face index near `u32::MAX` claims four billion faces: once the triangles rebuild, they are +/// charged before any face range is made, so the decode stops at the element allowance instead +/// of allocating them. +#[test] +fn a_huge_face_index_is_charged_not_allocated() { + let mut b = W::default(); + let c = Packed { + tolerance: 0.5, + points: &[0; 9], + status: &[0, 0, 0], + face_of: &[u32::MAX - 1], + face_bits: 33, + is_ref: &[false; 3], + refs: &[], + line_attributes: &[], + }; + packed(&mut b, &c); + let r = decode(&section(1, &b), &Schema::default(), 8137); + assert!(matches!(r, Err(PrcError::TooManyElements { .. })), "{r:?}"); +} + +/// The same huge face index on arrays the walk cannot fit charges nothing for triangles or +/// faces: the tessellation stays compressed and the file reads on. +#[test] +fn arrays_that_do_not_fit_spend_no_triangles_or_faces() { + let mut b = W::default(); + let c = Packed { + tolerance: 0.5, + points: &[0; 12], + status: &[0, 0, 0], + face_of: &[u32::MAX - 1], + face_bits: 33, + is_ref: &[false; 3], + refs: &[], + line_attributes: &[], + }; + packed(&mut b, &c); + let t = decode(&section(1, &b), &Schema::default(), 8137).unwrap(); + assert!(matches!(t[..], [Tessellation::Compressed { triangles: 1, .. }]), "{t:?}"); +} + +/// The two-face panel of [`a_recalculated_compressed_mesh_is_rebuilt_by_face`], its second +/// reference `last_ref`. +fn panel(last_ref: u32) -> W { + let mut b = W::default(); + packed( + &mut b, + &Packed { + tolerance: 0.5, + points: &[0, 0, 0, 4, 0, 0, -2, 4, 0, 1, 3, 0], + status: &[3, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0], + face_of: &[1, 0, 1, 0], + face_bits: 8, + is_ref: &[false, false, false, false, true, true], + refs: &[0, last_ref], + line_attributes: &[3, 0], + }, + ); + section(1, &b) +} + +/// A rebuilt mesh is charged its triangles, each with its style, and each face range at its +/// size; the same arrays left compressed (a reference to a vertex not yet made) are charged +/// neither. +#[test] +fn a_rebuilt_compressed_mesh_is_charged_its_triangles_and_faces() { + let fits = panel(1); + let t = decode(&fits, &Schema::default(), 8137).unwrap(); + assert_eq!(mesh(&t[0]).triangles.len(), 4); + let left = panel(9); + let t = decode(&left, &Schema::default(), 8137).unwrap(); + assert!(matches!(t[..], [Tessellation::Compressed { triangles: 4, .. }]), "{t:?}"); + assert_eq!(spent(&fits) - spent(&left), 4 * triangle_elements(false, 0, true) + 2 * RANGE_ELEMENTS); + assert_eq!(triangle_elements(false, 0, true), 3); + #[cfg(target_pointer_width = "64")] + assert_eq!(RANGE_ELEMENTS, 2); +} + +/// A rebuild whose walk would outgrow the allowance left keeps the arrays compressed, even +/// when the rebuilt mesh alone would have fit, and the stream reads on. +#[test] +fn a_compressed_rebuild_is_bounded_by_the_allowance_left() { + let fits = panel(1); + let bytes = fits.bytes(); + let schema = Schema::default(); + let read = |n| Ctx::new(BitReader::with_elements(&bytes, n), &schema, 8137).file_structure_tessellation(); + let arrays = spent(&panel(9)); + let mesh_alone = spent(&fits) - arrays; + let t = read(arrays + mesh_alone).unwrap(); + assert!(matches!(t[..], [Tessellation::Compressed { triangles: 4, .. }]), "{t:?}"); + assert!(matches!(read(crate::MAX_DECODED_ELEMENTS).unwrap()[..], [Tessellation::Mesh(_)])); +} + +/// A face's nonzero behaviour styles its triangles even when its line attribute is 0 (the +/// owner's graphics); all zero, the faces give no styles. +#[test] +fn a_compressed_face_behaviour_alone_styles_its_triangles() { + let attributes = |behaviours: Vec<i32>| FaceAttributes { multi: Vec::new(), line_attributes: vec![0], behaviours }; + let a = attributes(vec![0x30]); + assert!(a.styled(1)); + assert_eq!(a.styles(&[0, 0], 1), [TriangleStyle { style: 0, behaviour: 0x30 }; 2]); + assert!(!attributes(vec![0]).styled(1)); + assert!(!attributes(Vec::new()).styled(1)); +} + +fn rebuilt(triangles: usize) -> compressed::Rebuilt { + compressed::Rebuilt { positions: vec![[0.0; 3]; 3], triangles: (0..triangles).map(|i| [0, 1, u32::try_from(i).unwrap()]).collect() } +} + +/// Triangles are grouped by face in walk order within each, faces no triangle names (between +/// and after) get empty ranges, and each style moves with its triangle. +#[test] +fn rebuilt_triangles_are_grouped_by_face_with_their_styles() { + let face_of = [2, 0, 2, 1, 0]; + let m = by_face(rebuilt(5), &face_of, 5, &[]); + let apex: Vec<u32> = m.triangles.iter().map(|t| t[2]).collect(); + assert_eq!(apex, [1, 4, 3, 0, 2]); + assert_eq!(m.faces, [0..2, 2..3, 3..5, 5..5, 5..5]); + assert!(m.triangle_styles.is_empty()); + assert!(m.normals_recalculated); + + let style = |style| TriangleStyle { style, behaviour: u16::try_from(style).unwrap() }; + let styles: Vec<TriangleStyle> = face_of.iter().map(|&f| style(f + 1)).collect(); + let m = by_face(rebuilt(5), &[2, 0, 2, 3, 0], 4, &styles); + let apex: Vec<u32> = m.triangles.iter().map(|t| t[2]).collect(); + assert_eq!(apex, [1, 4, 0, 2, 3]); + assert_eq!(m.faces, [0..2, 2..2, 2..4, 4..5]); + assert_eq!(m.triangle_styles, [style(1), style(1), style(3), style(3), style(2)]); +} + #[test] fn refusals_and_damage_are_errors() { // Edge statuses neither T nor 3T long. diff --git a/crates/prepress/src/lib.rs b/crates/prepress/src/lib.rs index 3fa4f472e..1afc7cf6f 100644 --- a/crates/prepress/src/lib.rs +++ b/crates/prepress/src/lib.rs @@ -12,6 +12,8 @@ pub mod flatten; pub mod ink; pub mod marks; pub mod output; +#[cfg(feature = "flatten")] +pub mod pdfx1a; pub mod plates; pub use cms::{CmsConversion, ProfileError}; diff --git a/crates/prepress/src/pdfx1a.rs b/crates/prepress/src/pdfx1a.rs new file mode 100644 index 000000000..92110166b --- /dev/null +++ b/crates/prepress/src/pdfx1a.rs @@ -0,0 +1,913 @@ +//! PDF/X-1a:2003: the PDF/X-4 print file flattened by craft-prepress (no transparency left; RGB +//! and ICC color converted into the output intent's CMYK; inks, overprint and live text kept), +//! written by krilla as PDF 1.4, given the PDF/X-1a identification and output intent, then +//! checked. Apps use [`flatten_x1a`] to flatten and finalize in one step, and [`check_pdfx1a`] +//! to inspect an existing file. + +use std::collections::{HashMap, HashSet}; + +use crate::flatten::pdf::ReadOptions; +use crate::flatten::{FlattenDocumentOptions, FlattenOptions, FlattenTotals, flatten_document}; +use craft_pdf::syntax::content::UntypedIter; +use craft_pdf::syntax::object::{Array, Dict, Name, Object, ObjectIdentifier, Stream}; +use craft_pdf::syntax::page::Resources; +use craft_pdf::write::backend::configure::PdfVersion; + +const MAX_DEPTH: usize = 16; + +/// `GTS_PDFXVersion` of PDF/X-1a:2003 (ISO 15930-4): the base level, PDF/X-1:2003. +const VERSION: &str = "PDF/X-1:2003"; + +/// `GTS_PDFXConformance` of PDF/X-1a:2003 (ISO 15930-4): with [`VERSION`], it names the +/// conformance level. +const CONFORMANCE: &str = "PDF/X-1a:2003"; + +/// `/RegistryName` of the ICC's registry of characterized printing conditions. An output intent +/// naming one of them needs no `/DestOutputProfile` in PDF/X. +const ICC_REGISTRY: &str = "http://www.color.org"; +const REGISTERED_CONDITIONS: &[&str] = &["FOGRA39"]; +/// Largest classic cross-reference size accepted by the public finalizer. The rewritten table +/// emits one entry per object number, so this is also an output-allocation bound. +const MAX_XREF_SIZE: usize = 1 << 20; + +/// The graphics placed on one output page, to name in errors: the page's name and the graphics' +/// names. +#[derive(Clone, Debug, Default)] +pub struct PageGraphics { + pub label: String, + pub graphics: Vec<String>, +} + +/// The PDF/X-1a file for `pdf`, the PDF/X-4 print file: flattened at `dpi`, written at PDF 1.4, +/// identified, checked. `pages` names each output page and its graphics for errors. Fails when +/// the flattener fails or leaves an image out, when the output intent's profile can't go into a +/// PDF 1.4 file, or when the result still has transparency or color outside DeviceCMYK, +/// DeviceGray, Separation and DeviceN; other check findings become warnings. +pub fn flatten_x1a(pdf: &[u8], dpi: f32, pages: &[PageGraphics]) -> Result<(Vec<u8>, Vec<String>), String> { + let dpi = if dpi.is_finite() { dpi.clamp(36.0, 2400.0) } else { 300.0 }; + let opts = FlattenDocumentOptions { + read: ReadOptions { raster_dpi: dpi, ..ReadOptions::default() }, + flatten: FlattenOptions { raster_dpi: dpi, ..FlattenOptions::default() }, + producer: "DesignCraft".into(), + version: PdfVersion::Pdf14, + pdfx_version: Some(VERSION.into()), + ..FlattenDocumentOptions::default() + }; + let (bytes, report) = flatten_document(pdf, &opts).map_err(|e| format!("PDF/X-1a: the transparency flattener failed: {e}"))?; + let unread: Vec<String> = report + .pages + .iter() + .filter(|(_, r)| r.read.unreadable_images > 0) + .map(|(page, r)| { + let n = r.read.unreadable_images; + let images = if n == 1 { "1 image".to_string() } else { format!("{n} images") }; + let fallback = PageGraphics { label: page.saturating_add(1).to_string(), graphics: Vec::new() }; + let at = pages.get(*page).unwrap_or(&fallback); + let names: Vec<String> = at.graphics.iter().take(5).map(|g| format!("`{g}`")).collect(); + let more = if at.graphics.len() > 5 { ", …" } else { "" }; + let placed = if names.is_empty() { String::new() } else { format!(" (graphics on it: {}{more})", names.join(", ")) }; + format!("{images} on page {}{placed}", at.label) + }) + .collect(); + if !unread.is_empty() { + return Err(format!( + "PDF/X-1a: the transparency flattener couldn't read {}, and a PDF/X file can't leave images out: replace the graphic, or export without PDF/X-1a", + unread.join("; ") + )); + } + let mut warnings = flatten_warnings(&report.totals, dpi); + let bytes = finish_x1a(&bytes)?; + let (fatal, other) = checks(&bytes); + if !fatal.is_empty() { + return Err(format!("PDF/X-1a: after flattening, {}", fatal.join("; "))); + } + warnings.extend(other.into_iter().map(|issue| format!("PDF/X-1a: {issue}"))); + Ok((bytes, warnings)) +} + +/// What the flattener's `t` (at `dpi`) tells the user: rasterized transparency, and spot inks past +/// the ink set's capacity, whose tints the flattener drops. +pub fn flatten_warnings(t: &FlattenTotals, dpi: f32) -> Vec<String> { + let mut out = Vec::new(); + if t.complex_regions > 0 || t.complex_groups > 0 { + let at = t.lowest_dpi.map(|d| format!(", some below {dpi:.0} ppi (lowest {d:.0} ppi)")).unwrap_or_default(); + out.push(format!("PDF/X-1a: transparency flattened: {} region(s) rasterized at {dpi:.0} ppi{at}", t.complex_regions + t.complex_groups)); + } + if t.dropped_inks > 0 { + out.push(format!( + "PDF/X-1a: the document has more spot inks than the flattener can separate: {} tint(s) in the inks past its limit were dropped and won't print", + t.dropped_inks + )); + } + out +} + +/// PDF/X-1a:2003 checks on an exported file (empty = passes them): PDF 1.4 or lower, the +/// identification (`GTS_PDFXVersion` and `GTS_PDFXConformance`), a CMYK `GTS_PDFX` output intent +/// whose profile, when it has one, is ICC v2 (and without one, names a registered printing +/// condition), `/Trapped` True or False, trim boxes, no encryption or interpolation; no +/// transparency (soft masks, transparency groups, constant opacity below 1, blend modes other +/// than Normal); only DeviceCMYK, DeviceGray, Separation and DeviceN (and Indexed and Pattern +/// spaces over them), a spot's alternate space process; every font embedded. +pub fn check_pdfx1a(pdf: &[u8]) -> Vec<String> { + let (mut issues, other) = checks(pdf); + issues.extend(other); + issues +} + +/// [`check_pdfx1a`]'s findings: transparency and color spaces first, then the rest. +fn checks(pdf: &[u8]) -> (Vec<String>, Vec<String>) { + let mut issues = Vec::new(); + let file = craft_pdf::syntax::Pdf::new(pdf.to_vec()).ok(); + if !pdf.starts_with(b"%PDF-1.") || pdf.get(7).is_none_or(|v| *v > b'4') { + issues.push("the PDF version must be 1.4 or lower".into()); + } + if file.as_ref().is_none_or(|f| pdfx_intents(f).is_empty()) { + issues.push("no PDF/X output intent".into()); + } + let info = |key: &[u8]| file.as_ref().and_then(|f| info_text(f, key)); + if info(b"GTS_PDFXVersion").as_deref() != Some(VERSION) { + issues.push(format!("the document information doesn't name {VERSION}")); + } + if info(b"GTS_PDFXConformance").as_deref() != Some(CONFORMANCE) { + issues.push(format!("the document information doesn't name the conformance level {CONFORMANCE}")); + } + let trapped = file.as_ref().and_then(|f| f.info()).and_then(|info| info.get::<Name<'_>>(b"Trapped")); + if !trapped.as_ref().is_some_and(|value| matches!(value.as_ref(), b"False" | b"True")) { + issues.push("the document information needs /Trapped True or False".into()); + } + if file.as_ref().is_some_and(|f| f.is_encrypted()) { + issues.push("the file is encrypted".into()); + } + if let Some(file) = file.as_ref() { + for (index, page) in file.pages().iter().enumerate() { + let raw = page.raw(); + let trim = raw.contains_key(b"TrimBox"); + let art = raw.contains_key(b"ArtBox"); + if trim == art { + issues.push(format!("page {} needs either a trim box or an art box, but not both", index + 1)); + } + } + } + let (content, fonts, scan_issues) = content(file.as_ref()); + issues.extend(fonts); + issues.extend(scan_issues); + (content, issues) +} + +/// Transparency and color spaces, then the output intent and fonts, walked through every page's +/// content and what it uses. +fn content(file: Option<&craft_pdf::syntax::Pdf>) -> (Vec<String>, Vec<String>, Vec<String>) { + let Some(file) = file else { + return (vec!["the file couldn't be read to check its transparency and color spaces".into()], Vec::new(), Vec::new()); + }; + let mut fonts = intent_issues(file); + let mut found: Vec<(String, Vec<usize>)> = Vec::new(); + let mut font_found: Vec<(String, Vec<usize>)> = Vec::new(); + let mut scan_found: Vec<(String, Vec<usize>)> = Vec::new(); + for (i, page) in file.pages().iter().enumerate() { + let mut scan = Scan::default(); + let res = page.resources(); + if let Some(group) = page.raw().get::<Dict<'_>>(b"Group") { + scan.group(&group); + } + if let Some(content) = page.page_stream() { + scan.content(content, res, 0); + } + for (list, items) in [(&mut found, scan.found), (&mut font_found, scan.font_issues), (&mut scan_found, scan.other_issues)] { + for what in items { + match list.iter_mut().find(|(w, _)| *w == what) { + Some((_, pages)) => pages.push(i + 1), + None => list.push((what, vec![i + 1])), + } + } + } + } + let on_pages = |(what, pages): (String, Vec<usize>)| { + let list: Vec<String> = pages.iter().take(10).map(|p| p.to_string()).collect(); + let more = if pages.len() > 10 { ", …" } else { "" }; + let s = if pages.len() == 1 { "" } else { "s" }; + format!("{what} on page{s} {}{more}", list.join(", ")) + }; + fonts.extend(font_found.into_iter().map(on_pages)); + (found.into_iter().map(on_pages).collect(), fonts, scan_found.into_iter().map(on_pages).collect()) +} + +/// A `GTS_PDFX` output intent, as PDF/X-1a judges it. +struct Intent { + /// Its object number, when it is an indirect object. + obj: Option<usize>, + /// `/OutputCondition`, else `/OutputConditionIdentifier`, for messages. + name: String, + /// An `/OutputConditionIdentifier` other than `Custom` in the ICC registry. + registered: bool, + /// Whether it has a `/DestOutputProfile`, and the profile's object number. + has_profile: bool, + profile_obj: Option<usize>, + /// The profile's `/N` and decoded bytes. + channels: Option<i32>, + profile: Option<Vec<u8>>, +} + +impl Intent { + /// The profile's ICC major version (byte 8 of its header). + fn major(&self) -> Option<u8> { + self.profile.as_deref()?.get(8).copied() + } + + /// "ICC v4", or what keeps the version from being read. + fn version(&self) -> String { + self.major().map_or_else(|| "unreadable".to_string(), |v| format!("ICC v{v}")) + } +} + +/// The catalog's `GTS_PDFX` output intents. +fn pdfx_intents(file: &craft_pdf::syntax::Pdf) -> Vec<Intent> { + let number = |n: i32| usize::try_from(n).ok(); + raw_pdfx_intents(file) + .into_iter() + .map(|oi| { + let text = |key: &[u8]| { + oi.get::<craft_pdf::syntax::object::String<'_>>(key) + .map(|s| String::from_utf8_lossy(s.as_bytes()).trim().to_string()) + .filter(|s| !s.is_empty()) + }; + let identifier = text(b"OutputConditionIdentifier"); + let registry = text(b"RegistryName"); + let profile = oi.get::<Stream<'_>>(b"DestOutputProfile"); + Intent { + obj: oi.obj_id().and_then(|id| number(id.obj_number)), + name: text(b"OutputCondition").or_else(|| identifier.clone()).unwrap_or_else(|| "?".into()), + registered: registry.is_some_and(|r| r.trim_end_matches('/') == ICC_REGISTRY) + && identifier.as_deref().is_some_and(|identifier| REGISTERED_CONDITIONS.contains(&identifier)), + has_profile: oi.contains_key(b"DestOutputProfile"), + profile_obj: oi.get_ref(b"DestOutputProfile").and_then(|r| number(r.obj_number)), + channels: profile.as_ref().and_then(|p| p.dict().get::<i32>(b"N")), + profile: profile.and_then(|p| p.decoded().ok()).map(|b| b.into_owned()), + } + }) + .collect() +} + +fn raw_pdfx_intents<'a>(file: &'a craft_pdf::syntax::Pdf) -> Vec<Dict<'a>> { + let xref = file.xref(); + let Some(catalog) = xref.get::<Dict<'_>>(xref.root_id()) else { return Vec::new() }; + let Some(intents) = catalog.get::<Array<'_>>(b"OutputIntents") else { return Vec::new() }; + intents.iter::<Dict<'_>>().filter(|oi| oi.get::<Name<'_>>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX")).collect() +} + +fn info_text(file: &craft_pdf::syntax::Pdf, key: &[u8]) -> Option<String> { + file.info()?.get::<craft_pdf::syntax::object::String<'_>>(key).map(|s| String::from_utf8_lossy(s.as_bytes()).trim().to_string()) +} + +/// What PDF/X-1a finds wrong with the file's output intent: a CMYK profile, ICC v2 (PDF 1.4 +/// allows no later version), or none for a registered printing condition. +fn intent_issues(file: &craft_pdf::syntax::Pdf) -> Vec<String> { + let Some(oi) = pdfx_intents(file).into_iter().next() else { return Vec::new() }; + let mut issues = Vec::new(); + if oi.has_profile { + if oi.channels != Some(4) { + issues.push("the output intent has no CMYK destination profile".into()); + } + if oi.major() != Some(2) { + issues.push(format!("the output intent's profile is {}, and PDF/X-1a (PDF 1.4) allows only ICC v2 profiles", oi.version())); + } + } else if !oi.registered { + issues + .push(format!("the output intent has no destination profile and doesn't name a printing condition in the ICC registry ({ICC_REGISTRY})")); + } + issues +} + +/// krilla's PDF 1.4 file with what PDF/X-1a needs and krilla doesn't write, rewritten as one +/// revision: `GTS_PDFXConformance` in the document information and the XMP, and the output intent +/// of a registered printing condition without `/DestOutputProfile` (its profile is left out of +/// the file). An unregistered condition keeps its profile, which must then be ICC v2. +pub fn finish_x1a(pdf: &[u8]) -> Result<Vec<u8>, String> { + let unreadable = || "the flattened file couldn't be read to add the PDF/X-1a identification".to_string(); + let layout = Layout::read(pdf).ok_or_else(unreadable)?; + let file = craft_pdf::syntax::Pdf::new(pdf.to_vec()).map_err(|_| unreadable())?; + let mut bodies: HashMap<usize, Vec<u8>> = HashMap::new(); + let info = file.info().and_then(|info| info.obj_id()).and_then(|id| usize::try_from(id.obj_number).ok()).ok_or_else(unreadable)?; + let body = layout.body(pdf, info).ok_or_else(unreadable)?; + let (head, close) = body.split_at_checked(rfind(body, b">>").ok_or_else(unreadable)?).ok_or_else(unreadable)?; + bodies.insert(info, [head, format!("/GTS_PDFXConformance({CONFORMANCE})").as_bytes(), close].concat()); + let xref = file.xref(); + if let Some(meta) = xref.get::<Dict<'_>>(xref.root_id()).and_then(|c| c.get_ref(b"Metadata")).and_then(|r| usize::try_from(r.obj_number).ok()) + && let Some(xmp) = layout.body(pdf, meta).and_then(xmp_with_conformance) + { + bodies.insert(meta, xmp); + } + let mut stripped: Vec<usize> = Vec::new(); + for oi in pdfx_intents(&file) { + if !oi.has_profile { + continue; + } + if !oi.registered { + if oi.major() != Some(2) { + return Err(format!( + "the output intent's profile `{}` is {}, and PDF/X-1a (PDF 1.4) allows only ICC v2 profiles: choose a CMYK working space with an ICC v2 profile, or Coated FOGRA39", + oi.name, + oi.version() + )); + } + continue; + } + let (Some(obj), Some(profile)) = (oi.obj, oi.profile_obj) else { return Err(unreadable()) }; + let body = match bodies.get(&obj) { + Some(b) => b.clone(), + None => layout.body(pdf, obj).ok_or_else(unreadable)?.to_vec(), + }; + let key = format!("/DestOutputProfile {profile} 0 R"); + let at = find(&body, key.as_bytes(), 0).ok_or_else(unreadable)?; + let (before, rest) = body.split_at_checked(at).ok_or_else(unreadable)?; + let after = rest.get(key.len()..).ok_or_else(unreadable)?; + bodies.insert(obj, [before, after].concat()); + stripped.push(profile); + } + // A profile only the stripped intents named goes too. + let dropped: HashSet<usize> = stripped.iter().copied().filter(|p| references(pdf, *p) == stripped.iter().filter(|q| *q == p).count()).collect(); + layout.write(pdf, &bodies, &dropped).ok_or_else(unreadable) +} + +/// How often `n 0 R` appears in `pdf` (a stream that happens to hold those bytes counts too, which +/// only ever keeps an object). +fn references(pdf: &[u8], n: usize) -> usize { + let needle = format!("{n} 0 R"); + let mut count = 0; + let mut from = 0; + while let Some(at) = find(pdf, needle.as_bytes(), from) { + let before = at.checked_sub(1).and_then(|i| pdf.get(i)).is_none_or(|c| !c.is_ascii_digit()); + let after = pdf.get(at + needle.len()).is_none_or(|c| !c.is_ascii_alphanumeric()); + if before && after { + count += 1; + } + from = at + needle.len(); + } + count +} + +/// The body of an uncompressed XMP metadata stream object with the Adobe `pdfx` properties of +/// the identification (`GTS_PDFXVersion`, `GTS_PDFXConformance`) added and its `/Length` updated; +/// `None` when the stream is filtered or isn't XMP. +fn xmp_with_conformance(body: &[u8]) -> Option<Vec<u8>> { + let s0 = find(body, b"stream", 0)?; + let dict = String::from_utf8_lossy(body.get(..s0)?).to_string(); + let s0 = s0 + b"stream".len(); + let s0 = s0 + body.get(s0..)?.iter().take_while(|c| **c == b'\r' || **c == b'\n').count(); + let s1 = rfind(body, b"endstream")?; + let xml = String::from_utf8_lossy(body.get(s0..s1)?).trim_end().to_string(); + if dict.contains("/Filter") || !xml.contains("</rdf:RDF>") { + return None; + } + let ids = format!( + "<rdf:Description rdf:about=\"\" xmlns:pdfx=\"http://ns.adobe.com/pdfx/1.3/\"><pdfx:GTS_PDFXVersion>{VERSION}</pdfx:GTS_PDFXVersion>\ + <pdfx:GTS_PDFXConformance>{CONFORMANCE}</pdfx:GTS_PDFXConformance></rdf:Description>" + ); + let xml = xml.replacen("</rdf:RDF>", &format!("{ids}</rdf:RDF>"), 1); + let i = dict.find("/Length")?; + let rest = dict.get(i + 7..)?.trim_start(); + let end = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len()); + let dict = format!("{}/Length {}{}", dict.get(..i)?, xml.len(), rest.get(end..)?); + Some(format!("\n{}\nstream\n{xml}\nendstream\n", dict.trim()).into_bytes()) +} + +fn find(bytes: &[u8], needle: &[u8], from: usize) -> Option<usize> { + (from <= bytes.len()).then(|| bytes.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|at| at + from))? +} + +fn rfind(bytes: &[u8], needle: &[u8]) -> Option<usize> { + bytes.windows(needle.len()).rposition(|w| w == needle) +} + +fn int_after(text: &str, key: &str) -> Option<usize> { + let at = text.find(key)? + key.len(); + text.get(at..)?.trim_start().split(|c: char| !c.is_ascii_digit()).next()?.parse().ok() +} + +/// Where the objects of a single-revision file with a classic cross-reference table are. +struct Layout { + /// (object number, start, end), by start: from `n 0 obj` up to the next object or the table. + objects: Vec<(usize, usize, usize)>, + /// Where the cross-reference table starts. + table: usize, + /// The trailer dictionary. + trailer: String, + size: usize, +} + +impl Layout { + fn read(pdf: &[u8]) -> Option<Layout> { + let sx = rfind(pdf, b"startxref")?; + let table: usize = std::str::from_utf8(pdf.get(sx + b"startxref".len()..)?).ok()?.split_whitespace().next()?.parse().ok()?; + let section = pdf.get(table..sx)?; + let t = find(section, b"trailer", 0)?; + let trailer = String::from_utf8_lossy(section.get(t + b"trailer".len()..)?).trim().to_string(); + if trailer.contains("/Prev") || trailer.contains("/XRefStm") { + return None; + } + let size = int_after(&trailer, "/Size")?; + if size > MAX_XREF_SIZE { + return None; + } + let mut tokens = std::str::from_utf8(section.get(..t)?).ok()?.split_whitespace(); + if tokens.next()? != "xref" { + return None; + } + let mut starts: Vec<(usize, usize)> = Vec::new(); + let mut seen = HashSet::new(); + while let Some(first) = tokens.next() { + let first: usize = first.parse().ok()?; + let count: usize = tokens.next()?.parse().ok()?; + for i in 0..count { + let (offset, generation, kind) = (tokens.next()?, tokens.next()?, tokens.next()?); + if kind != "n" { + continue; + } + let n = first.checked_add(i)?; + let offset: usize = offset.parse().ok()?; + if generation != "00000" || offset >= table || n >= size || !seen.insert(n) { + return None; + } + starts.push((n, offset)); + } + } + // Free entries past the objects would only make the rewritten table longer. + let max = starts.iter().map(|(n, _)| *n).max().unwrap_or(0); + if size > max.saturating_mul(2).saturating_add(16) { + return None; + } + starts.sort_by_key(|(_, offset)| *offset); + let mut objects = Vec::with_capacity(starts.len()); + for (i, &(n, start)) in starts.iter().enumerate() { + let end = starts.get(i + 1).map_or(table, |(_, s)| *s); + if !pdf.get(start..end)?.starts_with(format!("{n} 0 obj").as_bytes()) { + return None; + } + objects.push((n, start, end)); + } + Some(Layout { objects, table, trailer, size }) + } + + /// Object `n` between `n 0 obj` and `endobj`. + fn body<'p>(&self, pdf: &'p [u8], n: usize) -> Option<&'p [u8]> { + let &(_, start, end) = self.objects.iter().find(|(m, _, _)| *m == n)?; + let obj = pdf.get(start..end)?; + obj.get(format!("{n} 0 obj").len()..rfind(obj, b"endobj")?) + } + + /// The file with the objects in `bodies` replaced and those in `dropped` left out, and a new + /// cross-reference table. + fn write(&self, pdf: &[u8], bodies: &HashMap<usize, Vec<u8>>, dropped: &HashSet<usize>) -> Option<Vec<u8>> { + let first = self.objects.first().map_or(self.table, |o| o.1); + let mut out = pdf.get(..first)?.to_vec(); + let mut offsets = HashMap::new(); + for &(n, start, end) in &self.objects { + if dropped.contains(&n) { + continue; + } + offsets.insert(n, out.len()); + match bodies.get(&n) { + Some(body) => { + out.extend_from_slice(format!("{n} 0 obj").as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"endobj\n"); + } + None => out.extend_from_slice(pdf.get(start..end)?), + } + } + if !out.ends_with(b"\n") { + out.push(b'\n'); + } + let table = out.len(); + // The free entries, each pointing at the next. + let free: Vec<usize> = (1..self.size).filter(|n| !offsets.contains_key(n)).collect(); + let next: HashMap<usize, usize> = free.iter().copied().zip(free.iter().skip(1).copied().chain([0])).collect(); + out.extend_from_slice(format!("xref\n0 {}\n{:010} 65535 f\r\n", self.size, free.first().copied().unwrap_or(0)).as_bytes()); + for n in 1..self.size { + let next = next.get(&n).copied().unwrap_or(0); + let entry = match offsets.get(&n) { + Some(offset) => format!("{offset:010} 00000 n\r\n"), + // A dropped object's number could be used again, at the next generation. + None if dropped.contains(&n) => format!("{next:010} 00001 f\r\n"), + None => format!("{next:010} 65535 f\r\n"), + }; + out.extend_from_slice(entry.as_bytes()); + } + out.extend_from_slice(format!("trailer\n{}\nstartxref\n{table}\n%%EOF\n", self.trailer).as_bytes()); + Some(out) + } +} + +/// Why a color space isn't allowed in PDF/X-1a, or `None` when it is. +fn disallowed(cs: &Object<'_>, res: &Resources<'_>, depth: usize) -> Option<String> { + if depth > 4 { + return Some("a color space nested too deeply".into()); + } + match cs { + Object::Name(n) => match n.as_ref() { + b"DeviceCMYK" | b"CMYK" | b"DeviceGray" | b"G" | b"Pattern" => None, + b"DeviceRGB" | b"RGB" => Some("DeviceRGB color".into()), + b"Indexed" | b"I" => None, + other => match res.get_color_space(&Name::new_unescaped(other)) { + Some(named) if !matches!(named, Object::Name(_)) => disallowed(&named, res, depth + 1), + Some(Object::Name(m)) if m.as_ref() != other => disallowed(&Object::Name(m), res, depth + 1), + _ => Some(format!("the color space /{}", String::from_utf8_lossy(other))), + }, + }, + Object::Array(a) => { + let mut items = a.iter::<Object<'_>>(); + let family = match items.next() { + Some(Object::Name(n)) => n, + _ => return Some("an unreadable color space".into()), + }; + match family.as_ref() { + b"ICCBased" => Some("ICC-based color".into()), + b"CalRGB" | b"CalGray" => Some("CIE-based (CalRGB/CalGray) color".into()), + b"Lab" => Some("Lab color".into()), + b"DeviceRGB" | b"RGB" => Some("DeviceRGB color".into()), + b"DeviceCMYK" | b"CMYK" | b"DeviceGray" | b"G" => None, + b"Indexed" | b"I" => items.next().and_then(|base| disallowed(&base, res, depth + 1)), + b"Pattern" => items.next().and_then(|base| disallowed(&base, res, depth + 1)), + b"Separation" | b"DeviceN" => { + let _names = items.next(); + let alt = items.next()?; + if !is_process_space(&alt, res, depth + 1) { + return Some("a spot color whose alternate space isn't a CMYK or gray process space".into()); + } + let _tint = items.next(); + // NChannel attributes are PDF 1.6, past the 1.4 that PDF/X-1a:2003 allows. + let attrs = items.next().and_then(|o| match o { + Object::Dict(d) => Some(d), + _ => None, + }); + attrs + .filter(|a| a.get::<Name<'_>>(b"Subtype").is_some_and(|n| n.as_ref() == b"NChannel") || a.contains_key(b"Process")) + .map(|_| "a DeviceN space with NChannel attributes (PDF 1.6)".into()) + } + other => Some(format!("the color space /{}", String::from_utf8_lossy(other))), + } + } + _ => Some("an unreadable color space".into()), + } +} + +fn is_process_space(cs: &Object<'_>, res: &Resources<'_>, depth: usize) -> bool { + if depth > 4 { + return false; + } + match cs { + Object::Name(name) => match name.as_ref() { + b"DeviceCMYK" | b"CMYK" | b"DeviceGray" | b"G" => true, + other => match res.get_color_space(&Name::new_unescaped(other)) { + Some(Object::Name(alias)) if alias.as_ref() != other => is_process_space(&Object::Name(alias), res, depth + 1), + Some(named) if !matches!(named, Object::Name(_)) => is_process_space(&named, res, depth + 1), + _ => false, + }, + }, + Object::Array(array) => { + array.iter::<Name<'_>>().next().is_some_and(|family| matches!(family.as_ref(), b"DeviceCMYK" | b"CMYK" | b"DeviceGray" | b"G")) + } + _ => false, + } +} + +/// What one page has that PDF/X-1a doesn't allow, in the order found. +#[derive(Default)] +struct Scan { + /// What was found, in the order found; `known` is the same as a set. + found: Vec<String>, + known: HashSet<String>, + font_issues: Vec<String>, + other_issues: Vec<String>, + seen: HashSet<ObjectIdentifier>, + fonts: HashSet<ObjectIdentifier>, +} + +impl Scan { + fn add(&mut self, what: String) { + if self.known.insert(what.clone()) { + self.found.push(what); + } + } + + fn space(&mut self, cs: &Object<'_>, res: &Resources<'_>) { + if let Some(why) = disallowed(cs, res, 0) { + self.add(why); + } + } + + fn content(&mut self, data: &[u8], res: &Resources<'_>, depth: usize) { + if depth > MAX_DEPTH { + self.add("content was not fully checked because nested resources exceed the scan limit".into()); + return; + } + let mut ops = UntypedIter::new(data); + while let Some(op) = ops.next() { + let operator: &[u8] = op.operator; + let last = op.operands().last().cloned(); + let name = || last.clone().and_then(Object::into_name); + match operator { + b"rg" | b"RG" => self.add("DeviceRGB color".into()), + b"cs" | b"CS" => { + if let Some(n) = name() { + self.space(&Object::Name(n), res); + } + } + b"sh" => { + if let Some(sh) = name().and_then(|n| res.get_shading(&n)) { + self.shading(sh, res); + } + } + b"scn" | b"SCN" => { + if let Some(p) = name().and_then(|n| res.get_pattern(&n)) { + self.pattern(p, res, depth); + } + } + b"gs" => { + if let Some(gs) = name().and_then(|n| res.get_ext_g_state(&n)) { + self.ext_g_state(&gs, res, depth); + } + } + b"Tf" => { + let font = op.operands().next().cloned().and_then(Object::into_name).and_then(|n| res.get_font(&n)); + if let Some(font) = font { + self.font(&font, res, depth); + } + } + b"Do" => { + if let Some(xo) = name().and_then(|n| res.get_x_object(&n)) { + match xo.dict().get::<Name<'_>>(b"Subtype").as_deref() { + Some(b"Image") => self.image(&xo, res), + Some(b"Form") => self.form(&xo, res, depth), + _ => {} + } + } + } + b"BI" | b"EI" => { + if let Some(Object::Stream(img)) = last { + let dict = img.dict(); + if let Some(cs) = dict.get::<Object<'_>>(b"CS").or_else(|| dict.get::<Object<'_>>(b"ColorSpace")) { + self.space(&cs, res); + } + self.interpolation(dict); + } + } + _ => {} + } + } + } + + fn ext_g_state(&mut self, gs: &Dict<'_>, res: &Resources<'_>, depth: usize) { + match gs.get::<Object<'_>>(b"SMask") { + None => {} + Some(Object::Name(n)) if n.as_ref() == b"None" => {} + Some(mask) => { + self.add("a soft mask (transparency)".into()); + if let Some(form) = match mask { + Object::Dict(d) => d.get::<Stream<'_>>(b"G"), + _ => None, + } { + self.form(&form, res, depth); + } + } + } + for key in [&b"CA"[..], b"ca"] { + if gs.get::<f32>(key).is_some_and(|a| a < 1.0) { + self.add("constant opacity below 100% (transparency)".into()); + } + } + let normal = |n: &[u8]| matches!(n, b"Normal" | b"Compatible"); + match gs.get::<Object<'_>>(b"BM") { + Some(Object::Name(n)) if !normal(n.as_ref()) => { + self.add(format!("the blend mode /{} (transparency)", String::from_utf8_lossy(n.as_ref()))) + } + Some(Object::Array(a)) if a.iter::<Name<'_>>().any(|n| !normal(n.as_ref())) => { + self.add("a blend mode other than Normal (transparency)".into()) + } + _ => {} + } + } + + fn image(&mut self, img: &Stream<'_>, res: &Resources<'_>) { + if !self.seen.insert(img.obj_id()) { + return; + } + let d = img.dict(); + self.interpolation(d); + if d.get::<Object<'_>>(b"SMask").is_some() { + self.add(format!("an image with a soft mask (object {}, transparency)", img.obj_id().obj_number)); + } + if d.get::<i32>(b"SMaskInData").is_some_and(|v| v != 0) { + self.add(format!("an image with transparency in its data (object {})", img.obj_id().obj_number)); + } + if d.get::<bool>(b"ImageMask") == Some(true) { + return; + } + match d.get::<Object<'_>>(b"ColorSpace") { + Some(cs) => { + if let Some(why) = disallowed(&cs, res, 0) { + let (w, h) = (d.get::<i32>(b"Width").unwrap_or(0), d.get::<i32>(b"Height").unwrap_or(0)); + self.add(format!("{why} in an image (object {}, {w} × {h} px)", img.obj_id().obj_number)); + } + } + // JPX images may carry their own space; X-1a doesn't allow them. + None => self.add(format!("an image without a color space (object {})", img.obj_id().obj_number)), + } + } + + fn interpolation(&mut self, dict: &Dict<'_>) { + if dict.get::<bool>(b"Interpolate") == Some(true) { + let message = "an image asks for interpolation".to_string(); + if !self.other_issues.contains(&message) { + self.other_issues.push(message); + } + } + } + + fn form(&mut self, form: &Stream<'_>, parent: &Resources<'_>, depth: usize) { + if depth >= MAX_DEPTH { + self.add("content was not fully checked because nested forms exceed the scan limit".into()); + return; + } + if !self.seen.insert(form.obj_id()) { + return; + } + let res = Resources::from_parent(form.dict().get::<Dict<'_>>(b"Resources").unwrap_or_default(), parent.clone()); + if let Some(group) = form.dict().get::<Dict<'_>>(b"Group") { + self.group(&group); + } + match form.decoded() { + Ok(data) => self.content(&data, &res, depth + 1), + Err(_) => self.add(format!("a form XObject could not be decoded (object {})", form.obj_id().obj_number)), + } + } + + fn group(&mut self, group: &Dict<'_>) { + if group.get::<Name<'_>>(b"S").is_some_and(|s| s.as_ref() == b"Transparency") { + self.add("a transparency group".into()); + } + } + + fn shading(&mut self, sh: Object<'_>, res: &Resources<'_>) { + let dict = match sh { + Object::Dict(d) => d, + Object::Stream(s) => s.dict().clone(), + _ => return, + }; + if let Some(cs) = dict.get::<Object<'_>>(b"ColorSpace") { + self.space(&cs, res); + } + } + + fn pattern(&mut self, p: Object<'_>, res: &Resources<'_>, depth: usize) { + match p { + Object::Dict(d) => { + if let Some(sh) = d.get::<Object<'_>>(b"Shading") { + self.shading(sh, res); + } + if let Some(gs) = d.get::<Dict<'_>>(b"ExtGState") { + self.ext_g_state(&gs, res, depth); + } + } + Object::Stream(s) => self.form(&s, res, depth), + _ => {} + } + } + + /// Embedded: a simple font's descriptor, or a Type 0 font's descendant's, has a font file. A + /// Type 3 font's glyphs are content streams in the file, scanned like the page's. + fn font(&mut self, font: &Dict<'_>, parent: &Resources<'_>, depth: usize) { + if let Some(id) = font.obj_id() + && !self.fonts.insert(id) + { + return; + } + let name = font.get::<Name<'_>>(b"BaseFont").map(|n| String::from_utf8_lossy(n.as_ref()).to_string()).unwrap_or_else(|| "?".into()); + let subtype = font.get::<Name<'_>>(b"Subtype"); + let descriptor = match subtype.as_deref() { + Some(b"Type3") => return self.type3(font, parent, depth), + Some(b"Type0") => { + font.get::<Array<'_>>(b"DescendantFonts").and_then(|a| a.iter::<Dict<'_>>().next()).and_then(|d| d.get::<Dict<'_>>(b"FontDescriptor")) + } + _ => font.get::<Dict<'_>>(b"FontDescriptor"), + }; + let embedded = descriptor.is_some_and(|d| [&b"FontFile"[..], b"FontFile2", b"FontFile3"].iter().any(|k| d.get::<Stream<'_>>(k).is_some())); + if !embedded { + self.font_issues.push(format!("the font {name} isn't embedded")); + } + } + + /// A Type 3 font's glyph procedures, with the font's resources over `parent`'s. + fn type3(&mut self, font: &Dict<'_>, parent: &Resources<'_>, depth: usize) { + if depth >= MAX_DEPTH { + self.add("content was not fully checked because nested Type 3 glyphs exceed the scan limit".into()); + return; + } + let res = Resources::from_parent(font.get::<Dict<'_>>(b"Resources").unwrap_or_default(), parent.clone()); + let Some(procs) = font.get::<Dict<'_>>(b"CharProcs") else { return }; + for key in procs.keys() { + if let Some(glyph) = procs.get::<Stream<'_>>(key.as_ref()) + && self.seen.insert(glyph.obj_id()) + { + match glyph.decoded() { + Ok(data) => self.content(&data, &res, depth + 1), + Err(_) => self.add(format!("a Type 3 glyph stream could not be decoded (object {})", glyph.obj_id().obj_number)), + } + } + } + } +} + +#[cfg(test)] +mod review_regressions { + use super::{Layout, check_pdfx1a, finish_x1a}; + fn pdf(page_boxes: &str, info: &str, content: &[u8], extra: &[(&str, &str)]) -> Vec<u8> { + let mut objects = vec![ + b"<< /Type /Catalog /Pages 2 0 R /OutputIntents [3 0 R] >>".to_vec(), + b"<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_vec(), + b"<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (FOGRA39) /RegistryName (http://www.color.org) >>".to_vec(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] {page_boxes} /Resources <<>> /Contents 5 0 R >>").into_bytes(), + [format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content, b"\nendstream"].concat(), + format!("<< {info} >>").into_bytes(), + ]; + for (key, body) in extra { + objects.push(format!("<< {key} {body} >>").into_bytes()); + } + let mut out = b"%PDF-1.4\n% parser regression fixture\n".to_vec(); + let mut offsets = Vec::new(); + for (index, body) in objects.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", index + 1).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes()); + for offset in offsets { + out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R /Info 6 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes()); + out + } + + fn compliant_info() -> &'static str { + "/GTS_PDFXVersion (PDF/X-1:2003) /GTS_PDFXConformance (PDF/X-1a:2003) /Trapped /False" + } + + #[test] + fn parsed_info_values_are_required_even_when_comment_contains_expected_values() { + let bytes = pdf( + "/TrimBox [0 0 100 100]", + "/GTS_PDFXVersion (wrong) /GTS_PDFXConformance (wrong) /Trapped /False", + b"% /GTS_PDFXVersion (PDF/X-1:2003) /GTS_PDFXConformance (PDF/X-1a:2003)\n", + &[], + ); + let issues = check_pdfx1a(&bytes); + assert!(issues.iter().any(|issue| issue.contains("doesn't name PDF/X-1:2003")), "{issues:?}"); + assert!(issues.iter().any(|issue| issue.contains("doesn't name the conformance level")), "{issues:?}"); + } + + #[test] + fn either_trim_or_art_box_is_accepted_but_not_both() { + let art_only = pdf("/ArtBox [0 0 100 100]", compliant_info(), b"", &[]); + let both = pdf("/TrimBox [0 0 100 100] /ArtBox [0 0 100 100]", compliant_info(), b"", &[]); + assert!(!check_pdfx1a(&art_only).iter().any(|issue| issue.contains("either a trim box or an art box"))); + assert!(check_pdfx1a(&both).iter().any(|issue| issue.contains("either a trim box or an art box"))); + } + + #[test] + fn an_unknown_registry_identifier_cannot_replace_a_destination_profile() { + let mut bytes = pdf("/TrimBox [0 0 100 100]", compliant_info(), b"", &[]); + let known = b"FOGRA39"; + let at = bytes.windows(known.len()).position(|window| window == known); + assert!(at.is_some()); + if let Some(at) = at { + bytes[at..at + known.len()].copy_from_slice(b"NOTREAL"); + } + let issues = check_pdfx1a(&bytes); + assert!(issues.iter().any(|issue| issue.contains("doesn't name a printing condition in the ICC registry")), "{issues:?}"); + } + + #[test] + fn finalizer_rejects_unbounded_xref_size_before_allocating_the_table() { + let mut bytes = pdf("/TrimBox [0 0 100 100]", compliant_info(), b"", &[]); + let size = b"/Size 7"; + let at = bytes.windows(size.len()).position(|window| window == size); + assert!(at.is_some()); + if let Some(at) = at { + bytes.splice(at..at + size.len(), b"/Size 1048577".iter().copied()); + } + assert!(Layout::read(&bytes).is_none()); + assert!(finish_x1a(&bytes).is_err()); + } + + #[test] + fn trapped_must_be_a_pdf_name_with_a_boolean_name_value() { + for value in ["(False)", "true", "(True)"] { + let info = format!("/GTS_PDFXVersion (PDF/X-1:2003) /GTS_PDFXConformance (PDF/X-1a:2003) /Trapped {value}"); + let bytes = pdf("/TrimBox [0 0 100 100]", &info, b"", &[]); + assert!(check_pdfx1a(&bytes).iter().any(|issue| issue.contains("needs /Trapped True or False")), "{value}"); + } + } +} diff --git a/crates/prepress/tests/flatten_document.rs b/crates/prepress/tests/flatten_document.rs index 165a80e9a..a24f5dfea 100644 --- a/crates/prepress/tests/flatten_document.rs +++ b/crates/prepress/tests/flatten_document.rs @@ -116,7 +116,6 @@ fn three_pages(font_bytes: &[u8]) -> Vec<u8> { s.pop(); text(s, &font, &face, (20.0, 110.0), 12.0, "World"); }); - drop(page); writer.finish().unwrap() } diff --git a/crates/print/Cargo.toml b/crates/print/Cargo.toml index 36b8813f2..7d4229f37 100644 --- a/crates/print/Cargo.toml +++ b/crates/print/Cargo.toml @@ -13,14 +13,14 @@ description = "System PDF print spooler for the Craft apps: CUPS and Windows" # downstream GDI values a different Rust type identity even when the code is unchanged. # PDF loader updates below are independent of this public transport API. craft-winprint-gdi = { git = "https://github.com/storytold/winprint.rs", rev = "64e7afd4d1483512385012c340ecaaaf0f3beb7f" } +# Says why the printer list is empty when lpstat can't run (e.g. a Flatpak without CUPS tools), +# and why a job went on with the paper the request names while the driver reported only one side +# of it (storytold/craft-libs#7230). +log = "0.4" [lints] workspace = true -[target.'cfg(unix)'.dependencies] -# Says why the printer list is empty when lpstat can't run (e.g. a Flatpak without CUPS tools). -log = "0.4" - [target.'cfg(windows)'.dependencies] # Printing without starting anything (storytold/pdfcraft#1107): the printer list (EnumPrinters) # and the job (Windows.Data.Pdf drawn with Direct2D into the XPS print API, options as a @@ -35,8 +35,9 @@ log = "0.4" # ticket (winprint.rs#12, storytold/pdfcraft#3823), and reads whitespace-padded integers in # PrintCapabilities (winprint.rs#3, storytold/pdfcraft#2430). Pinned to an immutable revision; # review before bumping. The settings chosen in a driver's own dialog become a ticket through -# `PrintTicket::from_dev_mode`. -winprint = { git = "https://github.com/storytold/winprint.rs", rev = "72951d7455ebcab569fbd9386c513d3d9f53fb02", default-features = false } +# `PrintTicket::from_dev_mode` (winprint.rs#24, pinned at its merge commit on winprint.rs's +# `main`). +winprint = { git = "https://github.com/storytold/winprint.rs", rev = "8ae097ef941b432b0e7671b1ec3a506800e65e57", default-features = false } # GetDefaultPrinter (MIT). winsafe = { version = "0.0.29", default-features = false, features = ["winspool"] } # The job file's private folder. diff --git a/crates/print/src/cups/mod.rs b/crates/print/src/cups/mod.rs new file mode 100644 index 000000000..1a0a9360b --- /dev/null +++ b/crates/print/src/cups/mod.rs @@ -0,0 +1,955 @@ +//! Based on the direct CUPS transport from contributor PR #156 (ahmedhosnypro), +//! kept separate from the broader network-printing registry in PR #116. +//! IPP/1.1 straight to the local CUPS server: printer discovery (`CUPS-Get-Printers`, +//! `CUPS-Get-Default`) and job submission (`Print-Job`) over HTTP/1.1, for when `lpstat`/`lp` +//! are missing (a sandboxed install, where the print dialog would otherwise have no printers). +//! Implemented from the public IPP encoding (RFC 2910/8010) and semantics (RFC 8011) and +//! CUPS's IPP documentation; the scheduler is reached on its socket or selected TCP endpoint. +//! +//! # Blocking and authorization +//! The caller authorizes endpoint selection. The absolute exchange deadline covers all request +//! writes and reply reads **after connection**. Standard-library DNS resolution and Unix socket +//! connection are blocking OS calls outside that deadline. TCP connection attempts have their +//! own timeout. This is not a whole-operation deadline API: do not call it on a UI thread or +//! promise bounded completion for arbitrary named hosts/Unix listeners. No detached timeout +//! thread is spawned; callers needing cancellation must supply a separately bounded transport. + +#[cfg(all(test, unix))] +mod tests; + +use super::{Duplex, Error, Job, Printer, Scaling}; +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; +#[cfg(unix)] +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::{Duration, Instant}; + +/// Where the local scheduler listens: its socket, else its loopback port. +const CUPS_SOCKET: &str = "/run/cups/cups.sock"; + +/// Caps on what the server may hand back: a reply is read into memory before it is parsed. +const MAX_BODY: usize = 1 << 20; +const MAX_HEADERS: usize = 8 << 10; +const MAX_PRINTERS: usize = 256; +const MAX_NAME: usize = 256; +/// A job's title on the wire; IPP values are u16-length, and no real title is this long. +const MAX_JOB_NAME: usize = 255; + +/// A wedged scheduler must not hang the dialog; a job may carry megabytes and is given longer. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(1); +const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(2); +const JOB_TIMEOUT: Duration = Duration::from_secs(30); + +/// IPP operation codes: the standard Print-Job, and CUPS's discovery extensions. +const OPERATION_PRINT_JOB: u16 = 0x0002; +const OPERATION_CUPS_GET_DEFAULT: u16 = 0x4001; +const OPERATION_CUPS_GET_PRINTERS: u16 = 0x4002; + +/// IPP value tags and group delimiters (RFC 8010 §5.1); the ones this client sends or reads. +const GROUP_OPERATION: u8 = 0x01; +const GROUP_JOB: u8 = 0x02; +const GROUP_END: u8 = 0x03; +const GROUP_PRINTER: u8 = 0x04; +const TAG_INTEGER: u8 = 0x21; +const TAG_BOOLEAN: u8 = 0x22; +const TAG_NAME: u8 = 0x42; +const TAG_KEYWORD: u8 = 0x44; +const TAG_URI: u8 = 0x45; +const TAG_CHARSET: u8 = 0x47; +const TAG_LANGUAGE: u8 = 0x48; +const TAG_MIME: u8 = 0x49; + +static REQUEST_ID: AtomicU32 = AtomicU32::new(1); + +/// How the scheduler is reached: its unix socket, else its loopback port. +#[derive(Clone, Debug)] +pub enum Server { + Unix(PathBuf), + Tcp(SocketAddr), + /// A caller-authorized host. DNS is resolved once for each connection attempt. + Named(String, u16), +} + +impl Server { + /// Parse an explicitly selected CUPS_SERVER value, without connecting. No URLs, + /// credentials, control characters or HTTP authority delimiters are accepted. + pub fn parse(value: &str) -> Result<Self, Error> { + if value.starts_with('/') { + return Ok(Self::Unix(value.into())); + } + if value.is_empty() || value.len() > 255 || value.bytes().any(|c| c.is_ascii_control() || c.is_ascii_whitespace() || b"/@?#\\".contains(&c)) { + return Err(Error::Spool("invalid CUPS server".into())); + } + let (host, port) = if let Some(rest) = value.strip_prefix('[') { + let (host, tail) = rest.split_once(']').ok_or_else(|| Error::Spool("invalid CUPS IPv6 host".into()))?; + if !host.contains(':') { + return Err(Error::Spool("bracketed CUPS host must be IPv6".into())); + } + let port = if tail.is_empty() { + 631 + } else { + tail.strip_prefix(':') + .and_then(|p| p.parse::<u16>().ok()) + .filter(|p| *p != 0) + .ok_or_else(|| Error::Spool("invalid CUPS port".into()))? + }; + (host, port) + } else if value.matches(':').count() > 1 { + // A bare IPv6 address is a host. A colon after its scope name may + // specify a port without cutting an address hextet in half. + if let Some((_, zone)) = value.split_once('%') + && zone.contains(':') + { + let (host, port) = value.rsplit_once(':').ok_or_else(|| Error::Spool("invalid CUPS endpoint".into()))?; + (host, port.parse::<u16>().ok().filter(|p| *p != 0).ok_or_else(|| Error::Spool("invalid CUPS port".into()))?) + } else { + (value, 631) + } + } else { + match value.rsplit_once(':') { + Some((host, port)) => (host, port.parse::<u16>().ok().filter(|p| *p != 0).ok_or_else(|| Error::Spool("invalid CUPS port".into()))?), + None => (value, 631), + } + }; + if host.is_empty() || host.contains(['[', ']']) { + return Err(Error::Spool("invalid CUPS host".into())); + } + if let Ok(ip) = host.parse::<std::net::IpAddr>() { + return Ok(Self::Tcp(SocketAddr::new(ip, port))); + } + if host.contains(':') { + let (ip, zone) = host.split_once('%').ok_or_else(|| Error::Spool("invalid CUPS IPv6 host".into()))?; + if ip.parse::<std::net::Ipv6Addr>().is_err() + || zone.is_empty() + || !zone.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) + { + return Err(Error::Spool("invalid CUPS IPv6 scope".into())); + } + } else if host.contains('%') { + return Err(Error::Spool("invalid CUPS host".into())); + } + Ok(Self::Named(host.into(), port)) + } + + fn authority(&self) -> String { + match self { + Self::Unix(_) => "localhost".into(), + Self::Tcp(addr) => addr.to_string().replace('%', "%25"), + Self::Named(host, port) if host.contains(':') => format!("[{}]:{port}", host.replace('%', "%25")), + Self::Named(host, port) => format!("{host}:{port}"), + } + } +} + +/// Local scheduler candidates, honoring the user's explicit CUPS_SERVER setting. +/// No requests are made by this function; apps must authorize selection before use. +pub fn configured_servers() -> Result<Vec<Server>, Error> { + if let Some(value) = std::env::var_os("CUPS_SERVER").filter(|v| !v.is_empty()) { + return Ok(vec![Server::parse(&value.to_string_lossy())?]); + } + Ok(vec![ + Server::Unix(CUPS_SOCKET.into()), + Server::Unix("/var/run/cups/cups.sock".into()), + Server::Unix("/private/var/run/cupsd".into()), + Server::Tcp(([127, 0, 0, 1], 631).into()), + ]) +} + +fn endpoints() -> [Server; 2] { + [Server::Unix(PathBuf::from(CUPS_SOCKET)), Server::Tcp(([127, 0, 0, 1], 631).into())] +} + +/// Whether the local CUPS server is reachable: its socket, else its loopback port. A missing +/// scheduler is a normal `false`, not an error. +pub fn cups_reachable() -> bool { + endpoints().iter().any(reachable) +} + +/// Probe a caller-authorized endpoint without sending a print request. +/// DNS and Unix connect have the blocking limitations documented on this module. +pub fn reachable(server: &Server) -> bool { + connect(server).is_ok() +} + +fn connect(server: &Server) -> std::io::Result<Stream> { + match server { + #[cfg(unix)] + Server::Unix(path) => UnixStream::connect(path).map(Stream::Unix), + #[cfg(not(unix))] + Server::Unix(_) => Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "Unix sockets unavailable")), + Server::Named(host, port) => { + // Validate even directly constructed public variants before resolving or writing headers. + let endpoint = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }; + let parsed = Server::parse(&endpoint).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?; + if matches!(parsed, Server::Unix(_)) { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "a named CUPS host cannot be a Unix path")); + } + let addr = (host.as_str(), *port) + .to_socket_addrs()? + .next() + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "CUPS host has no address"))?; + TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).map(Stream::Tcp) + } + // A loopback connect either answers promptly or the server is not there. + Server::Tcp(addr) => TcpStream::connect_timeout(addr, CONNECT_TIMEOUT).map(|s| { + let _ = s.set_nodelay(true); + Stream::Tcp(s) + }), + } +} + +/// A connection to the scheduler. +enum Stream { + #[cfg(unix)] + Unix(UnixStream), + Tcp(TcpStream), +} + +impl Stream { + fn set_timeouts(&self, timeout: Duration) -> std::io::Result<()> { + let (read, write) = match self { + #[cfg(unix)] + Stream::Unix(s) => (s.set_read_timeout(Some(timeout)), s.set_write_timeout(Some(timeout))), + Stream::Tcp(s) => (s.set_read_timeout(Some(timeout)), s.set_write_timeout(Some(timeout))), + }; + read.and(write) + } +} + +impl Read for Stream { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { + match self { + #[cfg(unix)] + Stream::Unix(s) => s.read(buf), + Stream::Tcp(s) => s.read(buf), + } + } +} + +impl Write for Stream { + fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { + match self { + #[cfg(unix)] + Stream::Unix(s) => s.write(buf), + Stream::Tcp(s) => s.write(buf), + } + } + fn flush(&mut self) -> std::io::Result<()> { + match self { + #[cfg(unix)] + Stream::Unix(s) => s.flush(), + Stream::Tcp(s) => s.flush(), + } + } +} + +/// The server's queues (CUPS-Get-Printers) and its default destination (CUPS-Get-Default), for +/// the Print dialog when `lpstat` is missing. A default the queue list lacks is appended, so +/// the dialog always has a selection to restore; a default that cannot be named still leaves +/// the queues usable. +pub fn printers() -> Result<Vec<Printer>, Error> { + printers_at(&endpoints()) +} + +pub fn printers_at(endpoints: &[Server]) -> Result<Vec<Printer>, Error> { + let queues = discover(endpoints, OPERATION_CUPS_GET_PRINTERS)?; + let default = discover(endpoints, OPERATION_CUPS_GET_DEFAULT).ok().and_then(|names| names.into_iter().next()); + let mut printers: Vec<Printer> = Vec::new(); + for name in queues { + if printers.len() >= MAX_PRINTERS { + break; + } + if !printers.iter().any(|p| p.name == name) { + printers.push(Printer { description: String::new(), default: default.as_deref() == Some(name.as_str()), name, two_sided: None }); + } + } + if let Some(name) = default + && !printers.iter().any(|p| p.name == name) + { + printers.push(Printer { description: String::new(), name, default: true, two_sided: None }); + } + Ok(printers) +} + +/// The printer names a discovery reply carries: every queue (CUPS-Get-Printers), or the default +/// destination (CUPS-Get-Default). +fn discover(endpoints: &[Server], operation: u16) -> Result<Vec<String>, Error> { + let reply = post(endpoints, "/", &discovery_request(operation), DISCOVERY_TIMEOUT, true)?; + let parsed = parse_reply(&reply)?; + if status_ok(parsed.status) { Ok(parsed.names) } else { Err(refused(parsed.status)) } +} + +/// Submit the PDF as a Print-Job to the printer (the job's, else the server's default); the +/// reply is the job message, like `lp` prints it (`request id is Office-12`). The driver's own +/// job options (PPD keywords) are not sent on this path: they have no IPP equivalents without +/// reading the printer's capabilities, which is another request. +pub fn print_job(pdf: &[u8], job: &Job) -> Result<String, Error> { + print_job_at(&endpoints(), pdf, job) +} + +pub(crate) fn print_job_at(endpoints: &[Server], pdf: &[u8], job: &Job) -> Result<String, Error> { + let queue = match &job.printer { + Some(name) => name.clone(), + None => discover(endpoints, OPERATION_CUPS_GET_DEFAULT)? + .into_iter() + .next() + .ok_or_else(|| Error::Spool("the print server has no default printer; choose one in the dialog".into()))?, + }; + if !is_queue_name(&queue) { + return Err(Error::Spool(format!("not a printer name: {queue}"))); + } + let reply = post(endpoints, &format!("/printers/{queue}"), &print_job_request(&queue, pdf, job), JOB_TIMEOUT, false)?; + let parsed = parse_reply(&reply)?; + if !status_ok(parsed.status) { + return Err(refused(parsed.status)); + } + Ok(match parsed.job_id { + Some(id) => format!("request id is {queue}-{id}"), + None => format!("the job was accepted by {queue}"), + }) +} + +/// A queue class can route a job to any member printer. Keep the destination kind +/// explicit rather than guessing it from a name shared by a printer and a class. +#[derive(Clone, Debug)] +pub struct Destination { + pub name: String, + pub is_class: bool, +} + +/// List both printer queues and classes from caller-selected CUPS endpoints. +/// The caller owns endpoint selection/authorization; this API does not discover network hosts. +pub fn destinations_at(endpoints: &[Server]) -> Result<Vec<Queue>, Error> { + let mut out = queues_at(endpoints, false)?; + out.extend(queues_at(endpoints, true)?); + if out.len() > MAX_PRINTERS { + return Err(Error::Spool("too many CUPS destinations".into())); + } + let default = default_at(endpoints)?; + for queue in &mut out { + queue.is_default = default.as_deref() == Some(queue.name.as_str()); + } + Ok(out) +} + +/// List either printer queues or classes, without resolving defaults. Applications can +/// explicitly choose whether an optional class/default query failure should hide otherwise +/// usable printer queues. No error is swallowed here except CUPS's absent/unsupported list. +pub fn queues_at(endpoints: &[Server], is_class: bool) -> Result<Vec<Queue>, Error> { + let operation = if is_class { 0x4005 } else { OPERATION_CUPS_GET_PRINTERS }; + let reply = post(endpoints, "/", &discovery_request(operation), DISCOVERY_TIMEOUT, true)?; + let parsed = parse_reply(&reply)?; + if !status_ok(parsed.status) { + if parsed.status == 0x0406 || (is_class && parsed.status == 0x0501) { + return Ok(Vec::new()); + } + return Err(refused(parsed.status)); + } + let mut queues = parsed.queues; + for queue in &mut queues { + queue.is_class = is_class; + } + Ok(queues) +} + +/// The scheduler's default queue; not-found means no default has been configured. +pub fn default_at(endpoints: &[Server]) -> Result<Option<String>, Error> { + let reply = post(endpoints, "/", &discovery_request(OPERATION_CUPS_GET_DEFAULT), DISCOVERY_TIMEOUT, true)?; + let parsed = parse_reply(&reply)?; + if parsed.status == 0x0406 { + return Ok(None); + } + if !status_ok(parsed.status) { + return Err(refused(parsed.status)); + } + Ok(parsed.names.into_iter().next()) +} + +/// Metadata from one CUPS printer group, without losing which fields belong together. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Queue { + pub name: String, + pub info: String, + pub state: u32, + pub accepting_jobs: bool, + pub is_default: bool, + pub is_class: bool, +} +impl Default for Queue { + fn default() -> Self { + Self { name: String::new(), info: String::new(), state: 3, accepting_jobs: true, is_default: false, is_class: false } + } +} + +/// Submit once to an explicitly selected queue/class, returning the numeric server job id. +/// An absent id is an uncertain accepted outcome, not permission to retry the document. +pub fn submit_at(endpoints: &[Server], destination: &Destination, pdf: &[u8], job: &Job) -> Result<u32, Error> { + submit_as_at(endpoints, destination, pdf, job, "") +} + +/// As [`submit_at`], with the user name supplied by the application, never inferred from +/// process credentials. Once any request bytes may have been sent, no other endpoint is tried. +pub fn submit_as_at(endpoints: &[Server], destination: &Destination, pdf: &[u8], job: &Job, user: &str) -> Result<u32, Error> { + let path = destination_path(destination)?; + if user.len() > MAX_JOB_NAME || user.chars().any(char::is_control) { + return Err(Error::Spool("invalid CUPS user name".into())); + } + if job.copies == 0 || job.copies > 999 { + return Err(Error::Spool("copies must be between 1 and 999".into())); + } + let mut last = Error::Spool("no CUPS endpoint selected".into()); + for endpoint in endpoints { + let mut stream = match connect(endpoint) { + Ok(stream) => stream, + Err(error) => { + last = Error::Spool(format!("CUPS connection failed: {error}")); + continue; + } + }; + let authority = endpoint.authority(); + let request = print_job_request_for(&authority, &path, pdf, job, user); + // Never retry exchange errors: the scheduler may already have accepted the job. + let reply = exchange(&mut stream, &authority, &path, &request, JOB_TIMEOUT)?; + let parsed = parse_reply(&reply)?; + if !status_ok(parsed.status) { + return Err(refused(parsed.status)); + } + return parsed + .job_id + .filter(|id| *id != 0 && *id <= i32::MAX as u32) + .ok_or_else(|| Error::Spool("CUPS accepted the job without a usable job id; do not resubmit".into())); + } + Err(last) +} + +/// Encode one destination as a URI path segment, never as routing syntax. Names from +/// discovery may include spaces or Unicode. Reject separators, controls and dot segments +/// rather than relying on a server to keep an encoded traversal request harmless. +fn destination_path(destination: &Destination) -> Result<String, Error> { + let name = &destination.name; + if name.is_empty() + || name.len() > MAX_NAME + || matches!(name.as_str(), "." | "..") + || name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\')) + { + return Err(Error::Spool("invalid CUPS destination name".into())); + } + let kind = if destination.is_class { "classes" } else { "printers" }; + let mut path = format!("/{kind}/"); + for byte in name.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + path.push(char::from(byte)); + } else { + use std::fmt::Write as _; + write!(&mut path, "%{byte:02X}").map_err(|_| Error::Spool("could not encode CUPS destination".into()))?; + } + } + Ok(path) +} + +/// A CUPS queue name: ASCII letters, digits and `_`, `-`, `.` — what the scheduler accepts, and +/// what cannot break the printer URI's path. +fn is_queue_name(name: &str) -> bool { + !name.is_empty() && name.len() <= MAX_NAME && name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) +} + +/// One IPP request and its reply body. Discovery may try each endpoint in turn; a job is given +/// to the first endpoint that accepts a connection, once: a retry could print it twice. +pub(crate) fn post(endpoints: &[Server], path: &str, body: &[u8], timeout: Duration, retry: bool) -> Result<Vec<u8>, Error> { + let mut failed: Option<Error> = None; + for server in endpoints { + let mut stream = match connect(server) { + Ok(stream) => stream, + Err(e) => { + failed = Some(Error::Spool(format!("the print server could not be reached: {e}"))); + continue; + } + }; + match exchange(&mut stream, &server.authority(), path, body, timeout) { + Ok(reply) => return Ok(reply), + Err(e) => { + failed = Some(e); + if !retry { + break; + } + } + } + } + Err(failed.unwrap_or_else(|| Error::Spool("the print server could not be reached".into()))) +} + +/// Send one IPP request and read the reply's body. +fn exchange(stream: &mut Stream, authority: &str, path: &str, body: &[u8], timeout: Duration) -> Result<Vec<u8>, Error> { + let mut stream = DeadlineReader { stream, end: Instant::now() + timeout }; + let head = format!( + "POST {path} HTTP/1.1\r\nHost: {authority}\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + stream + .write_all(head.as_bytes()) + .and_then(|()| stream.write_all(body)) + .and_then(|()| stream.flush()) + .map_err(|e| Error::Spool(format!("the request could not be sent to the print server: {e}")))?; + let reply = read_reply(&mut stream)?; + validate_reply_identity(body, &reply)?; + Ok(reply) +} + +/// One absolute deadline shared by request writes and reply reads after connection. +struct DeadlineReader<'a> { + stream: &'a mut Stream, + end: Instant, +} +impl Write for DeadlineReader<'_> { + fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { + let left = self + .end + .checked_duration_since(Instant::now()) + .filter(|d| !d.is_zero()) + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::TimedOut, "CUPS exchange deadline exceeded"))?; + self.stream.set_timeouts(left)?; + self.stream.write(buf) + } + fn flush(&mut self) -> std::io::Result<()> { + self.stream.flush() + } +} + +fn validate_reply_identity(request: &[u8], reply: &[u8]) -> Result<(), Error> { + if reply.get(..2) != Some(&[1, 1]) || request.get(4..8).is_none() || request.get(4..8) != reply.get(4..8) { + return Err(Error::Spool("CUPS reply version or request id does not match; do not resubmit".into())); + } + Ok(()) +} + +impl Read for DeadlineReader<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { + let left = self + .end + .checked_duration_since(Instant::now()) + .filter(|d| !d.is_zero()) + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::TimedOut, "CUPS reply deadline exceeded"))?; + #[cfg(not(target_os = "macos"))] + self.stream.set_timeouts(left)?; + #[cfg(target_os = "macos")] + if let Err(error) = self.stream.set_timeouts(left) { + // Darwin rejects timeout updates on a disconnected Unix socket even + // when a complete reply is still buffered. Never fall back to a + // blocking read: drain at most this buffer, or fail on WouldBlock. + // Every subsequent read rechecks the same absolute deadline above. + if error.raw_os_error() == Some(22) + && let Stream::Unix(stream) = self.stream + { + stream.set_nonblocking(true)?; + let result = stream.read(buf); + let restored = stream.set_nonblocking(false); + return result.and_then(|count| restored.map(|()| count)); + } + return Err(error); + } + self.stream.read(buf) + } +} + +fn read_reply(stream: &mut impl Read) -> Result<Vec<u8>, Error> { + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + loop { + if head.len() >= MAX_HEADERS { + return Err(Error::Spool("the print server sent a header block that is too large".into())); + } + match stream.read(&mut byte) { + Ok(0) => return Err(Error::Spool("the print server closed the connection before sending its reply".into())), + Ok(_) => head.push(byte[0]), + Err(e) => return Err(Error::Spool(format!("the print server's reply could not be read: {e}"))), + } + if head.ends_with(b"\r\n\r\n") { + break; + } + } + let head = String::from_utf8_lossy(&head); + let Some(status_line) = head.lines().next() else { return Err(Error::Spool("the print server sent an unreadable reply".into())) }; + let code = status_line + .strip_prefix("HTTP/") + .and_then(|rest| rest.split_once(' ')) + .and_then(|(_, code)| code.split_whitespace().next()) + .and_then(|code| code.parse::<u16>().ok()) + .ok_or_else(|| Error::Spool("the print server sent an unreadable reply".into()))?; + match code { + 200..=299 => {} + 401 => return Err(Error::Spool("the print server requires authentication".into())), + 426 => return Err(Error::Spool("the print server only accepts encrypted connections".into())), + _ => return Err(Error::Spool(format!("the print server refused the request (HTTP {code})"))), + } + let mut content_length: Option<usize> = None; + let mut chunked = false; + for line in head.lines().skip(1) { + // The empty line ends the header block; any other line without a colon is malformed. + if line.is_empty() { + continue; + } + let Some((name, value)) = line.split_once(':') else { + return Err(Error::Spool("the print server sent an unreadable header".into())); + }; + match name.trim().to_ascii_lowercase().as_str() { + "content-length" => { + let len = value.trim().parse::<usize>().map_err(|_| Error::Spool("invalid Content-Length".into()))?; + if content_length.replace(len).is_some() { + return Err(Error::Spool("duplicate Content-Length".into())); + } + } + // Only `identity` is not a transfer encoding to be decoded. + "transfer-encoding" => { + if chunked || !value.trim().eq_ignore_ascii_case("chunked") { + return Err(Error::Spool("unsupported Transfer-Encoding".into())); + } + chunked = true; + } + _ => {} + } + } + if chunked { + if content_length.is_some() { + return Err(Error::Spool("ambiguous reply framing".into())); + } + return read_chunks(stream); + } + let Some(len) = content_length else { return Err(Error::Spool("the print server sent no Content-Length".into())) }; + if len > MAX_BODY { + return Err(Error::Spool(format!("the print server's reply is too large ({len} bytes)"))); + } + let mut body = vec![0u8; len]; + stream.read_exact(&mut body).map_err(|e| Error::Spool(format!("the print server's reply was cut short: {e}")))?; + Ok(body) +} + +fn read_chunks(stream: &mut impl Read) -> Result<Vec<u8>, Error> { + fn line(stream: &mut impl Read) -> Result<Vec<u8>, Error> { + let mut out = Vec::new(); + for _ in 0..MAX_HEADERS { + let mut byte = [0]; + stream.read_exact(&mut byte).map_err(|e| Error::Spool(format!("truncated chunk: {e}")))?; + out.push(byte[0]); + if out.ends_with(b"\r\n") { + out.truncate(out.len() - 2); + return Ok(out); + } + } + Err(Error::Spool("chunk line exceeds limit".into())) + } + let mut body = Vec::new(); + for _ in 0..100_000 { + let header = line(stream)?; + let size = header.split(|b| *b == b';').next().unwrap_or_default(); + if size.is_empty() || !size.iter().all(u8::is_ascii_hexdigit) { + return Err(Error::Spool("invalid chunk size".into())); + } + let len = std::str::from_utf8(size) + .ok() + .and_then(|s| usize::from_str_radix(s, 16).ok()) + .ok_or_else(|| Error::Spool("invalid chunk size".into()))?; + if len == 0 { + let mut total = 0usize; + loop { + let trailer = line(stream)?; + total = total.saturating_add(trailer.len() + 2); + if total > MAX_HEADERS { + return Err(Error::Spool("chunk trailers exceed limit".into())); + } + if trailer.is_empty() { + return Ok(body); + } + if !trailer.contains(&b':') { + return Err(Error::Spool("invalid chunk trailer".into())); + } + } + } + let end = body.len().checked_add(len).filter(|n| *n <= MAX_BODY).ok_or_else(|| Error::Spool("chunked reply exceeds limit".into()))?; + let start = body.len(); + body.resize(end, 0); + stream.read_exact(&mut body[start..]).map_err(|e| Error::Spool(format!("truncated chunk: {e}")))?; + let mut crlf = [0; 2]; + stream.read_exact(&mut crlf).map_err(|e| Error::Spool(format!("truncated chunk: {e}")))?; + if crlf != *b"\r\n" { + return Err(Error::Spool("invalid chunk terminator".into())); + } + } + Err(Error::Spool("too many chunks".into())) +} + +/// An IPP request being built: a version, an operation and a request id, then attributes, then +/// the document. +struct Request { + bytes: Vec<u8>, +} + +impl Request { + fn new(operation: u16) -> Self { + // IPP 1.1: version, operation, a request id (any nonzero value). + let mut bytes = vec![1, 1]; + bytes.extend(operation.to_be_bytes()); + bytes.extend(REQUEST_ID.fetch_add(1, Ordering::Relaxed).max(1).to_be_bytes()); + Request { bytes } + } + + fn group(&mut self, tag: u8) { + self.bytes.push(tag); + } + + fn end(&mut self) { + self.bytes.push(GROUP_END); + } + + fn attribute(&mut self, tag: u8, name: &str, value: &[u8]) { + let (Ok(name_len), Ok(value_len)) = (u16::try_from(name.len()), u16::try_from(value.len())) else { + return; + }; + self.bytes.push(tag); + self.bytes.extend(name_len.to_be_bytes()); + self.bytes.extend(name.as_bytes()); + self.bytes.extend(value_len.to_be_bytes()); + self.bytes.extend(value); + } + + /// An additional value of the previous attribute (a `1setOf`): the name is empty. + fn additional(&mut self, tag: u8, value: &str) { + self.attribute(tag, "", value.as_bytes()); + } +} + +/// A discovery request: the operation's required attributes, then the names to be answered with. +fn discovery_request(operation: u16) -> Vec<u8> { + let mut r = Request::new(operation); + r.group(GROUP_OPERATION); + r.attribute(TAG_CHARSET, "attributes-charset", b"utf-8"); + r.attribute(TAG_LANGUAGE, "attributes-natural-language", b"en"); + r.attribute(TAG_URI, "printer-uri", b"ipp://localhost/"); + r.attribute(TAG_KEYWORD, "requested-attributes", b"printer-name"); + r.additional(TAG_KEYWORD, "printer-info"); + r.additional(TAG_KEYWORD, "printer-state"); + r.additional(TAG_KEYWORD, "printer-is-accepting-jobs"); + r.end(); + r.bytes +} + +/// A Print-Job request for `queue`: the job's options as IPP attributes, the PDF as the document +/// data that follows the end of attributes. +fn print_job_request(queue: &str, pdf: &[u8], job: &Job) -> Vec<u8> { + print_job_request_path(&format!("/printers/{queue}"), pdf, job) +} + +fn print_job_request_path(path: &str, pdf: &[u8], job: &Job) -> Vec<u8> { + print_job_request_for("localhost", path, pdf, job, "") +} + +fn print_job_request_for(authority: &str, path: &str, pdf: &[u8], job: &Job, user: &str) -> Vec<u8> { + let mut r = Request::new(OPERATION_PRINT_JOB); + r.group(GROUP_OPERATION); + r.attribute(TAG_CHARSET, "attributes-charset", b"utf-8"); + r.attribute(TAG_LANGUAGE, "attributes-natural-language", b"en"); + r.attribute(TAG_URI, "printer-uri", format!("ipp://{authority}{path}").as_bytes()); + if !user.is_empty() { + r.attribute(TAG_NAME, "requesting-user-name", user.as_bytes()); + } + r.attribute(TAG_NAME, "job-name", truncate_utf8(&job.title, MAX_JOB_NAME).as_bytes()); + r.attribute(TAG_MIME, "document-format", b"application/pdf"); + r.group(GROUP_JOB); + r.attribute(TAG_INTEGER, "copies", &job.copies.clamp(1, 999).to_be_bytes()); + r.attribute(TAG_BOOLEAN, "collate", &[u8::from(job.collate)]); + if let Some(duplex) = job.duplex { + r.attribute( + TAG_KEYWORD, + "sides", + match duplex { + Duplex::Off => "one-sided", + Duplex::LongEdge => "two-sided-long-edge", + Duplex::ShortEdge => "two-sided-short-edge", + } + .as_bytes(), + ); + } + if job.grayscale { + r.attribute(TAG_KEYWORD, "print-color-mode", b"monochrome"); + } + // PWG 5100.13 §6.2.5: `none` keeps every sheet at its size, `auto-fit` shrinks only + // oversized ones — the same choices `lp`'s fit-to-page and print-scaling options make. + r.attribute( + TAG_KEYWORD, + "print-scaling", + match job.scaling { + Scaling::Exact => "none", + Scaling::ShrinkToFit => "auto-fit", + } + .as_bytes(), + ); + r.end(); + r.bytes.extend(pdf); + r.bytes +} + +/// The string cut to at most `max` bytes, at a character boundary. +fn truncate_utf8(s: &str, max: usize) -> &str { + if s.len() <= max { + return s; + } + let mut end = max; + while !s.is_char_boundary(end) { + end -= 1; + } + // `end` is a checked boundary; nothing is the only name that cannot be cut. + s.get(..end).unwrap_or_default() +} + +/// The parsed parts of a reply: the IPP status, the printer names in its printer groups, and a +/// submission's job id. +struct Reply { + status: u16, + names: Vec<String>, + queues: Vec<Queue>, + job_id: Option<u32>, +} + +/// A cursor over a reply: `None` at the end or past a length, never an over-read. +struct Reader<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Reader<'a> { + fn take(&mut self, len: usize) -> Option<&'a [u8]> { + let end = self.pos.checked_add(len)?; + let taken = self.bytes.get(self.pos..end)?; + self.pos = end; + Some(taken) + } + + fn array<const N: usize>(&mut self) -> Option<[u8; N]> { + <[u8; N]>::try_from(self.take(N)?).ok() + } + + fn u16(&mut self) -> Option<u16> { + self.array::<2>().map(u16::from_be_bytes) + } +} + +fn parse_reply(reply: &[u8]) -> Result<Reply, Error> { + let malformed = || Error::Spool("the print server sent a malformed reply".into()); + let mut r = Reader { bytes: reply, pos: 0 }; + let _version = r.array::<2>().ok_or_else(malformed)?; + let status = r.u16().ok_or_else(malformed)?; + let _request_id = r.array::<4>().ok_or_else(malformed)?; + let (mut names, mut job_id, mut group) = (Vec::new(), None, 0u8); + let mut queues = Vec::new(); + let mut queue = Queue::default(); + loop { + let Some(tag) = r.array::<1>().map(|t| t[0]) else { return Err(malformed()) }; + match tag { + GROUP_END => { + if !queue.name.is_empty() { + queues.push(queue); + } + break; + } + GROUP_OPERATION | GROUP_JOB | GROUP_PRINTER | 0x05 => { + if !queue.name.is_empty() { + if queues.len() >= MAX_PRINTERS { + return Err(malformed()); + } + queues.push(std::mem::take(&mut queue)); + } else { + queue = Queue::default(); + } + group = tag; + } + // An attribute: name and value, each u16-length. An empty name is an additional + // value of the previous one (the attributes read here are single-valued, so those + // are ignored). Group tags not in the registry and collections (the attributes + // requested here are never collections) are refused, not guessed. + 0x10..=0x33 | 0x35..=0x4A => { + let name_len = r.u16().ok_or_else(malformed)?; + if usize::from(name_len) > MAX_NAME { + return Err(malformed()); + } + let name_bytes = r.take(usize::from(name_len)).ok_or_else(malformed)?; + let name = std::str::from_utf8(name_bytes).map_err(|_| malformed())?; + let value_len = r.u16().ok_or_else(malformed)?; + let value = r.take(usize::from(value_len)).ok_or_else(malformed)?; + match (group, name, tag) { + (GROUP_PRINTER, "printer-name", TAG_NAME) => { + if let Some(printer) = std::str::from_utf8(value).ok().filter(|n| !n.is_empty() && n.len() <= MAX_NAME) { + if names.len() >= MAX_PRINTERS { + return Err(Error::Spool("too many CUPS destinations".into())); + } + if !queue.name.is_empty() { + return Err(malformed()); + } + queue.name = printer.to_string(); + names.push(printer.to_string()); + } + } + (GROUP_PRINTER, "printer-info", 0x41 | TAG_NAME) => { + // Human descriptions are text, not queue identifiers. Their u16 + // wire length and the whole-response MAX_BODY cap bound allocation. + queue.info = std::str::from_utf8(value).map_err(|_| malformed())?.to_owned(); + } + (GROUP_PRINTER, "printer-state", 0x23 | TAG_INTEGER) => { + queue.state = u32::from_be_bytes(value.try_into().map_err(|_| malformed())?); + } + (GROUP_PRINTER, "printer-is-accepting-jobs", TAG_BOOLEAN) => { + queue.accepting_jobs = match value { + [0] => false, + [1] => true, + _ => return Err(malformed()), + }; + } + (GROUP_JOB, "job-id", TAG_INTEGER) => { + if let Ok(id) = <[u8; 4]>::try_from(value) { + job_id = Some(u32::from_be_bytes(id)); + } + } + _ => {} + } + } + _ => return Err(malformed()), + } + } + Ok(Reply { status, names, queues, job_id }) +} + +/// Successful IPP status codes are `0x00xx` (RFC 8011 Appendix B). +fn status_ok(status: u16) -> bool { + status < 0x0100 +} + +/// The IPP status code's name, for the error the user sees. +fn status_name(status: u16) -> Option<&'static str> { + Some(match status { + 0x0400 => "bad request", + 0x0401 => "forbidden", + 0x0402 => "not authenticated", + 0x0403 => "not authorized", + 0x0404 => "not possible", + 0x0406 => "printer not found", + 0x0408 => "request too large", + 0x040A => "PDF is not a supported document format for this printer", + 0x0412 => "the document could not be accessed", + 0x0500 => "internal error", + 0x0501 => "operation not supported", + 0x0502 => "service unavailable", + 0x0503 => "IPP version not supported", + 0x0504 => "device error", + 0x0505 => "temporary error", + 0x0506 => "the printer is not accepting jobs", + 0x0507 => "the printer is busy", + _ => return None, + }) +} + +fn refused(status: u16) -> Error { + match status_name(status) { + Some(name) => Error::Spool(format!("the print server refused the request ({name})")), + None => Error::Spool(format!("the print server refused the request (IPP status 0x{status:04X})")), + } +} diff --git a/crates/print/src/cups/tests.rs b/crates/print/src/cups/tests.rs new file mode 100644 index 000000000..978246e56 --- /dev/null +++ b/crates/print/src/cups/tests.rs @@ -0,0 +1,593 @@ +//! The IPP client against a fake CUPS server (a unix socket or a loopback port): discovery, +//! Print-Job, and the malformed replies it must refuse without a panic. + +use super::*; +use crate as spool; +use crate::cups::{self as ipp, Server}; +use std::collections::VecDeque; +use std::io::{Read, Write}; +use std::sync::Mutex; +use std::sync::mpsc::{self, Receiver}; +use std::time::Duration; + +const TIMEOUT: Duration = Duration::from_secs(2); + +/// A fake CUPS server: each connection carries one request; the next canned reply goes back +/// (nothing, when the list is out — the client then sees a hang-up). Every request is recorded +/// for the assertions. +struct FakeCups { + server: Server, + requests: Receiver<Vec<u8>>, +} + +impl FakeCups { + fn on_unix(replies: Vec<Vec<u8>>) -> std::io::Result<Self> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("cups.sock"); + let listener = std::os::unix::net::UnixListener::bind(&path)?; + // The socket must outlive this function; the folder is left for the process to reap. + std::mem::forget(dir); + let requests = listen_unix(listener, replies); + Ok(FakeCups { server: Server::Unix(path), requests }) + } + + fn on_tcp(replies: Vec<Vec<u8>>) -> std::io::Result<Self> { + let listener = std::net::TcpListener::bind("127.0.0.1:0")?; + let server = Server::Tcp(listener.local_addr()?); + let requests = listen_tcp(listener, replies); + Ok(FakeCups { server, requests }) + } + + fn request(&self) -> Result<Vec<u8>, mpsc::RecvTimeoutError> { + self.requests.recv_timeout(Duration::from_secs(5)) + } + + /// The server as the one-endpoint list the client functions take. + fn endpoint(&self) -> &[Server] { + std::slice::from_ref(&self.server) + } +} + +fn listen_unix(listener: std::os::unix::net::UnixListener, replies: Vec<Vec<u8>>) -> Receiver<Vec<u8>> { + let (tx, rx) = mpsc::channel(); + let replies = Mutex::new(VecDeque::from(replies)); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + serve(stream, &replies, &tx); + } + }); + rx +} + +fn listen_tcp(listener: std::net::TcpListener, replies: Vec<Vec<u8>>) -> Receiver<Vec<u8>> { + let (tx, rx) = mpsc::channel(); + let replies = Mutex::new(VecDeque::from(replies)); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + serve(stream, &replies, &tx); + } + }); + rx +} + +fn serve(mut stream: impl Read + Write, replies: &Mutex<VecDeque<Vec<u8>>>, requests: &mpsc::Sender<Vec<u8>>) { + let Some(request) = read_request(&mut stream) else { return }; + let Some(body) = ipp_body(&request) else { return }; + let request_id = body.get(4..8).map(|id| id.to_vec()); + let _ = requests.send(request); + // A list out of replies is a server that hangs up before answering. + let Ok(mut replies) = replies.lock() else { return }; + if let Some(mut reply) = replies.pop_front() { + if let Some(body) = reply.windows(4).position(|w| w == b"\r\n\r\n").map(|at| at + 4) + && reply.get(body..body + 2) == Some(&[1, 1]) + && let Some(id) = request_id + && let Some(destination) = reply.get_mut(body + 4..body + 8) + { + destination.copy_from_slice(&id); + } + let _ = stream.write_all(&reply); + let _ = stream.flush(); + } +} + +/// One HTTP request: the headers (bounded), then the `Content-Length` body it announces. +fn read_request(stream: &mut impl Read) -> Option<Vec<u8>> { + let mut buf = Vec::new(); + let mut byte = [0u8; 1]; + loop { + match stream.read(&mut byte) { + Ok(0) | Err(_) => return None, + Ok(_) => buf.push(byte[0]), + } + if buf.ends_with(b"\r\n\r\n") { + break; + } + if buf.len() > 1 << 16 { + return None; + } + } + let head = String::from_utf8_lossy(&buf); + let len: usize = head.lines().find_map(|l| l.strip_prefix("Content-Length:")).and_then(|v| v.trim().parse().ok())?; + let head_len = buf.len(); + buf.resize(head_len + len, 0); + stream.read_exact(&mut buf[head_len..]).ok()?; + Some(buf) +} + +/// An HTTP reply carrying `body`, as CUPS would send it. +fn http_reply(body: &[u8]) -> Vec<u8> { + let mut out = format!("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\n\r\n", body.len()).into_bytes(); + out.extend(body); + out +} + +/// An IPP reply body: `status`, then the attribute groups as raw bytes, then end of attributes. +fn ipp_reply(status: u16, groups: &[&[u8]]) -> Vec<u8> { + let mut out = vec![1, 1]; + out.extend(status.to_be_bytes()); + out.extend(1u32.to_be_bytes()); + for &group in groups { + out.extend(group); + } + out.push(0x03); + out +} + +fn group(tag: u8) -> Vec<u8> { + vec![tag] +} + +fn printer_name(name: &str) -> Vec<u8> { + attr(0x42, "printer-name", name.as_bytes()) +} + +/// One attribute, framed the way the client frames them, so `has` finds it in a request. +fn attr(tag: u8, name: &str, value: &[u8]) -> Vec<u8> { + let mut out = vec![tag]; + out.extend((name.len() as u16).to_be_bytes()); + out.extend(name.as_bytes()); + out.extend((value.len() as u16).to_be_bytes()); + out.extend(value); + out +} + +fn has(bytes: &[u8], needle: &[u8]) -> bool { + !needle.is_empty() && bytes.windows(needle.len()).any(|w| w == needle) +} + +/// The IPP part of a recorded request: everything after the HTTP head. +fn ipp_body(request: &[u8]) -> Option<&[u8]> { + let at = request.windows(4).position(|w| w == b"\r\n\r\n")?; + request.get(at + 4..) +} + +fn entry(name: &str, default: bool) -> spool::Printer { + spool::Printer { description: String::new(), name: name.into(), default, two_sided: None } +} + +#[test] +fn discovery_finds_queues_and_the_default_over_a_unix_socket() { + let fake = FakeCups::on_unix(vec![ + http_reply(&ipp_reply( + 0x0000, + &[ + &group(0x01), + &printer_name("Office_Laser"), + &group(0x04), + &printer_name("Office_Laser"), + &group(0x04), + &printer_name("Label_Writer"), + &group(0x04), + &printer_name("Office_Laser"), + ], + )), + http_reply(&ipp_reply(0x0000, &[&group(0x01), &group(0x04), &printer_name("Office_Laser")])), + ]) + .unwrap(); + let printers = ipp::printers_at(fake.endpoint()).unwrap(); + assert_eq!(printers, [entry("Office_Laser", true), entry("Label_Writer", false)], "each queue once, the default marked"); + let taken = fake.request().unwrap(); + let queues = ipp_body(&taken).unwrap(); + assert_eq!(&queues[..4], &[1, 1, 0x40, 0x02], "IPP 1.1, CUPS-Get-Printers"); + assert!(has(queues, b"ipp://localhost/")); + assert!(has(queues, &attr(0x44, "requested-attributes", b"printer-name"))); + assert!(has(queues, b"printer-is-accepting-jobs"), "only the attributes the dialog needs are asked for"); + let taken = fake.request().unwrap(); + let default = ipp_body(&taken).unwrap(); + assert_eq!(&default[..4], &[1, 1, 0x40, 0x01], "CUPS-Get-Default"); +} + +#[test] +fn a_print_job_carries_the_pdf_and_the_options() { + let pdf: Vec<u8> = b"%PDF-1.7 fake print job\n".iter().copied().cycle().take(1 << 20).collect(); + let job = spool::Job { + printer: Some("Office".into()), + copies: 2, + collate: false, + duplex: Some(spool::Duplex::LongEdge), + grayscale: true, + scaling: spool::Scaling::ShrinkToFit, + title: "memo.pdf".into(), + ..Job::default() + }; + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply( + 0x0000, + &[&group(0x01), &group(0x02), &attr(0x21, "job-id", &12u32.to_be_bytes()), &attr(0x23, "job-state", &[3u8])], + ))]) + .unwrap(); + let message = ipp::print_job_at(fake.endpoint(), &pdf, &job).unwrap(); + assert_eq!(message, "request id is Office-12", "the same message lp prints"); + let taken = fake.request().unwrap(); + let request = ipp_body(&taken).unwrap(); + assert_eq!(&request[..4], &[1, 1, 0x00, 0x02], "IPP 1.1, Print-Job"); + assert!(has(request, b"ipp://localhost/printers/Office")); + let mut copies = group(0x02); + copies.extend(attr(0x21, "copies", &2u32.to_be_bytes())); + assert!(has(request, &copies), "copies are a job attribute"); + assert!(has(request, &attr(0x22, "collate", &[0]))); + assert!(has(request, &attr(0x44, "sides", b"two-sided-long-edge"))); + assert!(has(request, &attr(0x44, "print-color-mode", b"monochrome"))); + assert!(has(request, &attr(0x44, "print-scaling", b"auto-fit"))); + assert!(has(request, &attr(0x49, "document-format", b"application/pdf"))); + assert!(has(request, &attr(0x42, "job-name", b"memo.pdf"))); + assert!(request.ends_with(&pdf), "the whole job is the document data"); +} + +#[test] +fn the_default_printer_is_used_when_the_job_has_none() { + let fake = FakeCups::on_tcp(vec![ + http_reply(&ipp_reply(0x0000, &[&group(0x01), &group(0x04), &printer_name("Office")])), + http_reply(&ipp_reply(0x0000, &[&group(0x01), &group(0x02), &attr(0x21, "job-id", &7u32.to_be_bytes())])), + ]) + .unwrap(); + let message = ipp::print_job_at(fake.endpoint(), b"%PDF-1.7\n", &Job::default()).unwrap(); + assert_eq!(message, "request id is Office-7"); + let default = fake.request().unwrap(); + assert_eq!(&ipp_body(&default).unwrap()[..4], &[1, 1, 0x40, 0x01], "the default comes from CUPS-Get-Default"); + let taken = fake.request().unwrap(); + assert!(has(ipp_body(&taken).unwrap(), b"ipp://localhost/printers/Office"), "the resolved default is the target"); +} + +#[test] +fn a_default_outside_the_queue_list_still_gets_its_marker() { + let fake = FakeCups::on_unix(vec![ + http_reply(&ipp_reply(0x0000, &[&group(0x01), &group(0x04), &printer_name("Office_Laser")])), + http_reply(&ipp_reply(0x0000, &[&group(0x01), &group(0x04), &printer_name("Label_Writer")])), + ]) + .unwrap(); + let printers = ipp::printers_at(fake.endpoint()).unwrap(); + assert_eq!( + printers, + [entry("Office_Laser", false), entry("Label_Writer", true)], + "the default joins the list, so the dialog has a selection to restore" + ); +} + +#[test] +fn no_default_printer_is_an_error_when_the_job_names_none() { + let fake = FakeCups::on_unix(vec![http_reply(&ipp_reply(0x0000, &[&group(0x01)]))]).unwrap(); + let err = ipp::print_job_at(fake.endpoint(), b"%PDF-1.7\n", &Job::default()).unwrap_err(); + assert!(err.to_string().contains("no default printer"), "{err}"); +} + +#[test] +fn a_printer_name_that_cannot_be_a_uri_path_is_refused() { + let fake = FakeCups::on_tcp(vec![]).unwrap(); + let mut long = "x".repeat(257); + long.push('y'); + for name in ["Office (east)", "../../admin", "", "a b", "Brother/HL", "Копир", long.as_str()] { + let job = spool::Job { printer: Some(name.into()), ..Job::default() }; + assert_eq!( + ipp::print_job_at(fake.endpoint(), b"pdf", &job), + Err(spool::Error::Spool(format!("not a printer name: {name}"))), + "{name:?} cannot go in the printer URI's path" + ); + } +} + +#[test] +fn an_ipp_refusal_is_an_error_that_names_the_problem() { + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0x0506, &[&group(0x01)]))]).unwrap(); + let job = spool::Job { printer: Some("Office".into()), ..Job::default() }; + assert_eq!( + ipp::print_job_at(fake.endpoint(), b"%PDF-1.7\n", &job), + Err(spool::Error::Spool("the print server refused the request (the printer is not accepting jobs)".into())) + ); +} + +#[test] +fn malformed_replies_are_errors_never_a_panic() { + let bodies: Vec<(&str, Vec<u8>)> = vec![ + // Shorter than an IPP header. + ("shorter than an IPP header", vec![1, 1, 0]), + // A reply that ends inside an attribute: the name is announced, the value never comes. + ("cut inside an attribute", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0x42, 0x00, 0x20, b'p']), + // A value tag the registry does not know. + ("unknown value tag", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0xFF, 0x00, 0x00, 0x00, 0x00]), + // A collection, which the attributes asked for never are. + ("collection", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0x34, 0x00, 0x00, 0x00, 0x00]), + // A group tag that is no delimiter in the registry. + ("reserved delimiter", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x06]), + // A length within the cap that runs past the reply, and one past the cap. + ("length past the reply", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0x42, 0x00, 0xFE, b'p']), + ("length past the cap", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0x42, 0xFF, 0xFF, b'p']), + // No end of attributes before the body runs out. + ("no end of attributes", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0x42, 0x00, 0x01, b'x']), + ]; + for (why, body) in bodies { + let fake = FakeCups::on_unix(vec![http_reply(&body)]).unwrap(); + let result = ipp::printers_at(fake.endpoint()); + assert!(result.is_err(), "{why}: the reply must be an error, not a panic or a success"); + } +} + +#[test] +fn http_replies_that_cannot_carry_an_answer_are_refused() { + let replies: Vec<(&str, Vec<u8>)> = vec![ + ("requires authentication", b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n".to_vec()), + ("demands a TLS upgrade", b"HTTP/1.1 426 Upgrade Required\r\nContent-Length: 0\r\n\r\n".to_vec()), + ("chunked", b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n25\r\nthe body is chunked\r\n0\r\n\r\n".to_vec()), + ("no Content-Length", b"HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\n\r\n".to_vec()), + ("Content-Length past the cap", b"HTTP/1.1 200 OK\r\nContent-Length: 99999999\r\n\r\n".to_vec()), + ("unreadable status line", b"not HTTP at all\r\n\r\n".to_vec()), + ]; + for (why, reply) in replies { + let fake = FakeCups::on_unix(vec![reply]).unwrap(); + let result = ipp::post(&[fake.server], "/", b"ignored", TIMEOUT, true); + assert!(result.is_err(), "{why}: the reply must be an error, not a panic or a success"); + } + // A server that takes the request and hangs up. + let fake = FakeCups::on_unix(vec![]).unwrap(); + assert!(ipp::post(&[fake.server], "/", b"ignored", TIMEOUT, true).is_err(), "a hang-up is an error"); +} + +#[test] +fn a_server_that_answers_is_reachable_and_silence_is_not() { + let fake = FakeCups::on_unix(vec![]).unwrap(); + assert!(ipp::reachable(&fake.server), "a unix socket that accepts connections is reachable"); + let fake = FakeCups::on_tcp(vec![]).unwrap(); + assert!(ipp::reachable(&fake.server), "a loopback port that accepts connections is reachable"); + let absent = Server::Unix("/nonexistent/craft-print-test.sock".into()); + assert!(!ipp::reachable(&absent), "a socket nothing listens on is not reachable"); + let addr = { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap() + }; + assert!(!ipp::reachable(&Server::Tcp(addr)), "a port nothing listens on is not reachable"); +} + +#[test] +fn chunked_reply_is_bounded_and_rejects_ambiguous_framing() { + let good = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n"; + assert_eq!(super::read_reply(&mut &good[..]).unwrap(), b"abcde"); + for bad in [ + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 0\r\n\r\n0\r\n\r\n".as_slice(), + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n100001\r\n", + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\na", + b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nContent-Length: 0\r\n\r\n", + ] { + assert!(super::read_reply(&mut &bad[..]).is_err()); + } +} + +#[test] +fn explicit_server_rejects_header_injection_and_malformed_port() { + for value in ["host\r\nInjected: yes", "host:0", "host:99999", "http://host", "user@host", ""] { + assert!(Server::parse(value).is_err(), "{value:?}"); + } + assert_eq!(Server::parse("[::1]:631").unwrap().authority(), "[::1]:631"); + assert_eq!(Server::parse("print.example:8631").unwrap().authority(), "print.example:8631"); +} + +#[test] +fn class_submission_preserves_authority_user_and_numeric_job_id() { + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0, &[&group(2), &attr(0x21, "job-id", &42u32.to_be_bytes())]))]).unwrap(); + let destination = super::Destination { name: "Studio".into(), is_class: true }; + assert_eq!(super::submit_as_at(fake.endpoint(), &destination, b"pdf", &Job::default(), "artist").unwrap(), 42); + let request = fake.request().unwrap(); + assert!(has(&request, b"POST /classes/Studio HTTP/1.1")); + assert!(has(&request, format!("Host: {}", fake.server.authority()).as_bytes())); + assert!(has(ipp_body(&request).unwrap(), format!("ipp://{}/classes/Studio", fake.server.authority()).as_bytes())); + assert!(has(ipp_body(&request).unwrap(), &attr(0x42, "requesting-user-name", b"artist"))); +} + +#[test] +fn uncertain_submission_never_tries_the_second_endpoint() { + let first = FakeCups::on_tcp(vec![]).unwrap(); + let second = FakeCups::on_tcp(vec![]).unwrap(); + let destination = super::Destination { name: "Studio".into(), is_class: false }; + assert!(super::submit_at(&[first.server.clone(), second.server.clone()], &destination, b"pdf", &Job::default()).is_err()); + let _ = first.request().unwrap(); + assert!(second.requests.recv_timeout(Duration::from_millis(100)).is_err()); +} + +#[test] +fn queue_metadata_stays_with_its_printer_group() { + let bytes = ipp_reply( + 0, + &[ + &group(4), + &attr(0x41, "printer-info", b"Studio printer"), + &printer_name("First"), + &attr(0x23, "printer-state", &5u32.to_be_bytes()), + &attr(0x22, "printer-is-accepting-jobs", &[0]), + &group(4), + &printer_name("Second"), + ], + ); + let reply = super::parse_reply(&bytes).unwrap(); + assert_eq!(reply.queues.len(), 2); + assert_eq!(reply.queues[0].info, "Studio printer"); + assert_eq!(reply.queues[0].state, 5); + assert!(!reply.queues[0].accepting_jobs); + assert!(reply.queues[1].info.is_empty()); + assert!(reply.queues[1].accepting_jobs); +} + +#[test] +fn reply_identity_and_metadata_request_are_checked() { + let request = super::discovery_request(0x4002); + assert!(has(&request, b"printer-info")); + let mut reply = vec![1, 1, 0, 0]; + reply.extend_from_slice(&request[4..8]); + reply.push(3); + assert!(super::validate_reply_identity(&request, &reply).is_ok()); + reply[7] ^= 1; + assert!(super::validate_reply_identity(&request, &reply).is_err()); + reply[4..8].copy_from_slice(&request[4..8]); + reply[0] = 9; + assert!(super::validate_reply_identity(&request, &reply).is_err()); +} + +#[test] +fn slow_reply_cannot_reset_the_absolute_deadline() { + let (client, mut peer) = std::os::unix::net::UnixStream::pair().unwrap(); + let producer = std::thread::spawn(move || { + // Finite work and a joined handle: no abandoned timeout worker. + for _ in 0..20 { + if peer.write_all(b"x").is_err() { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + }); + let start = std::time::Instant::now(); + let mut stream = super::Stream::Unix(client); + let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let mut bytes = [0; 20]; + assert!(reader.read_exact(&mut bytes).is_err(), "trickle reads must not extend the absolute deadline"); + drop(stream); + producer.join().unwrap(); + assert!(start.elapsed() < Duration::from_secs(3)); +} + +#[test] +fn blocked_upload_obeys_the_same_absolute_deadline() { + let (client, _peer) = std::os::unix::net::UnixStream::pair().unwrap(); + let start = std::time::Instant::now(); + let mut stream = super::Stream::Unix(client); + let mut writer = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let chunk = [0u8; 64 * 1024]; + let mut timed_out = false; + // A peer that never drains cannot turn each partial write into a fresh timeout budget. + for _ in 0..512 { + if writer.write_all(&chunk).is_err() { + timed_out = true; + break; + } + } + assert!(timed_out, "blocked upload must terminate without a reader"); + assert!(start.elapsed() < Duration::from_secs(3)); +} + +#[test] +fn recorded_request_body_requires_complete_http_headers() { + assert!(ipp_body(b"POST / HTTP/1.1\r\n").is_none()); + assert_eq!(ipp_body(b"POST / HTTP/1.1\r\n\r\nbody"), Some(b"body".as_slice())); +} + +#[test] +fn named_destinations_encode_one_path_segment_on_both_wire_fields() { + for is_class in [false, true] { + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0, &[&group(2), &attr(0x21, "job-id", &42u32.to_be_bytes())]))]).unwrap(); + let destination = super::Destination { name: "Office café%20?#".into(), is_class }; + assert_eq!(super::submit_as_at(fake.endpoint(), &destination, b"pdf", &Job::default(), "artist").unwrap(), 42); + let kind = if is_class { "classes" } else { "printers" }; + let path = format!("/{kind}/Office%20caf%C3%A9%2520%3F%23"); + let request = fake.request().unwrap(); + assert!(has(&request, format!("POST {path} HTTP/1.1").as_bytes())); + assert!(has(ipp_body(&request).unwrap(), format!("ipp://{}{path}", fake.server.authority()).as_bytes())); + } +} + +#[test] +fn destination_path_rejects_routing_syntax_before_connecting() { + for name in ["", ".", "..", "../admin", "a/b", "a\\b", "a\r\nb", "a\0b"] { + let destination = super::Destination { name: name.into(), is_class: false }; + assert!(super::destination_path(&destination).is_err(), "{name:?}"); + } + let destination = super::Destination { name: "x".repeat(257), is_class: false }; + assert!(super::destination_path(&destination).is_err()); +} + +#[test] +fn separate_queue_query_preserves_optional_discovery_errors() { + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0x0403, &[&group(1)]))]).unwrap(); + assert!(super::queues_at(fake.endpoint(), true).is_err(), "authorization refusal is not an empty class list"); + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0x0501, &[&group(1)]))]).unwrap(); + assert!(super::queues_at(fake.endpoint(), true).unwrap().is_empty(), "unsupported class operation is absent"); + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0, &[&group(1), &group(4), &printer_name("Pool")]))]).unwrap(); + let queues = super::queues_at(fake.endpoint(), true).unwrap(); + assert_eq!(queues.len(), 1); + assert!(queues[0].is_class); + assert!(!queues[0].is_default, "default resolution is caller-owned for this API"); + let request = fake.request().unwrap(); + assert_eq!(&ipp_body(&request).unwrap()[..4], &[1, 1, 0x40, 0x05]); +} + +#[test] +fn ipv6_endpoint_keeps_scope_for_resolution_and_escapes_wire_authority() { + assert_eq!(Server::parse("[::1]").unwrap().authority(), "[::1]:631"); + assert_eq!(Server::parse("::1").unwrap().authority(), "[::1]:631"); + let scoped = Server::parse("[fe80::1%en0]:8631").unwrap(); + assert!(matches!(&scoped, Server::Named(host, 8631) if host == "fe80::1%en0")); + assert_eq!(scoped.authority(), "[fe80::1%25en0]:8631"); + assert_eq!(Server::parse("fe80::1%en0:8631").unwrap().authority(), scoped.authority()); + assert_eq!(Server::parse("fe80::1%en0").unwrap().authority(), "[fe80::1%25en0]:631"); + assert!(Server::parse("[host]:631").is_err()); + assert_eq!(super::connect(&Server::Named("/invalid".into(), 631)).err().unwrap().kind(), std::io::ErrorKind::InvalidInput); + for bad in ["[::1]junk", "[::1]:0", "[::1]:abc", "[fe80::1%]:631", "[fe80::1%x%y]:631", "host%zone"] { + assert!(Server::parse(bad).is_err(), "{bad}"); + } +} + +#[test] +fn long_printer_descriptions_are_not_limited_like_queue_names() { + let description = "Studio ".repeat(200); + let body = ipp_reply(0, &[&group(1), &group(4), &printer_name("Studio"), &attr(0x41, "printer-info", description.as_bytes())]); + let parsed = super::parse_reply(&body).unwrap(); + assert_eq!(parsed.queues[0].info, description); +} + +#[test] +fn destination_limit_is_explicit_and_never_silently_truncates() { + let mut body = vec![1, 1, 0, 0, 0, 0, 0, 1]; + for index in 0..super::MAX_PRINTERS { + body.push(4); + body.extend(printer_name(&format!("Printer{index}"))); + } + body.push(3); + assert_eq!(super::parse_reply(&body).unwrap().queues.len(), super::MAX_PRINTERS); + assert_eq!(body.pop(), Some(3)); + body.push(4); + body.extend(printer_name("OneTooMany")); + body.push(3); + assert!(super::parse_reply(&body).err().unwrap().to_string().contains("too many CUPS destinations")); +} + +#[test] +fn closed_unix_peer_keeps_its_buffered_reply_readable_with_a_deadline() { + let (client, mut peer) = std::os::unix::net::UnixStream::pair().unwrap(); + let body = ipp_reply(0, &[&group(1), &group(4), &printer_name("Studio")]); + peer.write_all(&http_reply(&body)).unwrap(); + drop(peer); + let mut stream = super::Stream::Unix(client); + let mut reader = super::DeadlineReader { stream: &mut stream, end: std::time::Instant::now() + Duration::from_secs(1) }; + assert_eq!(super::read_reply(&mut reader).unwrap(), body); + let mut byte = [0]; + assert_eq!(reader.read(&mut byte).unwrap(), 0); + reader.end = std::time::Instant::now(); + assert_eq!(reader.read(&mut byte).unwrap_err().kind(), std::io::ErrorKind::TimedOut); +} + +#[test] +fn stalled_unix_peer_still_fails_within_the_absolute_read_deadline() { + let (client, _peer) = std::os::unix::net::UnixStream::pair().unwrap(); + let start = std::time::Instant::now(); + let mut stream = super::Stream::Unix(client); + let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let mut byte = [0]; + let error = reader.read(&mut byte).unwrap_err(); + assert!(matches!(error.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock)); + assert!(start.elapsed() < Duration::from_secs(3)); +} diff --git a/crates/print/src/lib.rs b/crates/print/src/lib.rs index dcc9c53f9..bf50e3a3f 100644 --- a/crates/print/src/lib.rs +++ b/crates/print/src/lib.rs @@ -8,6 +8,10 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +/// Direct local-CUPS transport, independent of command-line spooler selection. +#[cfg(not(target_arch = "wasm32"))] +pub mod cups; + #[cfg(any(test, windows))] mod progress; #[cfg(any(test, windows))] diff --git a/crates/print/src/sheets.rs b/crates/print/src/sheets.rs index 0f013478b..fa95d11c4 100644 --- a/crates/print/src/sheets.rs +++ b/crates/print/src/sheets.rs @@ -1136,6 +1136,21 @@ pub(crate) fn plan(sheets: &[Sheet], paper: (f64, f64), fit: Fit) -> Result<Vec< if scale >= 1.0 && close((w, h), paper) { None } else { + // The matrix is written with at most four decimals and a PDF real has no + // exponent, so a scale that rounds away prints nothing at all and one that + // rounds up prints the wrong size. Refuse both, the way a nondefault + // UserUnit is refused: an error, never a job that spools a blank page. + let written = number(scale).parse::<f64>().unwrap_or(0.0); + if written <= 0.0 || (written - scale).abs() > scale * 0.01 { + return Err(Error::Spool(format!( + "shrink to fit cannot place sheet {} ({:.2} x {:.2} in) on the {:.2} x {:.2} in paper; nothing was sent", + i + 1, + w / 72.0, + h / 72.0, + pw / 72.0, + ph / 72.0 + ))); + } let [x0, y0, x1, y1] = sheet.bounds; let (cw, ch) = (x1 - x0, y1 - y0); // The paper in the page's unrotated space. diff --git a/crates/print/src/tests/windows_native.rs b/crates/print/src/tests/windows_native.rs index 7882a0578..12c480f22 100644 --- a/crates/print/src/tests/windows_native.rs +++ b/crates/print/src/tests/windows_native.rs @@ -555,3 +555,42 @@ fn windows_jobs_reach_the_spooler() { let missing = spool::submit(&mixed, &Job { printer: Some(name.into()), ..Job::default() }); assert!(matches!(missing, Err(Error::Spool(ref m)) if m.contains(name)), "{missing:?}"); } + +#[test] +fn shrink_to_fit_refuses_a_sheet_the_output_cannot_represent() { + use crate::sheets::{Fit, plan, read}; + // A runaway-zoom export: 16 000 000 pt wide. Written with four decimals the scale would be + // "0" -- a singular matrix, a blank page, reported back as a spooled job. + let huge = TestPage { media: Some([0.0, 0.0, 16_000_000.0, 792.0]), ..LETTER }; + let pdf = test_pdf(&[huge], false); + let sheets = read(&pdf).unwrap(); + let refused = plan(&sheets.sheets, (612.0, 792.0), Fit::Shrink { margin: 18.0 }); + assert!(matches!(refused, Err(Error::Spool(ref m)) if m.contains("shrink")), "{refused:?}"); +} + +#[test] +fn shrink_to_fit_holds_the_one_percent_scale_boundary() { + use crate::sheets::{Fit, plan, read}; + // The matrix carries the scale through the four-decimal formatter, so the plan refuses when + // what would be written is more than 1% off the real scale. Letter with an 18 pt margin gives + // 576 pt of printable width: a 118 700 pt wide, 120 000 pt tall sheet (no quarter turn) scales + // by 576 / 118 700 = 0.00485257, written 0.0049 -- 0.98% short, inside the bound, so it + // prints. + let inside = TestPage { media: Some([0.0, 0.0, 118_700.0, 120_000.0]), ..LETTER }; + let pdf = test_pdf(&[inside], false); + let sheets = read(&pdf).unwrap(); + let edits = plan(&sheets.sheets, (612.0, 792.0), Fit::Shrink { margin: 18.0 }).unwrap(); + let updated = sheets.update(&edits).unwrap(); + let frame = frame_of(&updated, pdf.len()); + let written: f64 = frame.split_whitespace().nth(1).unwrap().parse().unwrap(); + let real = edits[0].frame.as_ref().unwrap().matrix[0]; + assert!(written != real && (written - real).abs() < real * 0.01, "just inside the 1% bound the written scale is accepted: {frame}"); + + // A 118 750 pt wide sheet: 576 / 118 750 = 0.00485053, written 0.0049, 1.02% off -- refused as + // an error before anything is sent, rather than printed a percent too small. + let outside = TestPage { media: Some([0.0, 0.0, 118_750.0, 120_000.0]), ..LETTER }; + let pdf = test_pdf(&[outside], false); + let sheets = read(&pdf).unwrap(); + let refused = plan(&sheets.sheets, (612.0, 792.0), Fit::Shrink { margin: 18.0 }); + assert!(matches!(refused, Err(Error::Spool(ref m)) if m.contains("shrink") && m.contains("nothing was sent")), "{refused:?}"); +} diff --git a/crates/print/src/ticket.rs b/crates/print/src/ticket.rs index ddf2c3955..e6224df69 100644 --- a/crates/print/src/ticket.rs +++ b/crates/print/src/ticket.rs @@ -197,11 +197,24 @@ pub(crate) fn paper_names(width: f64, height: f64) -> &'static [&'static str] { } /// Whether a driver's paper name is `name`: it starts with it, ignoring case, and the name ends -/// there ("A4 210 x 297 mm", not "A4 Extra" for "A4" or "ARCH E1" for "ARCH E"). +/// there — either nothing follows ("arch d"), or a separator and the sheet's dimensions ("A4 +/// 210 x 297 mm"). After a separator, dimensions are a digit: a word is a modifier, another +/// paper ("A4 Extra", "A4 (Extra)"), and anything joined to the name without a separator is +/// another paper too ("A4Extra", "ARCH E1" for "ARCH E"). pub(crate) fn names_paper(display: Option<&str>, name: &str) -> bool { let Some(display) = display else { return false }; - display.get(..name.len()).is_some_and(|start| start.eq_ignore_ascii_case(name)) - && display.get(name.len()..).is_some_and(|rest| rest.chars().next().is_none_or(|c| !c.is_alphanumeric())) + let Some(rest) = display.get(name.len()..) else { return false }; + if !display.get(..name.len()).is_some_and(|start| start.eq_ignore_ascii_case(name)) { + return false; + } + let after = rest.trim_start_matches(|c: char| !c.is_alphanumeric()); + match after.chars().next() { + // The name ends here, or a separator introduces the sheet's dimensions. + None => true, + Some(c) if !c.is_alphabetic() => after.len() < rest.len(), + // A word, directly after the name or after a separator, is a modifier: another paper. + Some(_) => false, + } } /// A driver paper offered for the job: its size in micrometres (as the driver lists it), its @@ -218,6 +231,17 @@ pub(crate) struct Paper<'a> { /// The driver paper for a sheet of `width` × `height` points (either way round): within a /// quarter of a millimetre, preferring the one named like the standard size, then a Print Schema /// keyword, then the closest; on a tie the driver's own order. Its index in `papers`. +/// +/// An entry the driver keeps only one side of (the other reads zero, a legacy host-based driver's +/// DEVMODE metric, storytold/craft-libs#7230) is a candidate of last resort (INV-4): only when no +/// full entry matched, only a Print Schema keyword entry, and only while its known side agrees +/// with the sheet, either way round. A single such entry is still refused when its own name is +/// known and contradicts the requested standard sheet (INV-4): a known conflicting name is +/// evidence against the choice, and failing closed is safer than a guess. Without a name there is +/// nothing contradicting, so the agreement alone is enough. Several such entries that all agree +/// (a Letter and a Legal option share a width) are told apart by name, as full candidates are: +/// the one named like the requested standard sheet wins, and when that leaves more than one, or +/// none, nothing is chosen — a guess here would lay the sheets out for the wrong paper. pub(crate) fn matching_paper(papers: &[Paper<'_>], width: f64, height: f64) -> Option<usize> { let (w, h) = (micrometres(width.min(height))?, micrometres(width.max(height))?); let names = paper_names(width, height); @@ -231,7 +255,33 @@ pub(crate) fn matching_paper(papers: &[Paper<'_>], width: f64, height: f64) -> O }) .collect(); candidates.sort_by_key(|(_, p, off)| (!names.iter().any(|n| names_paper(p.name, n)), !p.keyword, *off)); - candidates.first().map(|(i, _, _)| *i) + if let Some(index) = candidates.first().map(|(i, _, _)| *i) { + return Some(index); + } + let agrees = |side: u32| side.abs_diff(w) <= PAPER_TOLERANCE || side.abs_diff(h) <= PAPER_TOLERANCE; + let partials: Vec<usize> = papers + .iter() + .enumerate() + .filter(|(_, p)| p.keyword && (p.width == 0) != (p.height == 0) && (p.width == 0 || agrees(p.width)) && (p.height == 0 || agrees(p.height))) + .map(|(i, _)| i) + .collect(); + match partials.as_slice() { + [only] => { + // INV-4: a known name that contradicts the requested standard sheet is evidence + // against this single partial record — refuse it; without a name, the known side's + // agreement is all the evidence there is, and the record stands. + let contradicts = papers[*only].name.is_some_and(|name| !names.iter().any(|n| names_paper(Some(name), n))); + (!contradicts).then_some(*only) + } + // Ambiguous by agreement alone: a partial named like the requested standard sheet wins. + _ => { + let named: Vec<usize> = partials.iter().copied().filter(|i| names.iter().any(|n| names_paper(papers[*i].name, n))).collect(); + match named.as_slice() { + [only] => Some(*only), + _ => None, + } + } + } } fn named(node: roxmltree::Node<'_, '_>, local: &str) -> bool { @@ -274,12 +324,32 @@ pub(crate) fn two_sided(xml: &str) -> Option<bool> { ) } -/// The integer value of the Print Schema element under `node` with this keyword name. -fn integer(node: roxmltree::Node<'_, '_>, tag: &str, name: &str) -> Option<u32> { +/// The `Value` of the Print Schema element `element`: its own, or one a `ParameterRef` names +/// through the `ParameterInit` under the document's root that sets it (a driver may keep a paper +/// side or a resolution this way). `None` when the element has neither, or names a parameter the +/// ticket does not set. +fn resolved_value<'a>(document: &'a roxmltree::Document<'a>, element: roxmltree::Node<'a, 'a>) -> Option<roxmltree::Node<'a, 'a>> { + let value = element.children().find(|v| v.has_tag_name((NS_PSF, "Value")) || v.has_tag_name((NS_PSF, "ParameterRef")))?; + if value.has_tag_name((NS_PSF, "Value")) { + return Some(value); + } + let parameter = expanded(value, value.attribute("name")?); + document + .root_element() + .children() + .filter(|p| p.has_tag_name((NS_PSF, "ParameterInit"))) + .find(|p| p.attribute("name").is_some_and(|name| expanded(*p, name) == parameter))? + .children() + .find(|v| v.has_tag_name((NS_PSF, "Value"))) +} + +/// The integer value of the Print Schema element under `node` with this keyword name, direct or +/// through a `ParameterRef` the ticket resolves ([`resolved_value`]). +fn integer(document: &roxmltree::Document<'_>, node: roxmltree::Node<'_, '_>, tag: &str, name: &str) -> Option<u32> { node.descendants() .find(|n| n.has_tag_name((NS_PSF, tag)) && named(*n, name)) - .and_then(|n| n.children().find(|v| v.has_tag_name((NS_PSF, "Value")))) - .and_then(|n| n.text()) + .and_then(|element| resolved_value(document, element)) + .and_then(|value| value.text()) .and_then(|v| v.trim().parse::<u32>().ok()) } @@ -287,14 +357,35 @@ fn integer(node: roxmltree::Node<'_, '_>, tag: &str, name: &str) -> Option<u32> /// paper (when `paper` is given, that one, to a quarter of a millimetre). Returns the paper's /// width and height in micrometres as the driver lists it. Only those schema fields are read: /// some drivers return empty vendor parameters that a stricter parser would refuse. +/// +/// A zero or unreadable side (`MediaSizeWidth` gone) is roll-like only while the request itself +/// names no sheet (INV-2): a legacy host-based driver keeps the paper metric in its DEVMODE +/// extension and reads back a zero side for a real sheet (HP LaserJet P1102, storytold/craft-libs#7230), so +/// with a sheet named the job falls back to the size the request asked for (INV-1, +/// fail-closed: every refusal here is before anything reaches the spooler). A side the driver +/// did report must agree with the sheet asked for, either way round (INV-3); both sides gone is +/// refused whatever the request names (INV-5). The fallback is logged (INV-7). pub(crate) fn verify_ticket(xml: &str, paper: Option<(u32, u32)>, landscape: bool) -> Result<(u32, u32), Error> { let document = crate::xml::parse(xml).map_err(spool_error)?; let feature = |name: &str| document.root_element().children().find(|n| n.has_tag_name((NS_PSF, "Feature")) && named(*n, name)); let media = feature("PageMediaSize").ok_or_else(|| spool_error("the printer's driver did not confirm the paper size; nothing was sent"))?; - let size = integer(media, "ScoredProperty", "MediaSizeWidth") - .zip(integer(media, "ScoredProperty", "MediaSizeHeight")) - .filter(|(w, h)| *w > 0 && *h > 0) - .ok_or_else(|| spool_error("the printer's driver gave a paper without a size (a roll?); nothing was sent"))?; + let width = integer(&document, media, "ScoredProperty", "MediaSizeWidth").filter(|w| *w > 0); + let height = integer(&document, media, "ScoredProperty", "MediaSizeHeight").filter(|h| *h > 0); + let without_a_size = spool_error("the printer's driver gave a paper without a size (a roll?); nothing was sent"); + let size = match (width, height, paper) { + (Some(w), Some(h), _) => (w, h), + (None, None, _) | (_, _, None) => return Err(without_a_size), + (Some(reported), None, Some(wanted)) | (None, Some(reported), Some(wanted)) => { + let (w, h) = wanted; + // Either way round: the one side the driver did report against the sheet's width or height. + let agrees = |other: u32| reported.abs_diff(other) <= PAPER_TOLERANCE; + if !agrees(w) && !agrees(h) { + return Err(spool_error("the printer's driver changed the paper size; nothing was sent (choose a paper size it has)")); + } + log::warn!("the printer's driver reported only {reported} µm of the paper; going on with the requested {w} × {h} µm"); + (w, h) + } + }; if let Some((w, h)) = paper { let same = |a: (u32, u32), b: (u32, u32)| a.0.abs_diff(b.0) <= PAPER_TOLERANCE && a.1.abs_diff(b.1) <= PAPER_TOLERANCE; if !same(size, (w, h)) && !same(size, (h, w)) { @@ -384,7 +475,9 @@ pub(crate) fn one_job_sides(xml: &str) -> Option<bool> { _ => return None, } } - if features(&["JobNUpAllDocumentsContiguously", "DocumentNUp"]).any(|f| integer(f, "ScoredProperty", "PagesPerSheet").is_some_and(|n| n > 1)) { + if features(&["JobNUpAllDocumentsContiguously", "DocumentNUp"]) + .any(|f| integer(&document, f, "ScoredProperty", "PagesPerSheet").is_some_and(|n| n > 1)) + { return None; } if features(&["JobBindAllDocuments", "DocumentBinding", "JobStapleAllDocuments", "DocumentStaple"]) @@ -421,7 +514,7 @@ pub(crate) fn verify_job_options(xml: &str, job: &Job, pages: usize, offered: Of }; let refused = |field: &str| spool_error(format!("the printer's driver did not retain the requested {field}; nothing was sent")); let copies = job.copies.clamp(1, 999); - if integer(root, "ParameterInit", "JobCopiesAllDocuments") != Some(copies) { + if integer(&document, root, "ParameterInit", "JobCopiesAllDocuments") != Some(copies) { return Err(refused("copy count")); } if copies > 1 && pages > 1 && !option("DocumentCollate").is_some_and(|n| named(n, if job.collate { "Collated" } else { "Uncollated" })) { @@ -497,19 +590,7 @@ fn feature_option(document: &roxmltree::Document<'_>, feature: &str) -> Option<F .children() .filter(|n| n.has_tag_name((NS_PSF, "ScoredProperty"))) .filter_map(|n| { - let value = match n.children().find(|v| v.has_tag_name((NS_PSF, "Value")) || v.has_tag_name((NS_PSF, "ParameterRef")))? { - value if value.has_tag_name((NS_PSF, "Value")) => value, - reference => { - let parameter = expanded(reference, reference.attribute("name")?); - document - .root_element() - .children() - .filter(|p| p.has_tag_name((NS_PSF, "ParameterInit"))) - .find(|p| p.attribute("name").is_some_and(|name| expanded(*p, name) == parameter))? - .children() - .find(|v| v.has_tag_name((NS_PSF, "Value")))? - } - }; + let value = resolved_value(document, n)?; let text = value.text()?.trim(); let value = match text.parse::<i64>() { _ if is_qname_value(value) => expanded(value, text), @@ -766,11 +847,11 @@ pub(crate) fn prefixes_unlike_the_drivers(ticket: &str, driver: &str) -> Option< pub(crate) fn imageable_margin(capabilities_xml: &str) -> Option<u32> { let document = crate::xml::parse(capabilities_xml).ok()?; let imageable = document.root_element().children().find(|n| n.has_tag_name((NS_PSF, "Property")) && named(*n, "PageImageableSize"))?; - let width = integer(imageable, "Property", "ImageableSizeWidth")?; - let height = integer(imageable, "Property", "ImageableSizeHeight")?; + let width = integer(&document, imageable, "Property", "ImageableSizeWidth")?; + let height = integer(&document, imageable, "Property", "ImageableSizeHeight")?; let area = imageable.children().find(|n| n.has_tag_name((NS_PSF, "Property")) && named(*n, "ImageableArea"))?; - let (x, y) = (integer(area, "Property", "OriginWidth")?, integer(area, "Property", "OriginHeight")?); - let (w, h) = (integer(area, "Property", "ExtentWidth")?, integer(area, "Property", "ExtentHeight")?); + let (x, y) = (integer(&document, area, "Property", "OriginWidth")?, integer(&document, area, "Property", "OriginHeight")?); + let (w, h) = (integer(&document, area, "Property", "ExtentWidth")?, integer(&document, area, "Property", "ExtentHeight")?); let right = width.checked_sub(x)?.checked_sub(w)?; let bottom = height.checked_sub(y)?.checked_sub(h)?; Some(x.max(y).max(right).max(bottom)) @@ -1058,6 +1139,89 @@ mod tests { assert!(verify_ticket("<not xml", Some(letter), false).is_err()); } + /// A validated ticket that keeps only the sides its DEVMODE extension could read, as a legacy + /// host-based driver (HP LaserJet P1102, storytold/craft-libs#7230) returns one. + fn validated_partial(width: Option<u32>, height: Option<u32>) -> String { + let side = |name: &str, value: Option<u32>| { + value.map_or(String::new(), |v| { + format!(r#"<psf:ScoredProperty name="psk:{name}"><psf:Value xsi:type="xsd:integer">{v}</psf:Value></psf:ScoredProperty>"#) + }) + }; + format!( + r#"<psf:PrintTicket version="1" xmlns:psf="{NS_PSF}" xmlns:psk="{NS_PSK}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> +<psf:Feature name="psk:PageMediaSize"><psf:Option name="psk:ISOA4">{}{}</psf:Option></psf:Feature> +<psf:Feature name="psk:PageOrientation"><psf:Option name="psk:Portrait"/></psf:Feature> +<psf:Feature name="psk:PageScaling"><psf:Option name="psk:None"/></psf:Feature> +</psf:PrintTicket>"#, + side("MediaSizeWidth", width), + side("MediaSizeHeight", height) + ) + } + + /// storytold/craft-libs#7230: the driver reports one side of the paper as zero for a real + /// sheet. With the sheet the request names, the job goes on with the size it asked for; a + /// side the driver did report must still agree with it, and a request that names no sheet is + /// refused as before. + #[test] + fn a_legacy_v3_drivers_zero_side_falls_back_to_the_requested_paper() { + let a4 = (210_000, 297_000); + assert_eq!(verify_ticket(&validated_partial(None, Some(297_000)), Some(a4), false), Ok(a4)); + assert_eq!(verify_ticket(&validated_partial(Some(0), Some(297_000)), Some(a4), false), Ok(a4), "a zero side is a missing one"); + assert_eq!(verify_ticket(&validated_partial(Some(297_000), None), Some(a4), false), Ok(a4), "either way round"); + // 0.5 pt (176 µm) inside the tolerance still agrees. + assert_eq!(verify_ticket(&validated_partial(Some(0), Some(297_176)), Some(a4), false), Ok(a4)); + assert_eq!(verify_ticket(&validated_partial(Some(0), Some(297_250)), Some(a4), false), Ok(a4), "exactly the tolerance"); + // A side that disagrees means the driver changed the paper, not that it has a roll. + let changed = verify_ticket(&validated_partial(Some(0), Some(279_400)), Some(a4), false).unwrap_err(); + assert!(changed.to_string().contains("changed the paper size"), "{changed}"); + assert!(!changed.to_string().contains("roll"), "{changed}"); + assert!(verify_ticket(&validated_partial(Some(0), Some(297_251)), Some(a4), false).is_err(), "one µm past the tolerance"); + // Without a sheet named the zero side stays roll-like. + assert!(verify_ticket(&validated_partial(Some(0), Some(297_000)), None, false).is_err()); + assert!(verify_ticket(&validated_partial(None, Some(297_000)), None, false).is_err()); + // Both sides gone is refused whatever the request names. + for wanted in [Some(a4), None] { + for (width, height) in [(None, None), (Some(0), Some(0))] { + let refused = verify_ticket(&validated_partial(width, height), wanted, false).unwrap_err(); + assert!(refused.to_string().contains("roll"), "{refused}"); + } + } + } + + /// A validated ticket whose width the option refers to a parameter the ticket sets + /// (`MediaSizeWidth` a `ParameterRef`, storytold/craft-libs#1225), as a driver writes one. + fn validated_referenced(width: u32, height: u32) -> String { + format!( + r#"<psf:PrintTicket version="1" xmlns:psf="{NS_PSF}" xmlns:psk="{NS_PSK}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> +<psf:ParameterInit name="psk:PageMediaSizeWidth"><psf:Value xsi:type="xsd:integer">{width}</psf:Value></psf:ParameterInit> +<psf:Feature name="psk:PageMediaSize"><psf:Option name="psk:ISOA4"> +<psf:ScoredProperty name="psk:MediaSizeWidth"><psf:ParameterRef name="psk:PageMediaSizeWidth"/></psf:ScoredProperty> +<psf:ScoredProperty name="psk:MediaSizeHeight"><psf:Value xsi:type="xsd:integer">{height}</psf:Value></psf:ScoredProperty> +</psf:Option></psf:Feature> +<psf:Feature name="psk:PageOrientation"><psf:Option name="psk:Portrait"/></psf:Feature> +<psf:Feature name="psk:PageScaling"><psf:Option name="psk:None"/></psf:Feature> +</psf:PrintTicket>"# + ) + } + + /// A paper side a driver keeps in a `ParameterRef` is resolved through the `ParameterInit` + /// the ticket sets, and checked like a direct one: a referenced width that disagrees with the + /// sheet the request names is refused, one that agrees is taken. + #[test] + fn a_referenced_paper_side_is_resolved_through_the_parameter_it_names() { + let a4 = (210_000, 297_000); + assert_eq!(verify_ticket(&validated_referenced(210_000, 297_000), Some(a4), false), Ok(a4)); + assert_eq!(verify_ticket(&validated_referenced(209_750, 297_000), Some(a4), false), Ok((209_750, 297_000)), "exactly the tolerance"); + // A referenced size that disagrees is refused, not rewritten from the request. + let changed = verify_ticket(&validated_referenced(400_000, 297_000), Some(a4), false).unwrap_err(); + assert!(changed.to_string().contains("changed the paper size"), "{changed}"); + // A reference to a parameter the ticket does not set is a missing side, which falls back + // to the requested paper like any unreadable one. + let unset = + validated_referenced(400_000, 297_000).replace(r#"name="psk:PageMediaSizeWidth"><psf:Value"#, r#"name="psk:OtherParameter"><psf:Value"#); + assert_eq!(verify_ticket(&unset, Some(a4), false), Ok(a4), "a parameter the ticket does not set is a missing side"); + } + /// The namespace of the Brother driver's own keywords. const BROTHER: &str = "http://schemas.brother.info/mfc/printing/2006/11/printschemakeywords"; @@ -1544,10 +1708,83 @@ mod tests { assert!(!names_paper(Some("ANSI D"), "ARCH D")); assert!(!names_paper(Some("ARCH E1"), "ARCH E")); assert!(!names_paper(Some("A4Extra"), "A4")); + // storytold/craft-libs#1225: a word after a separator is a modifier, not dimensions. + assert!(!names_paper(Some("A4 Extra"), "A4")); + assert!(!names_paper(Some("A4 (Extra)"), "A4")); + assert!(names_paper(Some("A4 210 x 297 mm"), "A4")); assert!(!names_paper(Some("Ä"), "A4"), "never slices inside a character"); assert!(!names_paper(None, "A4")); } + /// A paper the driver keeps one side of (storytold/craft-libs#7230) is a candidate of last + /// resort only: no full entry matched, a Print Schema keyword entry, and its known side + /// agrees with the sheet. + #[test] + fn a_partially_known_paper_is_a_candidate_of_last_resort_only() { + let paper = |width, height, name, keyword| Paper { width, height, name, keyword }; + let partial = paper(0, 297_000, Some("A4"), true); + let alone = [partial.clone()]; + assert_eq!(matching_paper(&alone, 595.28, 841.89), Some(0), "no full entry: the partial one is taken"); + // A full candidate, however it spells its option, wins over the partial one. + let with_full = [partial, paper(210_100, 297_000, Some("A4"), false)]; + assert_eq!(matching_paper(&with_full, 595.28, 841.89), Some(1), "the full entry wins"); + // A vendor's own entry is no partial candidate. + assert_eq!(matching_paper(&[paper(0, 297_000, Some("A4"), false)], 595.28, 841.89), None); + // A partial entry whose known side disagrees is no candidate. + assert_eq!(matching_paper(&[paper(0, 279_400, Some("Letter"), true)], 595.28, 841.89), None); + // Both sides gone: nothing known to agree with. + assert_eq!(matching_paper(&[paper(0, 0, Some("A4"), true)], 595.28, 841.89), None); + } + + /// One partial paper whose known side agrees is still taken, named like the requested + /// standard sheet or not. The known side agrees only to a quarter of a millimetre: exactly + /// the tolerance is taken, one micrometre past it is another paper. + #[test] + fn a_single_partially_known_paper_that_agrees_is_still_taken() { + let paper = |width, height, name, keyword| Paper { width, height, name, keyword }; + assert_eq!(matching_paper(&[paper(215_900, 0, Some("Legal 215.9 x 355.6 mm"), true)], 612.0, 1008.0), Some(0), "named like the sheet"); + assert_eq!(matching_paper(&[paper(215_900, 0, None, true)], 612.0, 1008.0), Some(0), "or without a name at all"); + assert_eq!(matching_paper(&[paper(0, 297_250, None, true)], 595.28, 841.89), Some(0), "exactly the tolerance"); + assert_eq!(matching_paper(&[paper(0, 297_251, None, true)], 595.28, 841.89), None, "one µm past the tolerance"); + } + + /// storytold/craft-libs#1225 (Code Rabbit, second round): a single partial paper whose known + /// side agrees is still refused when its own name is known and contradicts the requested + /// standard sheet — the width the driver kept is shared by Letter and Legal, and a known + /// Letter name is evidence against choosing it for a Legal sheet (INV-4). "Extra" is a + /// modifier word, another paper: a known "Letter Extra" name contradicts a Letter sheet too. + /// Without a name there is nothing contradicting, and the agreeing entry is taken as before. + #[test] + fn a_single_partially_known_paper_whose_known_name_contradicts_the_sheet_is_refused() { + let paper = |width, height, name, keyword| Paper { width, height, name, keyword }; + assert_eq!( + matching_paper(&[paper(215_900, 0, Some("Letter 215.9 x 279.4 mm"), true)], 612.0, 1008.0), + None, + "a known Letter name is not a Legal sheet" + ); + assert_eq!( + matching_paper(&[paper(215_900, 0, Some("Letter Extra 215.9 x 431.8 mm"), true)], 612.0, 792.0), + None, + "a known \"Letter Extra\" name is not a Letter sheet" + ); + assert_eq!(matching_paper(&[paper(215_900, 0, None, true)], 612.0, 1008.0), Some(0), "an unnamed twin stands, the agreement alone"); + } + + /// storytold/craft-libs#1225: two partial papers that both agree (Letter and Legal share a + /// width) are told apart by name, as full candidates are; when nothing tells them apart, + /// none is chosen, not the first one that agrees. + #[test] + fn two_partially_known_papers_that_agree_are_told_apart_by_their_names() { + let paper = |width, height, name, keyword| Paper { width, height, name, keyword }; + let both = [paper(215_900, 0, Some("Letter"), true), paper(215_900, 0, Some("Legal"), true)]; + assert_eq!(matching_paper(&both, 612.0, 1008.0), Some(1), "the partial named like the sheet wins"); + assert_eq!(matching_paper(&both, 612.0, 792.0), Some(0), "and for a Letter sheet, the Letter one"); + let unnamed = [paper(215_900, 0, None, true), paper(215_900, 0, None, true)]; + assert_eq!(matching_paper(&unnamed, 612.0, 1008.0), None, "nothing to tell them apart by"); + let same_name = [paper(215_900, 0, Some("Legal"), true), paper(215_900, 0, Some("Legal"), true)]; + assert_eq!(matching_paper(&same_name, 612.0, 1008.0), None, "two of the same name are ambiguous too"); + } + #[test] fn the_unprintable_margin_comes_from_the_capabilities() { let caps = |x: u32, y: u32, w: u32, h: u32| { diff --git a/crates/print/src/windows.rs b/crates/print/src/windows.rs index d43e3981a..7ba238808 100644 --- a/crates/print/src/windows.rs +++ b/crates/print/src/windows.rs @@ -224,7 +224,28 @@ fn driver_ticket(device: &PrinterDevice, job: &Job, sheet: (f64, f64), landscape .collect(); let media = ticket::matching_paper(&papers, sheet.0, sheet.1).and_then(|i| medias.get(i)); let wanted = match (media, job.scaling) { - (Some(m), _) => Some((m.size().width_in_micron(), m.size().height_in_micron())), + (Some(m), _) => { + let size = (m.size().width_in_micron(), m.size().height_in_micron()); + // INV-6: a driver that keeps one side of the paper metric in its DEVMODE extension + // (storytold/craft-libs#7230) reports a zero side; the wanted size then is the sheet + // the job asked for, not the zero record, which would poison the cross-check and hand + // `sheets::plan` a width of zero. + if size.0 == 0 || size.1 == 0 { + match (ticket::micrometres(sheet.0), ticket::micrometres(sheet.1)) { + (Some(w), Some(h)) => Some((w, h)), + _ => { + return Err(spool_error(format!( + "{} has no {:.2} × {:.2} inch paper; choose a paper size it has, or add this one in its driver", + device.name(), + sheet.0 / 72.0, + sheet.1 / 72.0 + ))); + } + } + } else { + Some(size) + } + } (None, Scaling::ShrinkToFit) => None, (None, Scaling::Exact) => { return Err(spool_error(format!( diff --git a/crates/proto/Cargo.toml b/crates/proto/Cargo.toml new file mode 100644 index 000000000..528e407a8 --- /dev/null +++ b/crates/proto/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "craft-proto" +description = "Mail protocols without sockets: IMAP4rev1 and SMTP clients over any Read + Write stream" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +base64 = "0.23" +zeroize = "1" +# Internationalization: error messages and user-facing text. +log = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/proto/src/i18n.rs b/crates/proto/src/i18n.rs new file mode 100644 index 000000000..af0499154 --- /dev/null +++ b/crates/proto/src/i18n.rs @@ -0,0 +1,246 @@ +// SPDX-FileCopyrightText: Craft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Error message handling for protocol errors. +//! +//! Provides the `said!` macro and related types for creating user-facing error messages. + +pub use crate::said; +use std::fmt; + +/// A value that can be converted to an argument for error messages. +pub trait ToArg { + fn to_arg(&self) -> Arg; +} + +impl<T: fmt::Display> ToArg for T { + fn to_arg(&self) -> Arg { + Arg::Plain(format!("{}", self)) + } +} + +/// An argument for error messages. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Arg { + Plain(String), +} + +impl fmt::Display for Arg { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Arg::Plain(s) => f.write_str(s), + } + } +} + +impl Arg { + /// Create an argument from a string. + pub fn said(t: Text) -> Self { + Arg::Plain(format!("{}", t)) + } +} + +/// A text with values: `said!("no folder named {name}", name)`, or +/// `said!("{name} is larger than {mb} MB", name, mb = MAX >> 20)`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Text { + template: String, +} + +impl Text { + /// Preserve text supplied by a server or host without interpreting it. + pub fn verbatim(text: String) -> Self { + Self { template: text } + } + + /// Create a new text with the given template and arguments. + pub fn new(template: &str, args: Vec<(&str, Arg)>) -> Self { + // Substitute only placeholders in the template, never text inserted by a server. + let mut filled = String::new(); + let mut rest = template; + while let Some(open) = rest.find('{') { + filled.push_str(rest.get(..open).unwrap_or_default()); + let after = rest.get(open.saturating_add(1)..).unwrap_or_default(); + let Some(close) = after.find('}') else { + filled.push_str(rest.get(open..).unwrap_or_default()); + rest = ""; + break; + }; + let key = after.get(..close).unwrap_or_default(); + if let Some((_, arg)) = args.iter().find(|(name, _)| *name == key) { + filled.push_str(&arg.to_string()); + } else { + filled.push('{'); + filled.push_str(key); + filled.push('}'); + } + rest = after.get(close.saturating_add(1)..).unwrap_or_default(); + } + filled.push_str(rest); + Text { template: filled } + } +} + +impl fmt::Display for Text { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.template) + } +} + +impl From<&str> for Text { + fn from(s: &str) -> Self { + Text { template: s.to_string() } + } +} + +impl From<String> for Text { + fn from(s: String) -> Self { + Self::verbatim(s) + } +} + +/// The `said!` macro for creating error messages. +#[macro_export] +macro_rules! said { + (@arg $k:ident) => { $crate::i18n::ToArg::to_arg(&$k) }; + (@arg $k:ident = $v:expr) => { $crate::i18n::ToArg::to_arg(&$v) }; + ($t:literal $(, $k:ident $(= $v:expr)?)* $(,)?) => { + $crate::i18n::Text::new($t, vec![$((stringify!($k), $crate::said!(@arg $k $(= $v)?))),*]) + }; +} + +/// Trace only recognized protocol structure, never arbitrary reply text or command arguments. +/// Uppercase text can be private too; capitalization must not determine what is safe to log. +pub fn for_trace(line: &str) -> String { + let line = line.trim_end(); + let mut words = line.split_ascii_whitespace(); + let first = words.next().unwrap_or_default(); + let known = |word: &str| { + matches!( + word, + "OK" | "NO" + | "BAD" + | "BYE" + | "PREAUTH" + | "CAPABILITY" + | "LOGIN" + | "LOGOUT" + | "AUTHENTICATE" + | "SELECT" + | "EXAMINE" + | "CREATE" + | "DELETE" + | "RENAME" + | "SUBSCRIBE" + | "UNSUBSCRIBE" + | "LIST" + | "LSUB" + | "STATUS" + | "APPEND" + | "CHECK" + | "CLOSE" + | "EXPUNGE" + | "SEARCH" + | "FETCH" + | "STORE" + | "COPY" + | "MOVE" + | "UID" + | "IDLE" + | "DONE" + | "NOOP" + | "EHLO" + | "HELO" + | "STARTTLS" + | "AUTH" + | "MAIL" + | "RCPT" + | "DATA" + | "RSET" + | "QUIT" + | "EXISTS" + | "RECENT" + | "FLAGS" + ) + }; + let smtp_code = first.get(..3).is_some_and(|code| code.bytes().all(|b| b.is_ascii_digit())) + && first.as_bytes().first().is_some_and(|b| matches!(b, b'1'..=b'5')); + let tag = first.strip_prefix('A').is_some_and(|digits| !digits.is_empty() && digits.len() <= 16 && digits.bytes().all(|b| b.is_ascii_digit())); + let end = if smtp_code && (first.len() == 3 || first.get(3..4) == Some("-")) { + if first.len() > 3 { 4 } else { 3 } + } else if known(first) { + first.len() + } else if first == "*" || tag { + let second = words.next().unwrap_or_default(); + let last = if first == "*" && !second.is_empty() && second.bytes().all(|b| b.is_ascii_digit()) { + words.next().filter(|word| known(word)) + } else { + known(second).then_some(second) + }; + last.and_then(|word| line.find(word)?.checked_add(word.len())).unwrap_or(first.len()) + } else if first == "+" { + 1 + } else { + 0 + }; + let kept = line.get(..end).unwrap_or_default(); + let left = line.get(end..).unwrap_or_default().trim_start().len(); + match (kept.is_empty(), left) { + (_, 0) => kept.to_owned(), + (true, _) => format!("({left} bytes)"), + (false, _) => format!("{kept} … ({left} bytes)"), + } +} + +/// Server text made fit for an error message: one line, no control characters, not too long. +pub fn tidy(text: &str) -> String { + const MAX_CHARS: usize = 300; + let mut out = String::new(); + let mut space = false; + for (n, c) in text.trim().chars().enumerate() { + if n >= MAX_CHARS { + out.push('…'); + break; + } + if c.is_control() || c.is_whitespace() { + space = !out.is_empty(); + } else { + if space { + out.push(' '); + space = false; + } + out.push(c); + } + } + out +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + #[test] + fn inserted_arguments_are_not_interpreted() { + let msg = Text::new("{a} {b}", vec![("a", Arg::Plain("{b}".into())), ("b", Arg::Plain("secret".into()))]); + assert_eq!(msg.to_string(), "{b} secret"); + } + + #[test] + fn simple_message() { + let msg = said!("the server closed the connection"); + assert_eq!(msg.to_string(), "the server closed the connection"); + } + + #[test] + fn message_with_args() { + let msg = said!("the server sent {n} bytes", n = 123); + assert_eq!(msg.to_string(), "the server sent 123 bytes"); + } + + #[test] + fn tidy_removes_control_chars() { + assert_eq!(tidy("hello\x01world"), "hello world"); + assert_eq!(tidy("hello\nworld"), "hello world"); + } +} diff --git a/crates/proto/src/imap/gmail_labels_tests.rs b/crates/proto/src/imap/gmail_labels_tests.rs new file mode 100644 index 000000000..441e3220b --- /dev/null +++ b/crates/proto/src/imap/gmail_labels_tests.rs @@ -0,0 +1,230 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Gmail's labels of a message (`X-GM-LABELS`, Google's "Gmail IMAP extensions", #1153). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use proptest::prelude::*; + +use super::*; +use crate::script::Script; + +fn labels(server: &str) -> Vec<(u32, Option<Vec<String>>)> { + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_flags_gmail("1:*").unwrap_or_default(); + got.into_iter().map(|f| (f.uid, f.gmail_labels)).collect() +} + +fn owned(labels: &[&str]) -> Option<Vec<String>> { + Some(labels.iter().map(|l| l.to_string()).collect()) +} + +#[test] +fn labels_come_with_the_flags() { + let mut server = String::new(); + // Atoms, quoted strings, Gmail's own with their backslash, an empty list. + server += "* 1 FETCH (UID 1 FLAGS (\\Seen) X-GM-MSGID 11 X-GM-LABELS (\\Inbox \\Sent Important \"Muy Importante\"))\r\n"; + server += "* 2 FETCH (X-GM-LABELS (foo) UID 2 FLAGS ())\r\n"; + server += "* 3 FETCH (UID 3 FLAGS () X-GM-LABELS ())\r\n"; + // A literal, and modified UTF-7 as mailbox names are written. + server += "* 4 FETCH (UID 4 FLAGS () X-GM-LABELS ({12}\r\nWork/Clients \"Caf&AOk-\" &AOk-t&AOk-))\r\n"; + // UTF-8 as it stands, and an ampersand that isn't the start of a shifted run. + server += "* 5 FETCH (UID 5 FLAGS () X-GM-LABELS (\"Été\" \"Tom & Jerry\" \\Drafts))\r\n"; + // A message the server gave none for. + server += "* 6 FETCH (UID 6 FLAGS ())\r\n"; + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_flags_gmail("1:*").unwrap(); + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS X-GM-MSGID X-GM-LABELS)\r\n"); + let got: Vec<(u32, Option<Vec<String>>)> = got.into_iter().map(|f| (f.uid, f.gmail_labels)).collect(); + assert_eq!( + got, + [ + (1, owned(&["\\Inbox", "\\Sent", "Important", "Muy Importante"])), + (2, owned(&["foo"])), + (3, owned(&[])), + (4, owned(&["Work/Clients", "Café", "été"])), + (5, owned(&["Été", "Tom & Jerry", "\\Drafts"])), + (6, None), + ] + ); +} + +#[test] +fn the_later_word_counts_and_other_servers_are_not_asked() { + let got = labels( + "* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (a))\r\n* 1 FETCH (UID 1 X-GM-LABELS (b c))\r\n* 1 FETCH (UID 1 FLAGS ())\r\nA0001 OK done\r\n", + ); + assert_eq!(got, [(1, owned(&["b", "c"]))]); + // Without asking for them, labels the server gives anyway are not taken. + let mut s = Script::new("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (a))\r\nA0001 OK done\r\n"); + let plain = Imap::resume(&mut s).uid_fetch_flags("1:*").unwrap(); + assert_eq!(plain.first().and_then(|f| f.gmail_labels.clone()), None); + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS)\r\n"); +} + +#[test] +fn hostile_label_lists_are_kept_small() { + // A huge list: only so many are kept. + let many: String = (0..1000).map(|n| format!(" L{n}")).collect(); + let got = labels(&format!("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS ({many}))\r\nA0001 OK done\r\n")); + assert_eq!(got.first().and_then(|(_, l)| l.as_ref()).map(Vec::len), Some(MAX_GMAIL_LABELS)); + // A long label is cut, at a character boundary. + let long = "é".repeat(400); + let got = labels(&format!("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (\"{long}\"))\r\nA0001 OK done\r\n")); + let label = got.first().and_then(|(_, l)| l.as_ref()).and_then(|l| l.first()).cloned().unwrap_or_default(); + assert!(label.len() <= MAX_GMAIL_LABEL_LEN && !label.is_empty() && label.chars().all(|c| c == 'é')); + // A NUL in a literal is carried as text for the model to clean; a list inside the list is + // skipped; a list that isn't closed is read as far as it goes. + let got = labels("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS ({3}\r\na\0b (nested list) ok))\r\nA0001 OK done\r\n"); + assert_eq!(got, [(1, owned(&["a\0b", "ok"]))]); + let got = labels("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (a (b\r\nA0001 OK done\r\n"); + assert!(got.len() <= 1); + // Something other than a list is no labels. + let got = labels("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS NIL)\r\nA0001 OK done\r\n"); + assert_eq!(got, [(1, None)]); +} + +#[test] +fn a_fetch_keeps_no_more_label_bytes_than_its_budget() { + // Labels as literals, which the cap on a command's text doesn't count: each message with as + // many as a response may carry, of 256 bytes each. Past 32 MiB the rest come without. + let label = "x".repeat(MAX_GMAIL_LABEL_LEN); + let list: String = (0..MAX_LITERALS).map(|_| format!(" {{{}}}\r\n{label}", label.len())).collect(); + let count = MAX_GMAIL_LABEL_BYTES / (MAX_GMAIL_LABEL_LEN * MAX_LITERALS) + 4; + let mut server = String::new(); + for uid in 1..=count { + server += &format!("* {uid} FETCH (UID {uid} FLAGS () X-GM-LABELS ({list}))\r\n"); + } + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: u32::try_from(count).unwrap_or(u32::MAX), uid_validity: 1, uid_next: 0 }; + let got = imap.uid_fetch_flags_gmail("1:*").unwrap(); + assert_eq!(got.len(), count); + let kept: usize = got.iter().filter_map(|f| f.gmail_labels.as_ref()).flatten().map(String::len).sum(); + assert!(kept <= MAX_GMAIL_LABEL_BYTES); + assert!(got.last().is_some_and(|f| f.gmail_labels.is_none())); +} + +proptest! { + #[test] + fn arbitrary_label_lists_never_panic(inside in proptest::collection::vec(any::<u8>(), 0..400)) { + let mut server = b"* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (".to_vec(); + server.extend(inside.iter().filter(|b| **b != b'\r' && **b != b'\n')); + server.extend_from_slice(b"))\r\nA0001 OK done\r\n"); + let mut s = Script::new(server); + if let Ok(got) = Imap::resume(&mut s).uid_fetch_flags_gmail("1:*") { + for labels in got.iter().filter_map(|f| f.gmail_labels.as_ref()) { + prop_assert!(labels.len() <= MAX_GMAIL_LABELS); + } + } + } + + #[test] + fn arbitrary_server_bytes_never_panic_in_a_gmail_fetch(server in proptest::collection::vec(any::<u8>(), 0..600)) { + let mut s = Script::new(server); + let _ = Imap::resume(&mut s).uid_fetch_flags_gmail("1:*"); + } +} + +#[test] +fn a_folder_other_than_the_inbox_asks_for_labels_alone() { + let mut s = Script::new("* 1 FETCH (UID 1 FLAGS () X-GM-MSGID 5 X-GM-LABELS (a))\r\nA0001 OK done\r\n"); + let got = Imap::resume(&mut s).uid_fetch_flags_labels("1:*").unwrap(); + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS X-GM-LABELS)\r\n"); + // An id it wasn't asked for is not taken. + assert_eq!(got.into_iter().map(|f| (f.uid, f.gmail_id, f.gmail_labels)).collect::<Vec<_>>(), [(1, None, owned(&["a"]))]); +} + +#[test] +fn nil_in_a_list_is_no_label() { + assert_eq!(labels("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (NIL))\r\nA0001 OK done\r\n"), [(1, owned(&[]))]); + // A label called so comes quoted, and is one. + assert_eq!(labels("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (nil \"NIL\"))\r\nA0001 OK done\r\n"), [(1, owned(&["NIL"]))]); +} + +#[test] +fn tiny_labels_count_against_the_budget_too() { + // Empty labels, as many as a message keeps: each costs its overhead, so the budget still ends. + let list: String = (0..MAX_GMAIL_LABELS).map(|_| " \"\"").collect(); + let per_message = MAX_GMAIL_LABELS * LABEL_OVERHEAD; + let count = MAX_GMAIL_LABEL_BYTES / per_message + 4; + let mut server = String::new(); + for uid in 1..=count { + server += &format!("* {uid} FETCH (UID {uid} FLAGS () X-GM-LABELS ({list}))\r\n"); + } + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: u32::try_from(count).unwrap_or(u32::MAX), uid_validity: 1, uid_next: 0 }; + let got = imap.uid_fetch_flags_labels("1:*").unwrap(); + assert_eq!(got.len(), count); + let kept = got.iter().filter(|f| f.gmail_labels.is_some()).count(); + assert!(kept * per_message <= MAX_GMAIL_LABEL_BYTES && kept < count); +} + +#[test] +fn a_big_folders_listing_is_not_cut_short_for_its_size() { + // 300,000 messages with labels: more text than one command may otherwise bring (32 MiB). + let count: u32 = 300_000; + let mut server = String::with_capacity(count as usize * 200); + for uid in 1..=count { + server += &format!( + "* {uid} FETCH (FLAGS (\\Seen) UID {uid} X-GM-LABELS (\\Inbox \\Important \"Work/Clients and partners\" \"Receipts 2026\" \"Travel/Japan\"))\r\n" + ); + } + assert!(server.len() > MAX_COMMAND_TEXT); + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: count, uid_validity: 1, uid_next: count + 1 }; + assert_eq!(imap.uid_fetch_flags_labels("1:*").map(|got| got.len()), Ok(count as usize)); + // The room is the listing's alone: the next command has the usual cap again. + assert_eq!(imap.text_cap, MAX_COMMAND_TEXT); +} + +#[test] +fn a_mailbox_claimed_huge_cant_fill_memory_with_flags() { + // Any server (no Gmail here): ten million messages claimed, then message after message with + // every flag it may have. The text it may send is capped, and so are the flags kept: the + // listing fails, and never hands back messages that seem to have lost their flags. + let flags: Vec<String> = (0..MAX_FLAGS).map(|n| format!("f{n}")).collect(); + let flags = flags.join(" "); + let mut server = String::new(); + let mut uid = 0u32; + while server.len() < MAX_FETCH_TEXT / 4 { + uid += 1; + server += &format!("* {uid} FETCH (UID {uid} FLAGS ({flags}))\r\n"); + } + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: 10_000_000, uid_validity: 1, uid_next: 0 }; + let got = imap.uid_fetch_flags("1:*"); + assert!(matches!(&got, Err(ProtoError::Protocol(m)) if format!("{m:?}").contains("more flags")), "{:?}", got.as_ref().map(Vec::len)); + assert_eq!(imap.text_cap, MAX_COMMAND_TEXT); + // And what it may send at all stays within the ceiling, however many messages are claimed. + let mut s = Script::new(format!("* OK {}\r\n", "x".repeat(60_000)).repeat(MAX_FETCH_TEXT / 60_000 + 8)); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: u32::MAX, uid_validity: 1, uid_next: 0 }; + assert!(matches!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn an_honest_big_mailboxs_flags_fit_the_budget() { + // A million messages with three flags each. + const { assert!(1_000_000 * (ENTRY_OVERHEAD + 3 * (FLAG_OVERHEAD + 8)) <= MAX_FLAG_BYTES) }; +} + +#[test] +fn a_small_folders_listing_still_has_its_cap() { + // One message, and more than 32 MiB of other lines before it: refused as before. + let junk = format!("* OK {}\r\n", "x".repeat(60_000)); + let mut server = junk.repeat(MAX_COMMAND_TEXT / 60_000 + 8); + server += "* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (a))\r\nA0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: 1, uid_validity: 1, uid_next: 2 }; + assert!(matches!(imap.uid_fetch_flags_labels("1:*"), Err(ProtoError::Protocol(_)))); + assert_eq!(imap.text_cap, MAX_COMMAND_TEXT); +} diff --git a/crates/proto/src/imap/gmail_tests.rs b/crates/proto/src/imap/gmail_tests.rs new file mode 100644 index 000000000..451690bc5 --- /dev/null +++ b/crates/proto/src/imap/gmail_tests.rs @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Gmail's IMAP extensions (#911): `X-GM-MSGID` and `X-GM-RAW`. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use super::*; +use crate::script::Script; + +#[test] +fn gmail_ids_come_with_the_flags() { + let mut server = String::new(); + server += "* 1 FETCH (UID 4 FLAGS (\\Seen) X-GM-MSGID 1278455344230334865)\r\n"; + server += "* 2 FETCH (X-GM-MSGID 18446744073709551615 UID 7 FLAGS ())\r\n"; + // An id that is no number, or 0, is none; a later word about a message without one keeps it. + server += "* 3 FETCH (UID 9 FLAGS () X-GM-MSGID 12ab)\r\n"; + server += "* 4 FETCH (UID 10 FLAGS () X-GM-MSGID 0)\r\n"; + server += "* 2 FETCH (UID 7 FLAGS (\\Flagged))\r\n"; + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_flags_gmail("1:*").unwrap(); + let ids: Vec<(u32, Option<u64>)> = got.iter().map(|f| (f.uid, f.gmail_id)).collect(); + assert_eq!(ids, [(4, Some(1_278_455_344_230_334_865)), (7, Some(u64::MAX)), (9, None), (10, None)]); + assert_eq!(got.get(1).map(|f| f.flags.clone()), Some(vec!["\\Flagged".to_string()])); + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS X-GM-MSGID X-GM-LABELS)\r\n"); + // Without asking for them, an id the server gives anyway is not taken. + let mut s = Script::new("* 1 FETCH (UID 4 FLAGS () X-GM-MSGID 5)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_flags("1:*").unwrap().first().and_then(|f| f.gmail_id), None); +} + +#[test] +fn gmail_search_is_quoted_and_kept_to_its_set() { + let mut s = Script::new("* SEARCH 9 4 0 x 4 12 600\r\nA0001 OK done\r\nA0002 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + // In UID order, once each, and only what the set names. + assert_eq!(imap.uid_search_gmail("4:12", "category:social"), Ok(vec![4, 9, 12])); + // Quotes are quoted; CR, LF and NUL never go out. + assert_eq!(imap.uid_search_gmail("1:*", "category:\"x\"\r\nA9 DELETE INBOX\0"), Ok(vec![])); + assert_eq!( + s.sent(), + "A0001 UID SEARCH UID 4:12 UNDELETED X-GM-RAW \"category:social\"\r\n\ + A0002 UID SEARCH UID 1:* UNDELETED X-GM-RAW \"category:\\\"x\\\"A9 DELETE INBOX\"\r\n" + ); + // A refusal is said. + let mut s = Script::new("A0001 BAD no such search\r\n"); + assert!(matches!(Imap::resume(&mut s).uid_search_gmail("1:*", "category:forums"), Err(ProtoError::Rejected(_)))); + // What can't be sent is refused unsent. + for (set, query) in [("1:*", ""), ("1:*", "\r\n"), ("1:*", "kategorie:äöü"), ("1 2", "category:social"), ("", "category:social")] { + let mut s = Script::new("A0001 OK done\r\n"); + assert!(matches!(Imap::resume(&mut s).uid_search_gmail(set, query), Err(ProtoError::Protocol(_))), "{set:?} {query:?}"); + assert_eq!(s.sent(), "", "{set:?} {query:?}"); + } +} + +#[test] +fn gmail_search_takes_no_more_than_its_cap() { + let many: String = (1..=6000).map(|n| format!(" {n}")).collect(); + let mut s = Script::new(format!("* SEARCH{many}\r\nA0001 OK done\r\n")); + assert_eq!(Imap::resume(&mut s).uid_search_gmail("1:*", "category:promotions").map(|uids| uids.len()), Ok(MAX_GMAIL_FOUND)); + // As many as the cap, at the longest a UID is written, fit in one line. + let longest: String = (0..MAX_GMAIL_FOUND).map(|_| " 4294967295").collect(); + assert!(format!("* SEARCH{longest}").len() < crate::MAX_LINE); +} + +#[test] +fn a_gmail_answer_too_long_is_refused_and_the_session_goes_on() { + let long: String = (0..20_000).map(|n| format!(" {}", 1_000_000_000u32 + n)).collect(); + assert!(long.len() > crate::MAX_LINE); + let server = format!("* SEARCH{long}\r\n* SEARCH 3\r\nA0001 OK done\r\n* SEARCH 5\r\nA0002 OK done\r\n"); + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.uid_search_gmail("1:*", "category:social"), Err(ProtoError::Rejected(_)))); + // The next command is answered as if nothing had happened. + assert_eq!(imap.uid_search_gmail("1:*", "category:social"), Ok(vec![5])); + // Elsewhere a line that long still ends the session, and a tagged one is never read past. + let mut s = Script::new(format!("* SEARCH{long}\r\nA0001 OK done\r\n")); + assert!(matches!(Imap::resume(&mut s).uid_search_header("Message-ID", "x"), Err(ProtoError::Protocol(_)))); + let mut s = Script::new(format!("A0001 OK{long}\r\n")); + assert!(matches!(Imap::resume(&mut s).uid_search_gmail("1:*", "category:social"), Err(ProtoError::Protocol(_)))); +} diff --git a/crates/proto/src/imap/idle.rs b/crates/proto/src/imap/idle.rs new file mode 100644 index 000000000..ecccec50c --- /dev/null +++ b/crates/proto/src/imap/idle.rs @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! IDLE (RFC 2177): the server says when a mailbox changes, instead of being asked. The session +//! is in one of two states, and this module only moves it between them: a mailbox is selected +//! (EXAMINE), [`Imap::idle_begin`] puts the server to waiting, [`Imap::idle_poll`] hears what it +//! says (a line a second at most, so that the caller can look at the clock and at whether it was +//! told to stop), and [`Imap::idle_end`] says DONE and reads on to the command's end. +//! +//! The server's word is bounded as everywhere: a line over [`crate::MAX_LINE`] and a line that +//! announces a literal end the session, and the caller counts what it hears. + +use std::io::{Read, Write}; + +use super::Imap; +use super::parse; +use crate::i18n::{Arg, said}; +use crate::{ProtoError, for_trace}; + +/// Most lines [`Imap::idle_end`] reads on the way to the command's end. +const MAX_ENDING: usize = 256; +/// Most quiet reads [`Imap::idle_end`] waits through for one line. +const MAX_QUIET: usize = 30; + +/// What the server said while it was waiting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IdleEvent { + /// `* n EXISTS`: the mailbox now has `n` messages. + Exists(u32), + /// `* n EXPUNGE`: the message with that sequence number is gone. + Expunge(u32), + /// `* n RECENT`: `n` messages are new since the mailbox was opened. + Recent(u32), + /// Anything else the server said unasked (a flag change, a status line): not news of mail. + Other, + /// The server ended the command itself (`tag OK`): IDLE has to be begun again. + Ended, +} + +/// From the text after `* `: `3 EXISTS`. +fn event_from(rest: &[u8], secrets: &crate::Secrets) -> Result<IdleEvent, ProtoError> { + let text = String::from_utf8_lossy(rest); + let mut words = text.split_whitespace(); + let (first, second) = (words.next().unwrap_or(""), words.next().unwrap_or("")); + let count = first.parse::<u32>().ok(); + Ok(match (count, second.to_ascii_uppercase().as_str()) { + (Some(n), "EXISTS") => IdleEvent::Exists(n), + (Some(n), "EXPUNGE") => IdleEvent::Expunge(n), + (Some(n), "RECENT") => IdleEvent::Recent(n), + _ if first.eq_ignore_ascii_case("BYE") => { + return Err(ProtoError::Io(said!("the server ended the session: {reason}", reason = crate::tidy(&secrets.hide(&text))))); + } + _ => IdleEvent::Other, + }) +} + +impl<S: Read + Write> Imap<S> { + /// Send IDLE and wait for the server's go-ahead. The session has to have a mailbox selected; + /// a server that refuses (NO, BAD) is an error. While idle, the only commands that may follow + /// are [`Imap::idle_poll`] and [`Imap::idle_end`]. + pub fn idle_begin(&mut self) -> Result<(), ProtoError> { + if self.idle_tag.is_some() { + return Err(ProtoError::Protocol(said!("the server is already idling"))); + } + self.idle_pending.clear(); + let tag = self.tag(); + self.text_seen = 0; + log::trace!("C: {tag} IDLE"); + self.wire.write(format!("{tag} IDLE\r\n").as_bytes())?; + self.wire.flush()?; + self.idle_tag = Some(tag.clone()); + // Untagged lines may come before the `+`; the tagged answer is a refusal. + for _ in 0..MAX_ENDING { + match self.read_response()? { + super::Response::GoAhead => return Ok(()), + super::Response::Status { tag: Some(answered), line } => { + self.idle_tag = None; + if answered != tag { + return Err(ProtoError::Protocol(said!("the server answered a command that wasn't sent"))); + } + return Err(ProtoError::Rejected(self.refusal(&line))); + } + super::Response::Status { tag: None, line } => { + if line.status == parse::Status::Bye { + self.idle_tag = None; + return Err(ProtoError::Io(said!("the server ended the session: {reason}", reason = Arg::said(self.refusal(&line))))); + } + self.note_status(&line); + } + super::Response::Data(values) => { + self.note_data(&values); + let event = match (values.first().and_then(parse::Value::number), values.get(1).and_then(parse::Value::atom)) { + (Some(n), Some(word)) if word.eq_ignore_ascii_case("EXISTS") => IdleEvent::Exists(n), + (Some(n), Some(word)) if word.eq_ignore_ascii_case("EXPUNGE") => IdleEvent::Expunge(n), + (Some(n), Some(word)) if word.eq_ignore_ascii_case("RECENT") => IdleEvent::Recent(n), + _ => IdleEvent::Other, + }; + self.idle_pending.push_back(event); + } + } + } + self.idle_tag = None; + Err(ProtoError::Protocol(said!("the server sent too many responses to one command"))) + } + + /// The next thing the server says while idle, or `None` after one read if the line is + /// incomplete or no bytes arrived (see [`crate::MAX_LINE`] for the bound on a line). + pub fn idle_poll(&mut self) -> Result<Option<IdleEvent>, ProtoError> { + let Some(tag) = self.idle_tag.clone() else { + return Err(ProtoError::Protocol(said!("the server isn't idling"))); + }; + if let Some(event) = self.idle_pending.pop_front() { + return Ok(Some(event)); + } + let Some(line) = self.wire.poll_line()? else { return Ok(None) }; + if log::log_enabled!(log::Level::Trace) { + log::trace!("S: {}", for_trace(&self.secrets.hide(&String::from_utf8_lossy(&line)))); + } + if let Some(rest) = line.strip_prefix(b"* ") { + // A literal in what is said while idle is nothing a server has a reason to send. + if parse::literal_marker(rest).is_some() { + return Err(ProtoError::Protocol(said!("the server sent data it has no reason to send while idle"))); + } + return event_from(rest, &self.secrets).map(Some); + } + let text = String::from_utf8_lossy(&line); + if text.strip_prefix(tag.as_str()).is_some_and(|rest| rest.starts_with(' ')) { + // The server ended IDLE by itself (a timeout of its own, say). + self.idle_tag = None; + let status = text.split_ascii_whitespace().nth(1).and_then(parse::Status::parse); + return match status { + Some(parse::Status::Ok) => Ok(Some(IdleEvent::Ended)), + Some(parse::Status::No | parse::Status::Bad) => Err(ProtoError::Rejected(said!("the server didn't end IDLE properly"))), + _ => Err(ProtoError::Protocol(said!("the server returned an invalid IDLE completion"))), + }; + } + Err(ProtoError::Protocol(said!("the server said something that is no news while idle"))) + } + + /// Say DONE and read what the server still has to say, up to the end of the command. What was + /// said on the way is given back. After this the session is as it was before + /// [`Imap::idle_begin`]. + pub fn idle_end(&mut self) -> Result<Vec<IdleEvent>, ProtoError> { + let Some(tag) = self.idle_tag.take() else { + return Err(ProtoError::Protocol(said!("the server isn't idling"))); + }; + log::trace!("C: DONE"); + self.wire.write(b"DONE\r\n")?; + self.wire.flush()?; + let mut events: Vec<_> = self.idle_pending.drain(..).collect(); + for _ in 0..MAX_ENDING { + // The server may take a moment to answer: a few polls of the stream's own wait. + let mut polled = None; + for _ in 0..MAX_QUIET { + polled = self.wire.poll_line()?; + if polled.is_some() { + break; + } + } + let Some(line) = polled else { return Err(ProtoError::Io(said!("the server took too long to answer"))) }; + if let Some(rest) = line.strip_prefix(b"* ") { + if parse::literal_marker(rest).is_some() { + return Err(ProtoError::Protocol(said!("the server sent data it has no reason to send while idle"))); + } + events.push(event_from(rest, &self.secrets)?); + continue; + } + let text = String::from_utf8_lossy(&line); + let mut words = text.splitn(3, ' '); + let (answered, status) = (words.next().unwrap_or(""), words.next().unwrap_or("")); + if answered != tag { + return Err(ProtoError::Protocol(said!("the server answered a command that wasn't sent"))); + } + return match parse::Status::parse(status) { + Some(parse::Status::Ok) => Ok(events), + _ => Err(ProtoError::Rejected(said!("the server didn't end IDLE properly"))), + }; + } + Err(ProtoError::Protocol(said!("the server sent too many responses to one command"))) + } + + /// Whether the server said it can do IDLE (upper-cased capability list as last said). + pub fn offers_idle(&self) -> bool { + self.offers("IDLE") + } +} diff --git a/crates/proto/src/imap/idle_tests.rs b/crates/proto/src/imap/idle_tests.rs new file mode 100644 index 000000000..cb0515cdd --- /dev/null +++ b/crates/proto/src/imap/idle_tests.rs @@ -0,0 +1,139 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use proptest::prelude::*; + +use super::*; +use crate::script::Script; + +// Polling now yields after each underlying read, including partial lines. +fn next_event(imap: &mut Imap<&mut Script>) -> Result<Option<IdleEvent>, ProtoError> { + for _ in 0..crate::MAX_LINE + 2 { + match imap.idle_poll() { + Ok(None) => continue, + result => return result, + } + } + panic!("script failed to produce an event within its bounded input"); +} + +#[test] +fn idle_goes_ahead_hears_news_and_ends() { + // The go-ahead is the first line; the rest is heard by polling. + let mut s2 = Script::new("+ idling\r\n* 4 EXISTS\r\n* 1 RECENT\r\n* 2 FETCH (FLAGS (\\Seen))\r\n* 3 EXPUNGE\r\n"); + let mut imap2 = Imap::resume(&mut s2); + imap2.idle_begin().unwrap(); + assert_eq!(next_event(&mut imap2).unwrap(), Some(IdleEvent::Exists(4))); + assert_eq!(next_event(&mut imap2).unwrap(), Some(IdleEvent::Recent(1))); + assert_eq!(next_event(&mut imap2).unwrap(), Some(IdleEvent::Other)); + assert_eq!(next_event(&mut imap2).unwrap(), Some(IdleEvent::Expunge(3))); + assert_eq!(s2.sent(), "A0001 IDLE\r\n"); + + let mut s3 = Script::new("+ idling\r\n* 5 EXISTS\r\nA0001 OK IDLE terminated\r\n"); + let mut imap3 = Imap::resume(&mut s3); + imap3.idle_begin().unwrap(); + assert_eq!(imap3.idle_end().unwrap(), vec![IdleEvent::Exists(5)]); + assert_eq!(s3.sent(), "A0001 IDLE\r\nDONE\r\n"); +} + +#[test] +fn a_refusal_or_an_early_end_or_a_goodbye_is_said() { + let mut s = Script::new("A0001 NO [CANNOT] not now\r\n"); + assert!(matches!(Imap::resume(&mut s).idle_begin(), Err(ProtoError::Rejected(_)))); + let mut s = Script::new("+ idling\r\nA0001 OK the server gave up waiting\r\n"); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + assert_eq!(next_event(&mut imap).unwrap(), Some(IdleEvent::Ended)); + // Not idling any more: nothing to poll or to end. + assert!(matches!(next_event(&mut imap), Err(ProtoError::Protocol(_)))); + assert!(matches!(imap.idle_end(), Err(ProtoError::Protocol(_)))); + let mut s = Script::new("+ idling\r\n* BYE going away\r\n"); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + assert!(matches!(next_event(&mut imap), Err(ProtoError::Io(_)))); +} + +#[test] +fn what_a_server_has_no_reason_to_send_while_idle_ends_the_session() { + for hostile in ["* 1 FETCH (BODY[] {5}\r\n", "A0099 OK that was never asked\r\n", "garbage\r\n", "* 1 EXISTS\r\n".repeat(0).as_str()] { + let mut s = Script::new(format!("+ idling\r\n{hostile}")); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + let got = next_event(&mut imap); + assert!(got.is_err() || hostile.is_empty(), "{hostile:?}: {got:?}"); + } + // A line longer than any a server is allowed. + let mut long = b"+ idling\r\n* ".to_vec(); + long.extend(std::iter::repeat_n(b'x', crate::MAX_LINE + 10)); + long.extend_from_slice(b"\r\n"); + let mut s = Script::whole(long); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + assert!(matches!(next_event(&mut imap), Err(ProtoError::Protocol(_)))); +} + +proptest! { + #[test] + fn arbitrary_server_bytes_never_panic_while_idle(server in proptest::collection::vec(any::<u8>(), 0..800), greeted in any::<bool>()) { + let mut bytes = if greeted { b"+ idling\r\n".to_vec() } else { Vec::new() }; + bytes.extend_from_slice(&server); + let mut s = Script::new(&bytes); + let mut imap = Imap::resume(&mut s); + if imap.idle_begin().is_ok() { + // However much is said, polling ends (the script runs out) and nothing is kept without bound. + for _ in 0..2_000 { + match next_event(&mut imap) { + Ok(Some(_)) => {} + Ok(None) | Err(_) => break, + } + } + let _ = imap.idle_end(); + } + } + + #[test] + fn idle_shaped_noise_never_panics(words in proptest::collection::vec(proptest::sample::select(&["* ", "1 ", "EXISTS", "EXPUNGE", "RECENT", " ", "\r\n", "A0001 OK ", "BYE ", "{9}", "FETCH (", ")"][..]), 0..60)) { + let mut s = Script::new(format!("+ go\r\n{}", words.concat())); + let mut imap = Imap::resume(&mut s); + if imap.idle_begin().is_ok() { + for _ in 0..200 { + if !matches!(next_event(&mut imap), Ok(Some(_))) { + break; + } + } + let _ = imap.idle_end(); + } + } +} + +#[test] +fn notifications_before_continuation_are_delivered() { + let mut s = Script::new("* 4 EXISTS\r\n* 2 EXPUNGE\r\n+ idling\r\nA0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + assert_eq!(imap.idle_poll().unwrap(), Some(IdleEvent::Exists(4))); + assert_eq!(imap.idle_end().unwrap(), vec![IdleEvent::Expunge(2)]); +} + +#[test] +fn idle_bye_errors_hide_registered_secrets() { + for ending in [false, true] { + let mut s = Script::new("+ idling\r\n* BYE test-token\r\n"); + let mut imap = Imap::resume(&mut s); + imap.secrets.add("test-token"); + imap.idle_begin().unwrap(); + let error = if ending { imap.idle_end().unwrap_err() } else { next_event(&mut imap).unwrap_err() }; + assert!(!error.to_string().contains("test-token")); + } +} + +#[test] +fn idle_completion_requires_a_valid_success_status() { + for (status, rejected) in [("NO", true), ("BAD", true), ("nonsense", false)] { + let mut s = Script::new(format!("+ idling\r\nA0001 {status} failed\r\n")); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + let error = next_event(&mut imap).unwrap_err(); + assert!(if rejected { matches!(error, ProtoError::Rejected(_)) } else { matches!(error, ProtoError::Protocol(_)) }); + } +} diff --git a/crates/proto/src/imap/limits_tests.rs b/crates/proto/src/imap/limits_tests.rs new file mode 100644 index 000000000..9b802055c --- /dev/null +++ b/crates/proto/src/imap/limits_tests.rs @@ -0,0 +1,215 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! What one command may make the client keep or read, however much the server sends. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use proptest::prelude::*; + +use super::*; +use crate::script::Script; + +/// A session whose open mailbox has `exists` messages and the next UID `uid_next`. +fn opened(s: &mut Script, exists: u32, uid_next: u32) -> Imap<&mut Script> { + let mut imap = Imap::resume(s); + imap.selected = Selected { exists, uid_validity: 1, uid_next }; + imap +} + +/// `lines` lines made by `line(n)`. +fn flood(lines: usize, line: impl Fn(usize) -> String) -> String { + (0..lines).map(line).collect() +} + +fn padding() -> String { + "x".repeat(60 * 1024) +} + +#[test] +fn a_flood_of_long_lines_ends_the_command() { + let pad = padding(); + // 600 lines of 60 KB are more than the 32 MB one command may bring. + let server = flood(600, |n| format!("* {n} FETCH (UID {} FLAGS ({pad}))\r\n", n + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + let err = opened(&mut s, 1000, 2000).uid_fetch_flags("1:*").unwrap_err(); + assert!(matches!(err, ProtoError::Protocol(ref m) if m.to_string().contains("too much")), "{err:?}"); + // The same in a list. + let server = flood(600, |n| format!("* LIST () \"/\" \"{n}{pad}\"\r\n")) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + assert!(matches!(opened(&mut s, 0, 0).list(), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn a_flood_of_responses_ends_the_command() { + let server = "* OK still here\r\n".repeat(MAX_RESPONSES + 1) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + let err = opened(&mut s, 0, 0).uid_fetch_sizes("1:*").unwrap_err(); + assert!(matches!(err, ProtoError::Protocol(ref m) if m.to_string().contains("too many")), "{err:?}"); +} + +#[test] +fn a_list_keeps_a_capped_number_of_mailboxes() { + let server = flood(MAX_MAILBOXES + 500, |n| format!("* LIST () \"/\" f{n}\r\n")) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + let got = opened(&mut s, 0, 0).list().unwrap(); + assert_eq!(got.len(), MAX_MAILBOXES); + assert_eq!(got.first().map(|m| m.raw.as_str()), Some("f0")); + // #991: and how many were dropped is said; none, for a list kept whole. + let server = flood(MAX_MAILBOXES + 500, |n| format!("* LIST () \"/\" f{n}\r\n")) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + assert_eq!(opened(&mut s, 0, 0).list_counted().unwrap().1, 500); + let mut s = Script::new("* LIST () \"/\" a\r\n* LIST () \"/\" a\r\nA0001 OK done\r\n"); + assert_eq!( + opened(&mut s, 0, 0).list_counted().unwrap(), + (vec![Mailbox { name: "a".into(), raw: "a".into(), delimiter: Some('/'), flags: Vec::new() }], 0) + ); +} + +/// #991: a list keeps a bounded number of bytes too, however many mailboxes that is. +#[test] +fn a_list_keeps_a_capped_number_of_bytes() { + let flags: Vec<String> = (0..MAX_FLAGS).map(|n| format!("\\F{n}{}", "x".repeat(MAX_FLAG_LEN - 8))).collect(); + let flags = flags.join(" "); + let server = flood(1_500, |n| format!("* LIST ({flags}) \"/\" f{n}\r\n")) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + let (got, dropped) = opened(&mut s, 0, 0).list_counted().unwrap(); + assert_eq!(got.len() + dropped, 1_500); + let kept: usize = got.iter().map(|m| m.raw.len() * 2 + m.name.len() + m.flags.iter().map(String::len).sum::<usize>()).sum(); + assert!(!got.is_empty() && got.len() < 1_500, "{}", got.len()); + // The last one kept may take it over by one mailbox's worth, never more. + assert!(kept < MAX_LIST_BYTES + MAX_LINE, "{kept}"); +} + +#[test] +fn names_and_flags_are_kept_short() { + let long_flag = "é".repeat(400); + let long_name = "n".repeat(MAX_MAILBOX_NAME + 1); + let server = format!("* LIST ({long_flag} \\Sent) \"/\" Fine\r\n* LIST () \"/\" {long_name}\r\nA0001 OK done\r\n"); + let mut s = Script::new(server); + let got = opened(&mut s, 0, 0).list().unwrap(); + // The mailbox with the oversized name is left out, not cut into another one. + assert_eq!(got.len(), 1); + assert!(got[0].flags[0].len() <= MAX_FLAG_LEN && got[0].flags[0].chars().all(|c| c == 'é')); + assert_eq!(got[0].flags[1], "\\Sent"); + + let server = format!("* 1 FETCH (UID 1 FLAGS ({long_flag}))\r\nA0001 OK done\r\n"); + let mut s = Script::new(server); + let got = opened(&mut s, 1, 2).uid_fetch_flags("1:*").unwrap(); + assert!(got[0].flags[0].len() <= MAX_FLAG_LEN); +} + +#[test] +fn only_uids_that_were_asked_for_and_exist_are_kept() { + let server = "* 1 FETCH (UID 3 FLAGS (\\Seen))\r\n* 2 FETCH (UID 7 FLAGS ())\r\n* 3 FETCH (UID 9 FLAGS ())\r\n* 4 FETCH (UID 4000000000 FLAGS ())\r\n\ + * 5 FETCH (UID 10 FLAGS ())\r\nA0001 OK done\r\n"; + // Not in the set. + let mut s = Script::new(server); + let got = opened(&mut s, 5, 11).uid_fetch_flags("3,8:9").unwrap(); + assert_eq!(got.iter().map(|f| f.uid).collect::<Vec<_>>(), [3, 9]); + // UIDNEXT is only a snapshot: later deliveries must not be discarded. + let sizes = server.replace("FLAGS (\\Seen)", "RFC822.SIZE 5").replace("FLAGS ()", "RFC822.SIZE 6"); + let mut s = Script::new(sizes); + let got = opened(&mut s, 5, 10).uid_fetch_sizes("1:*").unwrap(); + assert_eq!(got, [(3, 5), (7, 6), (9, 6), (10, 6), (4000000000, 6)]); +} + +#[test] +fn more_distinct_uids_than_the_mailbox_can_hold_fail_the_command() { + // 3 messages: room for 2 * 3 + FETCH_SLACK distinct UIDs, and not one more. + let room = 2 * 3 + FETCH_SLACK; + let many = |n: usize| flood(n, |i| format!("* {i} FETCH (UID {} FLAGS ())\r\n", i + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(many(room)); + assert_eq!(opened(&mut s, 3, u32::MAX).uid_fetch_flags("1:*").unwrap().len(), room); + let mut s = Script::new(many(room + 1)); + assert!(matches!(opened(&mut s, 3, u32::MAX).uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); + let sizes = flood(room + 1, |i| format!("* {i} FETCH (UID {} RFC822.SIZE 1)\r\n", i + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(sizes); + assert!(matches!(opened(&mut s, 3, u32::MAX).uid_fetch_sizes("1:*"), Err(ProtoError::Protocol(_)))); + // The same UID again and again is one. + let same = flood(room * 3, |_| "* 1 FETCH (UID 1 FLAGS ())\r\n".to_string()) + "A0001 OK done\r\n"; + let mut s = Script::new(same); + assert_eq!(opened(&mut s, 3, 100).uid_fetch_flags("1:*").unwrap().len(), 1); +} + +#[test] +fn set_ranges_read_what_is_written() { + assert_eq!(set_ranges("1:*", 9), Some(vec![(1, 9)])); + assert_eq!(set_ranges("5,9,20:12", 9), Some(vec![(5, 5), (9, 9), (12, 20)])); + assert_eq!(set_ranges("1:x", 9), None); + assert_eq!(set_ranges("", 9), None); +} + +proptest! { + /// Whatever the server sends, the command ends, and what it keeps is bounded by the caps. + #[test] + fn arbitrary_responses_are_kept_within_bounds(lines in proptest::collection::vec(("[ -~]{0,200}", any::<u32>(), 0usize..4), 0..400)) { + let server: String = lines + .iter() + .map(|(text, uid, kind)| match kind { + 0 => format!("* LIST (\\{text}) \"/\" {text}\r\n"), + 1 => format!("* 1 FETCH (UID {uid} FLAGS ({text}))\r\n"), + 2 => format!("* 1 FETCH (UID {uid} RFC822.SIZE {uid})\r\n"), + _ => format!("* {text}\r\n"), + }) + .collect::<String>() + + "A0001 OK done\r\n"; + let mut s = Script::new(server.clone()); + if let Ok(list) = opened(&mut s, 10, 50).list() { + prop_assert!(list.len() <= MAX_MAILBOXES); + prop_assert!(list.iter().all(|m| m.raw.len() <= MAX_MAILBOX_NAME && m.flags.len() <= MAX_FLAGS && m.flags.iter().all(|f| f.len() <= MAX_FLAG_LEN))); + } + let mut s = Script::new(server.clone()); + // A fixed range retains its UID bound even if the server sends newer deliveries. + if let Ok(got) = opened(&mut s, 10, 50).uid_fetch_flags("1:49") { + prop_assert!(got.len() <= 2 * 10 + FETCH_SLACK); + prop_assert!(got.iter().all(|f| f.uid >= 1 && f.uid < 50 && f.flags.len() <= MAX_FLAGS && f.flags.iter().all(|x| x.len() <= MAX_FLAG_LEN))); + } + let mut s = Script::new(server.clone()); + // Wildcards admit deliveries newer than SELECT's UIDNEXT, but retain all storage caps. + if let Ok(got) = opened(&mut s, 10, 50).uid_fetch_flags("1:*") { + prop_assert!(got.len() <= 2 * 10 + FETCH_SLACK); + prop_assert!(got.iter().all(|f| f.uid >= 1 && f.flags.len() <= MAX_FLAGS && f.flags.iter().all(|x| x.len() <= MAX_FLAG_LEN))); + } + let mut s = Script::new(server); + if let Ok(got) = opened(&mut s, 10, 50).uid_fetch_sizes("5:20") { + prop_assert!(got.iter().all(|(uid, _)| (5..=20).contains(uid))); + } + } +} + +#[test] +fn a_folder_with_more_messages_than_other_commands_may_answer_still_reads() { + let exists = 300_000u32; + let lines = |n: u32| flood(n as usize, |i| format!("* {i} FETCH (UID {} FLAGS ())\r\n", i + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(lines(exists)); + assert_eq!(opened(&mut s, exists, exists + 1).uid_fetch_flags("1:*").unwrap().len(), exists as usize); + let sizes = flood(exists as usize, |i| format!("* {i} FETCH (UID {} RFC822.SIZE 1)\r\n", i + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(sizes); + assert_eq!(opened(&mut s, exists, exists + 1).uid_fetch_sizes("1:*").unwrap().len(), exists as usize); + // Responses that are not messages still end at the cap for that folder, and the next command is back to the usual one. + let noise = "* OK still here\r\n".repeat(2 * exists as usize + FETCH_SLACK + 1) + "A0001 OK done\r\n"; + let mut s = Script::new(noise); + let mut imap = opened(&mut s, exists, exists + 1); + assert!(matches!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); + assert_eq!(imap.response_cap, MAX_RESPONSES); +} + +#[test] +fn short_flags_release_large_backing_allocations() { + let flags = short_flags(vec![Value::Atom("A".repeat(1024 * 1024))]); + assert_eq!(flags[0].len(), MAX_FLAG_LEN); + assert!(flags[0].capacity() <= MAX_FLAG_LEN); +} + +#[test] +fn wildcard_fetch_accepts_deliveries_after_select() { + let server = "* 1 FETCH (UID 10 FLAGS ())\r\nA0001 OK done\r\n"; + let mut s = Script::new(server); + assert_eq!(opened(&mut s, 1, 10).uid_fetch_flags("*").unwrap()[0].uid, 10); +} + +#[test] +fn brackets_in_flag_keywords_do_not_consume_body_sections() { + for flag in ["x[", "BODY["] { + let mut s = Script::new(format!("* 1 FETCH (UID 3 FLAGS ({flag}) BODY[] {{2}}\r\nok)\r\nA0001 OK done\r\n")); + assert_eq!(opened(&mut s, 1, 4).uid_fetch_message(3).unwrap().unwrap().body, Some(b"ok".to_vec())); + } +} diff --git a/crates/proto/src/imap/mod.rs b/crates/proto/src/imap/mod.rs new file mode 100644 index 000000000..d469bffcc --- /dev/null +++ b/crates/proto/src/imap/mod.rs @@ -0,0 +1,1405 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! An IMAP4rev1 client (RFC 3501) with the commands a two-way synchronisation needs: reading +//! mailboxes, and changing flags, moving, copying, removing and filing messages (UID MOVE of +//! RFC 6851; UID EXPUNGE and the `COPYUID` answer of RFC 4315). Special-use mailbox flags +//! (RFC 6154) come through in [`Mailbox::flags`] as the server wrote them. Password sign-in prefers +//! advertised SASL PLAIN, with LOGIN as a fallback when PLAIN is not offered; OAuth uses XOAUTH2. +//! +//! There is no plain EXPUNGE and no CLOSE here, on purpose: both remove every message marked +//! `\Deleted` in the mailbox, also those another program marked. + +mod idle; +#[cfg(test)] +mod idle_tests; +mod parse; +mod password; +#[cfg(test)] +mod password_tests; +mod status; +#[cfg(test)] +mod status_tests; +mod utf7; + +pub use idle::IdleEvent; +pub use status::{FolderStatus, MAX_STATUS_BATCH}; + +use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::io::{Read, Write}; + +use parse::{Piece, Status, StatusLine, Value}; +pub use utf7::{decode_utf7, encode_utf7}; + +use crate::i18n::{Arg, Text}; +use crate::line::Wire; +use crate::said; +use crate::{MAX_LINE, MAX_LITERAL, ProtoError, Secrets, for_trace, tidy, xoauth2}; + +/// Most responses the server may send to one command. +const MAX_RESPONSES: usize = 250_000; +/// Most text (everything outside literals) the server may send in answer to one command. +const MAX_COMMAND_TEXT: usize = 32 << 20; +/// Most mailboxes one LIST keeps; the ones after are read and dropped. More than a run reads +/// (10,000, #991), since some of those listed are never read (views, folders that can't be +/// opened). What is kept is bounded in bytes too ([`MAX_LIST_BYTES`]). +const MAX_MAILBOXES: usize = 12_000; +/// Most bytes of names and flags one LIST keeps, literals included (which +/// [`MAX_COMMAND_TEXT`] doesn't count): 12,000 mailboxes as most servers list them take a +/// megabyte or two; past this the ones after are read and dropped. +const MAX_LIST_BYTES: usize = 16 << 20; +/// Longest mailbox name kept (as the server wrote it); a mailbox with a longer one is left out, +/// since a name cut short would name another mailbox or none. +const MAX_MAILBOX_NAME: usize = 1_024; +/// Longest flag kept, in bytes. +const MAX_FLAG_LEN: usize = 256; +/// Most distinct messages a FETCH may report, beyond twice the mailbox's `EXISTS`. +const FETCH_SLACK: usize = 1_000; +/// Most literals one response may carry. +const MAX_LITERALS: usize = 32; +/// Most text one response may carry outside its literals. +const MAX_TEXT: usize = 4 * MAX_LINE; +/// Most flags kept for one message or mailbox, and most sent in one command. +const MAX_FLAGS: usize = 64; +/// Most of Gmail's labels kept for one message (`X-GM-LABELS`, #1153); the rest are dropped. +pub const MAX_GMAIL_LABELS: usize = 64; +/// Longest of Gmail's labels kept, in bytes as the server wrote it (cut at a character boundary). +const MAX_GMAIL_LABEL_LEN: usize = 256; +/// Most bytes of Gmail's labels one fetch keeps, all its messages together, each label counted +/// with [`LABEL_OVERHEAD`]: past it, a message's labels are not taken (`None`), as if the server +/// hadn't said them. +const MAX_GMAIL_LABEL_BYTES: usize = 32 << 20; +/// What a label kept costs beyond its bytes (its `String`), counted against +/// [`MAX_GMAIL_LABEL_BYTES`] so that many empty or tiny labels can't get past it. +const LABEL_OVERHEAD: usize = std::mem::size_of::<String>(); +/// Text a listing of flags may take for each message the mailbox may report, beyond +/// [`MAX_COMMAND_TEXT`]: a big folder's listing (Gmail's, with labels, runs to a few hundred +/// bytes a message) is never cut short for being big (#1153), and what a hostile server can send +/// stays bounded by the mailbox's size, and by [`MAX_FETCH_TEXT`] whatever size it claims. Only +/// a count: what is kept is bounded on its own ([`MAX_FLAG_BYTES`], [`MAX_GMAIL_LABEL_BYTES`]). +const FETCH_TEXT_PER_MESSAGE: usize = 2 << 10; +/// Most text a listing of flags may take, however many messages the mailbox claims. +const MAX_FETCH_TEXT: usize = 256 << 20; +/// Most bytes of flags one fetch keeps, all its messages together, each message counted with +/// [`ENTRY_OVERHEAD`] and each flag with [`FLAG_OVERHEAD`]: past it the listing fails, so that a +/// server claiming a huge mailbox can't fill memory and no message is taken to have lost its flags. +/// Room for over a million messages with a few flags each. +const MAX_FLAG_BYTES: usize = 256 << 20; +/// What a flag kept costs beyond its bytes (its `String`). +const FLAG_OVERHEAD: usize = std::mem::size_of::<String>(); +/// What a message kept in a listing costs beyond its flags and labels: its entry in the map, with +/// room for the map's own nodes. +const ENTRY_OVERHEAD: usize = 2 * std::mem::size_of::<(u32, (Vec<String>, Option<u64>, Option<Vec<String>>))>(); +const MAX_CAPABILITIES: usize = 256; +/// Longest string sent in quotes; a longer one goes as a literal. +const MAX_QUOTED: usize = 1_000; +/// Most messages named in one set by [`uid_sets`], and most a `COPYUID` answer may speak of. +const MAX_SET_UIDS: usize = 500; +/// Longest set [`uid_sets`] writes, in characters. +const MAX_SET_TEXT: usize = 800; +/// The most UIDs a search answers with that are taken in. +const MAX_FOUND: usize = 1_000; +/// The most UIDs one of Gmail's searches ([`Imap::uid_search_gmail`]) answers with that are taken +/// in: as many as fit the longest line read, at the longest a UID is written. +pub const MAX_GMAIL_FOUND: usize = 5_000; + +/// An IMAP session on a stream. +pub struct Imap<S> { + wire: Wire<S>, + /// The number in the next command's tag. + next_tag: u32, + secrets: Secrets, + /// What the server said it can do, upper-cased; `None` until it has. + capabilities: Option<Vec<String>>, + authenticated: bool, + /// What the mailbox being opened has said about itself so far. + selected: Selected, + /// Every `COPYUID` answer since the last copy or move was sent (`None` for one that couldn't + /// be read); two are as many as it takes to know there was more than one. + copied: Vec<Option<Copied>>, + /// Every `APPENDUID` answer since the last APPEND was sent, as [`Imap::copied`] is kept. + appended: Vec<Option<Appended>>, + /// LOGOUT was sent, so BYE is the answer we asked for. + leaving: bool, + /// Bytes of text (outside literals) read since the current command was sent. + text_seen: usize, + /// Most responses the current command may bring. + response_cap: usize, + /// Most text (outside literals) the current command may bring: [`MAX_COMMAND_TEXT`], or more + /// for a listing of a big mailbox's flags. + text_cap: usize, + /// Untagged lines too long to take are read past instead of ending the session, for the + /// current command alone (a Gmail search, #911); `skipped` says one was. + skip_long: bool, + skipped: bool, + /// The tag of the IDLE command the server is waiting in, if it is ([`Imap::idle_begin`]). + idle_tag: Option<String>, + idle_pending: std::collections::VecDeque<IdleEvent>, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Mailbox { + /// Decoded from modified UTF-7. + pub name: String, + /// The name exactly as the server wrote it (use this in commands). + pub raw: String, + pub delimiter: Option<char>, + /// Flags as written, e.g. `\\Noselect`, `\\Sent`, `\\HasChildren`. + pub flags: Vec<String>, +} + +/// The personal IMAP namespace (RFC 2342): `prefix` (as the server spells it, e.g. `"INBOX."`) and +/// hierarchy `delimiter` (`'.'`, `'/'`), if any. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Namespace { + pub prefix: String, + pub delimiter: Option<char>, +} + +impl Mailbox { + /// Whether the mailbox has `flag` (`\Noselect`), whatever the letter case. + pub fn has_flag(&self, flag: &str) -> bool { + self.flags.iter().any(|f| f.eq_ignore_ascii_case(flag)) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Selected { + pub exists: u32, + pub uid_validity: u32, + pub uid_next: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Fetched { + pub uid: u32, + pub flags: Vec<String>, + /// INTERNALDATE as written by the server, when asked for. + pub internal_date: Option<String>, + /// The whole message (BODY[]), when asked for. + pub body: Option<Vec<u8>>, + /// Gmail's own id of the message (`X-GM-MSGID`, Google's "Gmail IMAP extensions"), when + /// asked for and given; `None` from every other server. + pub gmail_id: Option<u64>, + /// Gmail's labels of the message (`X-GM-LABELS`, Google's "Gmail IMAP extensions", #1153), + /// when asked for and given: as the server wrote them, modified UTF-7 decoded, Gmail's own + /// (`\Inbox`, `\Important`…) with their backslash; at most [`MAX_GMAIL_LABELS`], each cut + /// short. Text from the server, not yet cleaned for showing. `None` from every other server. + pub gmail_labels: Option<Vec<String>>, +} + +/// What became of the messages a UID COPY or UID MOVE named, when the server says (the `COPYUID` +/// response code of RFC 4315). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Copied { + /// `UIDVALIDITY` of the mailbox the messages went to. + pub uid_validity: u32, + /// Each message's UID where it was, and its UID where it is now. + pub uids: Vec<(u32, u32)>, +} + +/// Where a message given with APPEND went, when the server says (the `APPENDUID` response code +/// of RFC 4315). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Appended { + /// `UIDVALIDITY` of the mailbox it went to. + pub uid_validity: u32, + /// Its UID there. + pub uid: u32, +} + +/// Neither the stream nor anything secret is shown. +impl<S> std::fmt::Debug for Imap<S> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Imap").field("next_tag", &self.next_tag).field("authenticated", &self.authenticated).finish_non_exhaustive() + } +} + +/// One response from the server. +enum Response { + /// `+ …`: the server is ready for the rest of the command. + GoAhead, + Status { + tag: Option<String>, + line: StatusLine, + }, + /// Untagged data: `* 3 EXISTS`, `* LIST …`, `* 3 FETCH (…)`. + Data(Vec<Value>), +} + +enum Part<'a> { + Text(Vec<u8>), + Literal(&'a [u8]), +} + +/// A command being put together (without its tag). +struct Command<'a> { + parts: Vec<Part<'a>>, + /// What the log shows in place of the command. + shown: Option<&'static str>, + /// An argument has a NUL, which no IMAP string can carry. + unsendable: bool, +} + +impl<'a> Command<'a> { + fn new(verb: &str) -> Self { + Command { parts: vec![Part::Text(verb.as_bytes().to_vec())], shown: None, unsendable: false } + } + + fn text(&mut self, bytes: &[u8]) { + match self.parts.last_mut() { + Some(Part::Text(text)) => text.extend_from_slice(bytes), + _ => self.parts.push(Part::Text(bytes.to_vec())), + } + } + + /// A bare argument: our own words, or text that was checked. + fn arg(mut self, word: &str) -> Self { + self.text(b" "); + self.text(word.as_bytes()); + self + } + + /// An argument as a quoted string, or as a literal when quotes can't carry it. + fn string(mut self, bytes: &'a [u8]) -> Self { + self.text(b" "); + if bytes.len() <= MAX_QUOTED && bytes.iter().all(|b| matches!(b, b' '..=b'~')) { + let mut quoted = Vec::with_capacity(bytes.len() + 2); + quoted.push(b'"'); + for b in bytes { + if matches!(b, b'"' | b'\\') { + quoted.push(b'\\'); + } + quoted.push(*b); + } + quoted.push(b'"'); + self.text(&quoted); + } else { + self.unsendable |= bytes.contains(&0); + self.parts.push(Part::Literal(bytes)); + } + self + } + + /// An argument that always goes as a literal (a message). + fn literal(mut self, bytes: &'a [u8]) -> Self { + self.text(b" "); + self.parts.push(Part::Literal(bytes)); + self + } + + fn shown_as(mut self, shown: &'static str) -> Self { + self.shown = Some(shown); + self + } + + /// The command for the log: literals by size only. + fn for_log(&self) -> String { + if let Some(shown) = self.shown { + return shown.to_string(); + } + self.parts + .iter() + .map(|part| match part { + Part::Text(text) => String::from_utf8_lossy(text).into_owned(), + Part::Literal(bytes) => format!("({} bytes)", bytes.len()), + }) + .collect() + } +} + +/// What one FETCH response says about a message. +#[derive(Default)] +struct Item { + uid: u32, + flags: Option<Vec<String>>, + internal_date: Option<String>, + body: Option<Vec<u8>>, + /// The header alone (`BODY[HEADER]`). + header: Option<Vec<u8>>, + size: Option<u64>, + /// Gmail's id of the message (`X-GM-MSGID`). + gmail_id: Option<u64>, + /// Gmail's labels of the message (`X-GM-LABELS`). + gmail_labels: Option<Vec<String>>, +} + +impl Item { + /// From `n FETCH (name value name value …)`, the names in any order. + fn from(values: Vec<Value>) -> Option<Item> { + let mut values = values.into_iter(); + values.next()?.number()?; + if !values.next()?.atom()?.eq_ignore_ascii_case("FETCH") { + return None; + } + let Value::List(pairs) = values.next()? else { return None }; + let mut item = Item::default(); + let mut pairs = pairs.into_iter(); + while let Some(name) = pairs.next() { + // Something that isn't a name is skipped, in the hope that a name follows. + let Some(name) = name.atom().map(str::to_ascii_uppercase) else { continue }; + let Some(value) = pairs.next() else { break }; + match (name.as_str(), value) { + ("UID", value) => item.uid = value.number().unwrap_or(0), + ("FLAGS", Value::List(flags)) => item.flags = Some(short_flags(flags)), + ("INTERNALDATE", Value::Str(date)) => item.internal_date = Some(String::from_utf8_lossy(&date).into_owned()), + ("RFC822.SIZE", value) => item.size = value.atom().and_then(|n| n.parse().ok()), + ("X-GM-MSGID", value) => item.gmail_id = value.atom().and_then(gmail_id), + ("X-GM-LABELS", Value::List(labels)) => item.gmail_labels = Some(gmail_labels(labels)), + ("BODY[]" | "RFC822", Value::Str(body)) => item.body = Some(body), + ("BODY[HEADER]" | "RFC822.HEADER", Value::Str(header)) => item.header = Some(header), + _ => {} + } + } + Some(item) + } +} + +/// From `LIST (flags) "delimiter" name`. +fn mailbox_from(values: Vec<Value>) -> Option<Mailbox> { + let mut values = values.into_iter(); + if !values.next()?.atom()?.eq_ignore_ascii_case("LIST") { + return None; + } + let Value::List(flags) = values.next()? else { return None }; + let delimiter = match values.next()? { + Value::Str(d) => String::from_utf8_lossy(&d).chars().next(), + _ => None, + }; + let raw = values.next()?.into_text()?; + if raw.len() > MAX_MAILBOX_NAME { + return None; + } + Some(Mailbox { name: decode_utf7(&raw), raw, delimiter, flags: short_flags(flags) }) +} + +/// From `NAMESPACE ((prefix delimiter) ...) other shared` (RFC 2342): the first personal namespace. +fn namespace_from(values: Vec<Value>) -> Option<Namespace> { + let mut values = values.into_iter(); + if !values.next()?.atom()?.eq_ignore_ascii_case("NAMESPACE") { + return None; + } + let Value::List(personal) = values.next()? else { return None }; + let Value::List(desc) = personal.into_iter().next()? else { return None }; + let mut desc = desc.into_iter(); + let prefix = desc.next()?.into_text()?; + if prefix.len() > MAX_MAILBOX_NAME { + return None; + } + let delimiter = match desc.next()? { + Value::Str(d) => String::from_utf8_lossy(&d).chars().next(), + _ => None, + }; + Some(Namespace { prefix, delimiter }) +} + +/// The flags of a list, as many as are kept and each cut at a character boundary. +fn short_flags(flags: Vec<Value>) -> Vec<String> { + flags + .into_iter() + .filter_map(Value::into_text) + .take(MAX_FLAGS) + .map(|mut flag| { + if flag.len() > MAX_FLAG_LEN { + let mut end = MAX_FLAG_LEN; + while !flag.is_char_boundary(end) { + end = end.saturating_sub(1); + } + flag = flag.get(..end).unwrap_or_default().to_owned(); + } + flag + }) + .collect() +} + +/// Gmail's labels of a message (`X-GM-LABELS`): a list of atoms and strings, modified UTF-7 as +/// mailbox names are; as many as are kept, each cut at a character boundary before it is decoded. +/// Anything in the list that isn't an atom or a string (a list) is skipped. +fn gmail_labels(labels: Vec<Value>) -> Vec<String> { + labels + .into_iter() + // `NIL` in the list is nothing, not a label (a label called so comes quoted). + .filter(|value| !value.atom().is_some_and(|atom| atom.eq_ignore_ascii_case("NIL"))) + .filter_map(Value::into_text) + .take(MAX_GMAIL_LABELS) + .map(|mut label| { + if label.len() > MAX_GMAIL_LABEL_LEN { + let mut end = MAX_GMAIL_LABEL_LEN; + while !label.is_char_boundary(end) { + end = end.saturating_sub(1); + } + label.truncate(end); + } + decode_utf7(&label) + }) + .collect() +} + +/// A message set as ranges of UIDs (`*` as `top`); `None` when it can't be read. +fn set_ranges(set: &str, top: u32) -> Option<Vec<(u32, u32)>> { + let bound = |text: &str| if text == "*" { Some(top) } else { number(text) }; + set.split(',') + .map(|part| { + // A wildcard-only fetch is resolved by the server, not a stale client snapshot. + if part == "*" || part == "*:*" { + return Some((1, top)); + } + let (a, b) = match part.split_once(':') { + Some((a, b)) => (bound(a)?, bound(b)?), + None => (bound(part)?, bound(part)?), + }; + Some((a.min(b), a.max(b))) + }) + .collect() +} + +/// What a FETCH of a set may report: only UIDs in the set, and not more distinct +/// ones than a mailbox of this size can hold. +struct Wanted { + ranges: Vec<(u32, u32)>, + cap: usize, + over: bool, +} + +impl Wanted { + fn new(set: &str, selected: &Selected) -> Option<Wanted> { + // UIDNEXT is a SELECT-time snapshot; new deliveries can have larger UIDs. + let ranges = set_ranges(set, u32::MAX)?; + let cap = usize::try_from(selected.exists).unwrap_or(usize::MAX).saturating_mul(2).saturating_add(FETCH_SLACK); + Some(Wanted { ranges, cap, over: false }) + } + + /// Most responses a fetch of this mailbox may bring: one for each message it may report, but + /// never fewer than any other command. + fn responses(&self) -> usize { + self.cap.max(MAX_RESPONSES) + } + + fn wants(&self, uid: u32) -> bool { + uid != 0 && self.ranges.iter().any(|(from, to)| (*from..=*to).contains(&uid)) + } + + /// Whether one more distinct UID fits after `count`; if not, the command fails. + fn room(&mut self, count: usize) -> bool { + if count >= self.cap { + self.over = true; + } + !self.over + } + + fn check(&self) -> Result<(), ProtoError> { + if self.over { Err(ProtoError::Protocol(said!("the server reported more messages than the mailbox holds"))) } else { Ok(()) } + } +} + +/// A message set: `1:*`, `5,9,12:20`. +fn is_set(set: &str) -> bool { + !set.is_empty() && set.len() <= MAX_QUOTED && set.bytes().all(|b| b.is_ascii_digit() || matches!(b, b':' | b',' | b'*')) +} + +/// A flag or keyword: `\Seen`, `$Forwarded`. +fn is_flag(flag: &str) -> bool { + let word = flag.strip_prefix('\\').unwrap_or(flag); + !word.is_empty() + && word.len() <= 100 + && word.bytes().all(|b| b.is_ascii_graphic() && !matches!(b, b'(' | b')' | b'{' | b'%' | b'*' | b'"' | b'\\' | b']')) +} + +/// `(\Seen \Flagged)`, once every flag is known to be one. +fn flag_list(flags: &[&str]) -> Result<String, ProtoError> { + if flags.len() > MAX_FLAGS { + return Err(ProtoError::Protocol(said!("too many flags for one command"))); + } + match flags.iter().find(|f| !is_flag(f)) { + Some(bad) => Err(ProtoError::Protocol(said!("\"{flag}\" can't be used as a flag", flag = tidy(bad)))), + None => Ok(format!("({})", flags.join(" "))), + } +} + +/// Gmail's id of a message (`X-GM-MSGID`): a 64-bit number, written in digits alone; 0 is none. +fn gmail_id(text: &str) -> Option<u64> { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse().ok().filter(|id| *id != 0) +} + +/// A number as IMAP writes one: digits and nothing else. +fn number(text: &str) -> Option<u32> { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse().ok() +} + +/// The UIDs a set names, in the order written (`4,7:9` is 4, 7, 8, 9). `None` for a set that +/// doesn't name its messages one by one beyond doubt: `*`, zero, a range written backwards, or +/// more than [`MAX_SET_UIDS`] numbers. +fn uids_of(set: &str) -> Option<Vec<u32>> { + let mut out: Vec<u32> = Vec::new(); + for part in set.split(',') { + let (first, last) = match part.split_once(':') { + Some((first, last)) => (number(first)?, number(last)?), + None => { + let one = number(part)?; + (one, one) + } + }; + if first == 0 || first > last || (last - first) as usize >= MAX_SET_UIDS.saturating_sub(out.len()) { + return None; + } + out.extend(first..=last); + } + Some(out) +} + +/// A set for a command that changes things: it names its messages number by number. `1:*` +/// would take in messages nobody looked at. +fn named(set: &str) -> Result<&str, ProtoError> { + if set.len() <= MAX_QUOTED && uids_of(set).is_some() { + Ok(set) + } else { + Err(ProtoError::Protocol(said!("\"{set}\" doesn't name the messages to change", set = tidy(set)))) + } +} + +/// From the text of a `COPYUID` code: `<uidvalidity> <where they were> <where they are>`. +/// `None` unless it pairs every message beyond doubt (the first set strictly ascending, the +/// second as long and without repeats): a wrong pairing would tie a message here to another one +/// on the server. +fn copied_from(arg: &str) -> Option<Copied> { + let mut words = arg.split_whitespace(); + let uid_validity = number(words.next()?).filter(|validity| *validity != 0)?; + let (from, to) = (uids_of(words.next()?)?, uids_of(words.next()?)?); + let mut distinct = to.clone(); + distinct.sort_unstable(); + distinct.dedup(); + if words.next().is_some() || from.len() != to.len() || distinct.len() != to.len() || !from.is_sorted_by(|a, b| a < b) { + return None; + } + Some(Copied { uid_validity, uids: from.into_iter().zip(to).collect() }) +} + +/// From the text of an `APPENDUID` code: `<uidvalidity> <uid>`, for one message. `None` for +/// anything else (a set of UIDs speaks of more than the one message given). +fn appended_from(arg: &str) -> Option<Appended> { + let mut words = arg.split_whitespace(); + let uid_validity = number(words.next()?).filter(|validity| *validity != 0)?; + let uid = number(words.next()?).filter(|uid| *uid != 0)?; + words.next().is_none().then_some(Appended { uid_validity, uid }) +} + +/// Whether `text` is an IMAP `date-time` without its quotes (RFC 3501): `01-Jul-2003 09:52:37 +/// +0000`, the day padded with a space or a nought. +fn is_date_time(text: &str) -> bool { + let b = text.as_bytes(); + let digits = |range: std::ops::Range<usize>| b.get(range).is_some_and(|d| d.iter().all(u8::is_ascii_digit)); + let at = |i: usize, c: u8| b.get(i) == Some(&c); + b.len() == 26 + && (digits(0..2) || (at(0, b' ') && digits(1..2))) + && at(2, b'-') + && b.get(3..6).is_some_and(|m| m.iter().all(u8::is_ascii_alphabetic)) + && at(6, b'-') + && digits(7..11) + && at(11, b' ') + && digits(12..14) + && at(14, b':') + && digits(15..17) + && at(17, b':') + && digits(18..20) + && at(20, b' ') + && (at(21, b'+') || at(21, b'-')) + && digits(22..26) +} + +/// Whether [`Imap::uid_search_header`] can look for `text`: printable ASCII, at most +/// [`MAX_QUOTED`] bytes. What it can't be asked for, it refuses unsent. +pub fn searchable(text: &str) -> bool { + !text.is_empty() && text.len() <= MAX_QUOTED && text.bytes().all(|b| matches!(b, b' '..=b'~')) +} + +/// UIDs as message sets for commands (`4,7:9,12`), each with the UIDs it names: sorted, each UID +/// once, consecutive numbers as ranges, and no set longer than one command should carry. A +/// range only ever spans numbers that were asked for. +pub fn uid_sets(uids: &[u32]) -> Vec<(String, Vec<u32>)> { + let mut sorted: Vec<u32> = uids.iter().copied().filter(|uid| *uid != 0).collect(); + sorted.sort_unstable(); + sorted.dedup(); + let mut sets = Vec::new(); + let (mut text, mut uids_named) = (String::new(), Vec::new()); + let mut at = 0; + // Every round takes at least one UID off the list. + while let Some(&first) = sorted.get(at) { + let (mut last, mut next) = (first, at + 1); + while uids_named.len() + (next - at) < MAX_SET_UIDS && sorted.get(next).is_some_and(|uid| last.checked_add(1) == Some(*uid)) { + last = last.saturating_add(1); + next += 1; + } + let range = if last == first { first.to_string() } else { format!("{first}:{last}") }; + if !text.is_empty() && text.len() + 1 + range.len() > MAX_SET_TEXT { + sets.push((std::mem::take(&mut text), std::mem::take(&mut uids_named))); + } + if !text.is_empty() { + text.push(','); + } + text.push_str(&range); + uids_named.extend_from_slice(sorted.get(at..next).unwrap_or(&[])); + at = next; + if uids_named.len() >= MAX_SET_UIDS { + sets.push((std::mem::take(&mut text), std::mem::take(&mut uids_named))); + } + } + if !text.is_empty() { + sets.push((text, uids_named)); + } + sets +} + +fn ignore(_: Vec<Value>) {} + +impl<S: Read + Write> Imap<S> { + /// Read the greeting (`* OK` or `* PREAUTH`; `* BYE` is an error). + pub fn connect(stream: S) -> Result<Self, ProtoError> { + let mut imap = Self::resume(stream); + match imap.read_response()? { + Response::Status { tag: None, line } => match line.status { + Status::Ok | Status::Preauth => { + imap.authenticated = line.status == Status::Preauth; + imap.note_status(&line); + Ok(imap) + } + Status::Bye => Err(ProtoError::Rejected(imap.refusal(&line))), + Status::No | Status::Bad => { + Err(ProtoError::Protocol(said!("the server greeted with a refusal: {reason}", reason = Arg::said(imap.refusal(&line))))) + } + }, + _ => Err(ProtoError::Protocol(said!("the server didn't greet like an IMAP server"))), + } + } + + /// Continue on a stream that already greeted (after the caller wrapped it in TLS). + pub fn resume(stream: S) -> Self { + Imap { + wire: Wire::new(stream), + next_tag: 1, + secrets: Secrets::default(), + capabilities: None, + authenticated: false, + selected: Selected::default(), + copied: Vec::new(), + appended: Vec::new(), + leaving: false, + text_seen: 0, + response_cap: MAX_RESPONSES, + text_cap: MAX_COMMAND_TEXT, + skip_long: false, + skipped: false, + idle_tag: None, + idle_pending: std::collections::VecDeque::new(), + } + } + + /// Whether the session is signed in: after [`login`](Self::login) or + /// [`authenticate_xoauth2`](Self::authenticate_xoauth2), or from the start when the server greeted with PREAUTH. + pub fn is_authenticated(&self) -> bool { + self.authenticated + } + + /// The stream the session runs on, for its owner to set up between commands (how long a + /// socket waits, say). Reading from it or writing to it would take the session apart. + pub fn get_mut(&mut self) -> &mut S { + self.wire.get_mut() + } + + /// Whether the server has said it can do `capability` (upper-cased); `false` while it hasn't said anything. + fn offers(&self, capability: &str) -> bool { + self.capabilities.as_ref().is_some_and(|caps| caps.iter().any(|c| c == capability)) + } + + /// Upper-cased capability atoms (`IMAP4REV1`, `STARTTLS`, `SPECIAL-USE`…). + pub fn capabilities(&mut self) -> Result<Vec<String>, ProtoError> { + self.capabilities = None; + self.run(Command::new("CAPABILITY"), &mut ignore)?; + Ok(self.capabilities.clone().unwrap_or_default()) + } + + /// Send STARTTLS and hand the stream back for the caller to wrap; call `resume` afterwards. + pub fn starttls(mut self) -> Result<S, ProtoError> { + self.run(Command::new("STARTTLS"), &mut ignore)?; + // Anything after the go-ahead was slipped in before encryption started. + if self.wire.has_pending() { + return Err(ProtoError::Protocol(said!("the server sent data before the secure connection started"))); + } + Ok(self.wire.into_inner()) + } + + /// LOGIN with properly quoted (or literal) strings. NO → `ProtoError::Auth`. + pub fn login(&mut self, user: &str, password: &str) -> Result<(), ProtoError> { + if user.contains('\0') || password.contains('\0') { + return Err(ProtoError::Auth(said!("the user name or password has a character that can't be sent"))); + } + // RFC 3501 §6.2.3: a server that says LOGINDISABLED must not be sent a password. + if self.offers("LOGINDISABLED") { + return Err(ProtoError::Auth(said!("the server doesn't take a password on this connection"))); + } + self.secrets.add(password); + let command = Command::new("LOGIN").string(user.as_bytes()).string(password.as_bytes()).shown_as("LOGIN ***"); + let line = self.exchange(command, &mut ignore)?; + match line.status { + Status::Ok => { + self.authenticated = true; + Ok(()) + } + Status::No => Err(ProtoError::Auth(self.refusal(&line))), + _ => Err(ProtoError::Rejected(self.refusal(&line))), + } + } + + /// AUTHENTICATE XOAUTH2: an OAuth access token in place of a password. NO → `ProtoError::Auth`. + /// + /// The token goes out with the command (RFC 4959) only to a server that listed both + /// `SASL-IR` and `AUTH=XOAUTH2`. Any other server, one that listed neither or hasn't said + /// what it can do, is tried all the same, but asked first: it gets the token after its + /// go-ahead, so one that doesn't know the mechanism refuses without having seen it. + pub fn authenticate_xoauth2(&mut self, user: &str, token: &str) -> Result<(), ProtoError> { + let payload = xoauth2(user, token)?; + self.secrets.add(token); + self.secrets.add(&payload); + let inline = self.offers("SASL-IR") && self.offers("AUTH=XOAUTH2"); + let tag = self.tag(); + log::trace!("C: {tag} AUTHENTICATE XOAUTH2{}", if inline { " ***" } else { "" }); + let mut out = format!("{tag} AUTHENTICATE XOAUTH2"); + if inline { + out.push(' '); + out.push_str(&payload); + } + out.push_str("\r\n"); + self.wire.write(out.as_bytes())?; + self.wire.flush()?; + // What each `+` from the server is answered with: the token (unless it went with the + // command), an empty line for the reasons a refusal starts with (JSON in base64), and + // for a question after that, the end of the exchange. + let answers = [(payload.as_str(), "***"), ("", ""), ("*", "*")]; + let mut asked = usize::from(inline); + let line = loop { + if let Some(line) = self.read_until(&tag, true, &mut ignore)? { + break line; + } + let Some((answer, shown)) = answers.get(asked) else { + return Err(ProtoError::Protocol(said!("the server asked for more than a sign-in has"))); + }; + asked += 1; + log::trace!("C: {shown}"); + self.wire.write(format!("{answer}\r\n").as_bytes())?; + self.wire.flush()?; + }; + match line.status { + // The exchange was called off, whatever the server makes of that. + _ if asked == answers.len() => Err(ProtoError::Auth(said!("the server asked for more than a user name and access token"))), + // Nobody is signed in by a token that was never sent. + Status::Ok if asked == 0 => Err(ProtoError::Protocol(said!("the server ended the command early"))), + Status::Ok => { + self.authenticated = true; + Ok(()) + } + Status::No => Err(ProtoError::Auth(self.refusal(&line))), + _ => Err(ProtoError::Rejected(self.refusal(&line))), + } + } + + /// LIST "" "*". + pub fn list(&mut self) -> Result<Vec<Mailbox>, ProtoError> { + self.list_counted().map(|(list, _)| list) + } + + /// [`list`](Self::list), and how many more mailboxes the server listed that were read and + /// dropped because the list was full ([`MAX_MAILBOXES`], [`MAX_LIST_BYTES`]): 0 when it + /// was kept whole. + pub fn list_counted(&mut self) -> Result<(Vec<Mailbox>, usize), ProtoError> { + let mut out: Vec<Mailbox> = Vec::new(); + let mut seen = HashSet::new(); + let (mut kept, mut dropped) = (0usize, 0usize); + self.run(Command::new("LIST").arg("\"\"").arg("\"*\""), &mut |values| { + let full = out.len() >= MAX_MAILBOXES || kept >= MAX_LIST_BYTES; + // A mailbox the server names twice is listed once; past either cap, nothing is kept. + let Some(mailbox) = mailbox_from(values) else { return }; + if full { + dropped = dropped.saturating_add(1); + } else if seen.insert(mailbox.raw.clone()) { + // The name twice (as written, decoded) and once more in `seen`, and the flags. + let size = mailbox.raw.len().saturating_mul(2).saturating_add(mailbox.name.len()); + kept = mailbox.flags.iter().fold(kept.saturating_add(size), |kept, flag| kept.saturating_add(flag.len())); + out.push(mailbox); + } + })?; + Ok((out, dropped)) + } + + /// NAMESPACE (RFC 2342): the server's first personal namespace, or `None` when the server + /// offers no `NAMESPACE` capability or names no personal namespace. + pub fn namespace(&mut self) -> Result<Option<Namespace>, ProtoError> { + if !self.offers("NAMESPACE") { + return Ok(None); + } + let mut found = None; + self.run(Command::new("NAMESPACE"), &mut |values| { + if found.is_none() { + found = namespace_from(values); + } + })?; + Ok(found) + } + + /// EXAMINE (read-only) or SELECT. + pub fn select(&mut self, raw_name: &str, read_only: bool) -> Result<Selected, ProtoError> { + self.selected = Selected::default(); + let command = Command::new(if read_only { "EXAMINE" } else { "SELECT" }).string(raw_name.as_bytes()); + self.run(command, &mut ignore)?; + Ok(self.selected.clone()) + } + + /// UID FETCH <set> (UID FLAGS): every message in the set with its flags. `set` like "1:*" or "5,9,12:20". + /// + /// The messages come back in UID order, each once. + pub fn uid_fetch_flags(&mut self, set: &str) -> Result<Vec<Fetched>, ProtoError> { + self.fetch_flags(set, false, false) + } + + /// [`uid_fetch_flags`](Self::uid_fetch_flags), with Gmail's id and labels of each message as + /// well (`UID FETCH <set> (UID FLAGS X-GM-MSGID X-GM-LABELS)`, in [`Fetched::gmail_id`] and + /// [`Fetched::gmail_labels`]): for Gmail's server alone, which documents them among its IMAP + /// extensions. A message it gives no id, or one that isn't a number, has none; one it gives + /// no labels has `None` there, and one past [`MAX_GMAIL_LABEL_BYTES`] of labels in the fetch + /// too. + pub fn uid_fetch_flags_gmail(&mut self, set: &str) -> Result<Vec<Fetched>, ProtoError> { + self.fetch_flags(set, true, true) + } + + /// [`uid_fetch_flags`](Self::uid_fetch_flags), with Gmail's labels of each message as well but + /// not its id (`UID FETCH <set> (UID FLAGS X-GM-LABELS)`, in [`Fetched::gmail_labels`]): for a + /// Gmail folder whose ids aren't wanted (every folder but the Inbox), so that its listing is + /// no longer than it has to be. + pub fn uid_fetch_flags_labels(&mut self, set: &str) -> Result<Vec<Fetched>, ProtoError> { + self.fetch_flags(set, false, true) + } + + fn fetch_flags(&mut self, set: &str, ids: bool, labels_wanted: bool) -> Result<Vec<Fetched>, ProtoError> { + type FetchedFlags = (Vec<String>, Option<u64>, Option<Vec<String>>); + let mut found: BTreeMap<u32, FetchedFlags> = BTreeMap::new(); + // The bytes of labels and of flags kept so far, all messages together. + let mut label_bytes = 0usize; + let mut flag_bytes = 0usize; + let items = match (ids, labels_wanted) { + (true, true) => "(UID FLAGS X-GM-MSGID X-GM-LABELS)", + (true, false) => "(UID FLAGS X-GM-MSGID)", + (false, true) => "(UID FLAGS X-GM-LABELS)", + (false, false) => "(UID FLAGS)", + }; + let command = Self::fetch(set, items)?; + let mut wanted = Wanted::new(set, &self.selected).ok_or_else(|| ProtoError::Protocol(said!("not a set of messages")))?; + self.response_cap = wanted.responses(); + let claimed = usize::try_from(self.selected.exists).unwrap_or(usize::MAX); + self.text_cap = claimed.saturating_mul(FETCH_TEXT_PER_MESSAGE).clamp(MAX_COMMAND_TEXT, MAX_FETCH_TEXT); + let answered = self.run(command, &mut |values| { + // A response with a UID shows the message is there, even one that forgot the flags. + if flag_bytes <= MAX_FLAG_BYTES + && let Some(item) = Item::from(values) + && wanted.wants(item.uid) + && (found.contains_key(&item.uid) || wanted.room(found.len())) + { + // Each word counted as it comes, a repeat included: past the budget nothing more + // is kept and the listing fails below. + let size = item.flags.iter().flatten().map(|flag| flag.len().saturating_add(FLAG_OVERHEAD)).sum::<usize>(); + let entry = if found.contains_key(&item.uid) { 0 } else { ENTRY_OVERHEAD }; + flag_bytes = flag_bytes.saturating_add(size).saturating_add(entry); + if flag_bytes > MAX_FLAG_BYTES { + return; + } + let (flags, id, labels) = found.entry(item.uid).or_default(); + // When the server speaks of a message twice, its later word counts. + if let Some(later) = item.flags { + *flags = later; + } + if ids && item.gmail_id.is_some() { + *id = item.gmail_id; + } + if labels_wanted && let Some(later) = item.gmail_labels { + let size = later.iter().map(|label| label.len().saturating_add(LABEL_OVERHEAD)).sum::<usize>(); + if label_bytes.saturating_add(size) <= MAX_GMAIL_LABEL_BYTES { + label_bytes = label_bytes.saturating_add(size); + *labels = Some(later); + } + } + } + }); + self.response_cap = MAX_RESPONSES; + self.text_cap = MAX_COMMAND_TEXT; + answered?; + if flag_bytes > MAX_FLAG_BYTES { + return Err(ProtoError::Protocol(said!("more flags than one listing keeps"))); + } + wanted.check()?; + Ok(found + .into_iter() + .map(|(uid, (flags, gmail_id, gmail_labels))| Fetched { uid, flags, internal_date: None, body: None, gmail_id, gmail_labels }) + .collect()) + } + + /// UID FETCH <set> (UID RFC822.SIZE): the size in bytes of every message in the set, in UID order. + pub fn uid_fetch_sizes(&mut self, set: &str) -> Result<Vec<(u32, u64)>, ProtoError> { + let mut out: Vec<(u32, u64)> = Vec::new(); + let command = Self::fetch(set, "(UID RFC822.SIZE)")?; + let mut wanted = Wanted::new(set, &self.selected).ok_or_else(|| ProtoError::Protocol(said!("not a set of messages")))?; + self.response_cap = wanted.responses(); + let answered = self.run(command, &mut |values| { + if let Some(Item { uid, size: Some(size), .. }) = Item::from(values) + && wanted.wants(uid) + && wanted.room(out.len()) + { + out.push((uid, size)); + } + }); + self.response_cap = MAX_RESPONSES; + answered?; + wanted.check()?; + out.sort_by_key(|(uid, _)| *uid); + out.dedup_by_key(|(uid, _)| *uid); + Ok(out) + } + + /// UID FETCH <uid> (UID FLAGS INTERNALDATE BODY.PEEK[]); `None` when the UID is gone. + pub fn uid_fetch_message(&mut self, uid: u32) -> Result<Option<Fetched>, ProtoError> { + self.fetch_one(uid, "(UID FLAGS INTERNALDATE BODY.PEEK[])", false) + } + + /// UID FETCH <uid> (UID FLAGS INTERNALDATE BODY.PEEK[HEADER]): the header alone of a message + /// that is not taken whole (one that is too large), in [`Fetched::body`], up to and with the + /// empty line that ends it. `None` when the UID is gone. + pub fn uid_fetch_header(&mut self, uid: u32) -> Result<Option<Fetched>, ProtoError> { + self.fetch_one(uid, "(UID FLAGS INTERNALDATE BODY.PEEK[HEADER])", true) + } + + /// One message with its flags and date, and either all of it or (`header_only`) its header. + fn fetch_one(&mut self, uid: u32, items: &str, header_only: bool) -> Result<Option<Fetched>, ProtoError> { + if uid == 0 { + return Ok(None); + } + let mut found: Option<Fetched> = None; + self.run(Self::fetch(&uid.to_string(), items)?, &mut |values| { + // Other messages may be mentioned in passing; this one may come in more than one response. + if let Some(item) = Item::from(values) + && item.uid == uid + { + let message = found.get_or_insert_with(|| Fetched { uid, ..Default::default() }); + if let Some(flags) = item.flags { + message.flags = flags; + } + message.internal_date = item.internal_date.or(message.internal_date.take()); + // Only what was asked for: a whole message in answer to a question about its + // header is not taken in. + let asked_for = if header_only { item.header } else { item.body }; + message.body = asked_for.or(message.body.take()); + } + })?; + Ok(found.filter(|message| message.body.is_some())) + } + + /// UID STORE <uid> +FLAGS.SILENT / -FLAGS.SILENT (flags). + pub fn uid_store(&mut self, uid: u32, add: bool, flags: &[&str]) -> Result<(), ProtoError> { + let flags = flag_list(flags)?; + if uid == 0 { + return Err(ProtoError::Protocol(said!("a message that isn't on the server has no flags there"))); + } + self.store(&uid.to_string(), add, &flags) + } + + /// UID STORE <set> +FLAGS.SILENT / -FLAGS.SILENT (flags): the same change for every message + /// the set names (number by number, as [`uid_sets`] writes it; `1:*` is refused). A UID that + /// is no longer there is passed over by the server without a word. + pub fn uid_store_set(&mut self, set: &str, add: bool, flags: &[&str]) -> Result<(), ProtoError> { + let flags = flag_list(flags)?; + self.store(named(set)?, add, &flags) + } + + /// UID SEARCH UNDELETED HEADER <field> <text>: the messages of the open mailbox, other than + /// those marked as deleted, whose header field `field` has `text` in it (the server matches a + /// part of the field, whatever its case), by UID in UID order, at most [`MAX_FOUND`] of them. + /// `field` is a field's name, and `text` one that [`searchable`] lets through: anything else + /// is refused unsent. + pub fn uid_search_header(&mut self, field: &str, text: &str) -> Result<Vec<u32>, ProtoError> { + if field.is_empty() || !field.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') { + return Err(ProtoError::Protocol(said!("\"{field}\" is not the name of a header field", field = tidy(field)))); + } + if !searchable(text) { + return Err(ProtoError::Protocol(said!("the text can't be looked for on the server"))); + } + let mut found = BTreeSet::new(); + let command = Command::new("UID SEARCH UNDELETED HEADER").arg(field).string(text.as_bytes()); + self.run(command, &mut |values| { + if values.first().and_then(Value::atom).is_some_and(|word| word.eq_ignore_ascii_case("SEARCH")) { + let uids = values.iter().skip(1).filter_map(Value::atom).filter_map(|n| n.parse::<u32>().ok()).filter(|uid| *uid != 0); + for uid in uids { + if found.len() >= MAX_FOUND { + break; + } + found.insert(uid); + } + } + })?; + Ok(found.into_iter().collect()) + } + + /// UID SEARCH UID <set> UNDELETED X-GM-RAW "<query>": the messages of the open mailbox, among + /// those `set` names and not marked as deleted, that Gmail's own search finds for `query` + /// (`category:social`), by UID in UID order. `X-GM-RAW` is Gmail's (Google's "Gmail IMAP extensions"): for Gmail's server alone. + /// + /// The query goes in quotes, without the CR, LF and NUL that could end the command early; one + /// that is empty then, or isn't printable ASCII within [`MAX_QUOTED`] bytes, is refused unsent. + /// Of the answer, only UIDs inside `set` are taken, at most [`MAX_GMAIL_FOUND`] of them: a + /// caller that wants them all asks for sets of fewer messages than that. An answer longer than + /// [`MAX_LINE`](crate::MAX_LINE) is read past and refused ([`ProtoError::Rejected`]): the + /// session goes on. + pub fn uid_search_gmail(&mut self, set: &str, query: &str) -> Result<Vec<u32>, ProtoError> { + if !is_set(set) { + return Err(ProtoError::Protocol(said!("\"{set}\" is not a set of messages", set = tidy(set)))); + } + let ranges = set_ranges(set, u32::MAX).ok_or_else(|| ProtoError::Protocol(said!("not a set of messages")))?; + let query: String = query.chars().filter(|c| !matches!(c, '\r' | '\n' | '\0')).collect(); + if !searchable(&query) { + return Err(ProtoError::Protocol(said!("the text can't be looked for on the server"))); + } + let mut found = BTreeSet::new(); + // Messages marked as deleted aren't shown, so they aren't asked about either. + let command = Command::new("UID SEARCH UID").arg(set).arg("UNDELETED X-GM-RAW").string(query.as_bytes()); + (self.skip_long, self.skipped) = (true, false); + let answer = self.run(command, &mut |values| { + if values.first().and_then(Value::atom).is_some_and(|word| word.eq_ignore_ascii_case("SEARCH")) { + let uids = values.iter().skip(1).filter_map(Value::number).filter(|uid| *uid != 0); + for uid in uids.filter(|uid| ranges.iter().any(|(from, to)| (*from..=*to).contains(uid))) { + if found.len() >= MAX_GMAIL_FOUND { + break; + } + found.insert(uid); + } + } + }); + let skipped = std::mem::take(&mut self.skipped); + self.skip_long = false; + answer?; + // An answer too long to read is no answer: the session goes on without it. + if skipped { + return Err(ProtoError::Rejected(said!("the server's answer was longer than {kb} KB", kb = crate::MAX_LINE / 1024))); + } + Ok(found.into_iter().collect()) + } + + fn store(&mut self, set: &str, add: bool, flags: &str) -> Result<(), ProtoError> { + // No flags: nothing to ask of the server. + if flags == "()" { + return Ok(()); + } + let command = Command::new("UID STORE").arg(set).arg(if add { "+FLAGS.SILENT" } else { "-FLAGS.SILENT" }).arg(flags); + self.run(command, &mut ignore).map(|_| ()) + } + + /// UID MOVE <set> <mailbox> (RFC 6851, for a server that offers `MOVE`): the messages leave + /// the open mailbox for the named one in one step. Answers where they are now when the + /// server says so beyond doubt (`COPYUID`), `None` otherwise. + pub fn uid_move(&mut self, set: &str, raw_name: &str) -> Result<Option<Copied>, ProtoError> { + self.transfer("UID MOVE", set, raw_name) + } + + /// UID COPY <set> <mailbox>: copies of the messages are added to the named mailbox. Answers + /// like [`uid_move`](Self::uid_move). + pub fn uid_copy(&mut self, set: &str, raw_name: &str) -> Result<Option<Copied>, ProtoError> { + self.transfer("UID COPY", set, raw_name) + } + + fn transfer(&mut self, verb: &str, set: &str, raw_name: &str) -> Result<Option<Copied>, ProtoError> { + let command = Command::new(verb).arg(named(set)?).string(raw_name.as_bytes()); + self.copied.clear(); + let done = self.run(command, &mut ignore); + // One answer that could be read, or nothing is known: two that might disagree are none. + let copied = match std::mem::take(&mut self.copied).as_mut_slice() { + [only] => only.take(), + _ => None, + }; + done.map(|_| copied) + } + + /// UID EXPUNGE <set> (RFC 4315): the messages of the set that are marked `\Deleted` go for + /// good, and no others. Refused unsent unless the server has said `UIDPLUS`: a server + /// without it only knows the EXPUNGE that takes every marked message of the mailbox. + pub fn uid_expunge(&mut self, set: &str) -> Result<(), ProtoError> { + let set = named(set)?; + if !self.offers("UIDPLUS") { + return Err(ProtoError::Protocol(said!("the server can't remove single messages (it doesn't offer UIDPLUS)"))); + } + self.run(Command::new("UID EXPUNGE").arg(set), &mut ignore).map(|_| ()) + } + + /// CREATE <mailbox>. `raw_name` is the name as the server wants it: in modified UTF-7 + /// ([`encode_utf7`]), its levels joined with the server's own delimiter. + pub fn create(&mut self, raw_name: &str) -> Result<(), ProtoError> { + self.run(Command::new("CREATE").string(raw_name.as_bytes()), &mut ignore).map(|_| ()) + } + + /// SUBSCRIBE <mailbox>: other mail programs list subscribed mailboxes only. + pub fn subscribe(&mut self, raw_name: &str) -> Result<(), ProtoError> { + self.run(Command::new("SUBSCRIBE").string(raw_name.as_bytes()), &mut ignore).map(|_| ()) + } + + /// APPEND with a literal (handles the `+` continuation). + pub fn append(&mut self, raw_name: &str, flags: &[&str], message: &[u8]) -> Result<(), ProtoError> { + self.append_at(raw_name, flags, None, message).map(|_| ()) + } + + /// [`append`](Self::append), with the time the server is to keep as the message's arrival + /// (its `INTERNALDATE`, an IMAP `date-time` such as `01-Jul-2003 09:52:37 +0000`) when one is + /// given. Answers where the message went when the server says so beyond doubt (`APPENDUID`), + /// `None` otherwise. + pub fn append_at(&mut self, raw_name: &str, flags: &[&str], date: Option<&str>, message: &[u8]) -> Result<Option<Appended>, ProtoError> { + let mut command = Command::new("APPEND").string(raw_name.as_bytes()); + if !flags.is_empty() { + command = command.arg(&flag_list(flags)?); + } + if let Some(date) = date { + if !is_date_time(date) { + return Err(ProtoError::Protocol(said!("\"{date}\" is not a date and time IMAP can carry", date = tidy(date)))); + } + command = command.arg(&format!("\"{date}\"")); + } + self.appended.clear(); + let done = self.run(command.literal(message), &mut ignore); + // One answer that could be read, or nothing is known. + let appended = match std::mem::take(&mut self.appended).as_mut_slice() { + [only] => only.take(), + _ => None, + }; + done.map(|_| appended) + } + + /// LOGOUT. A server that hangs up without answering has logged us out all the same. + pub fn logout(mut self) -> Result<(), ProtoError> { + self.leaving = true; + match self.run(Command::new("LOGOUT"), &mut ignore) { + Ok(_) | Err(ProtoError::Io(_)) => Ok(()), + Err(e) => Err(e), + } + } + + fn fetch(set: &str, items: &str) -> Result<Command<'static>, ProtoError> { + if !is_set(set) { + return Err(ProtoError::Protocol(said!("\"{set}\" is not a set of messages", set = tidy(set)))); + } + Ok(Command::new("UID FETCH").arg(set).arg(items)) + } + + /// How many commands have been sent on this connection (the tags used so far). + pub fn commands(&self) -> u32 { + self.next_tag.wrapping_sub(1) + } + + /// The tag of the next command. + fn tag(&mut self) -> String { + let tag = format!("A{:04}", self.next_tag); + self.next_tag = self.next_tag.wrapping_add(1); + tag + } + + /// Run a command that must end in OK; untagged data goes to `on_data` as it arrives. + fn run(&mut self, command: Command<'_>, on_data: &mut dyn FnMut(Vec<Value>)) -> Result<StatusLine, ProtoError> { + let line = self.exchange(command, on_data)?; + match line.status { + Status::Ok => Ok(line), + _ => Err(ProtoError::Rejected(self.refusal(&line))), + } + } + + /// Send a command and read up to its tagged answer: OK, NO or BAD. + fn exchange(&mut self, command: Command<'_>, on_data: &mut dyn FnMut(Vec<Value>)) -> Result<StatusLine, ProtoError> { + if command.unsendable { + return Err(ProtoError::Protocol(said!("the text has a character that can't be sent"))); + } + let tag = self.tag(); + self.text_seen = 0; + if log::log_enabled!(log::Level::Trace) { + log::trace!("C: {tag} {}", for_trace(&self.secrets.hide(&command.for_log()))); + } + let mut out = Vec::with_capacity(128); + out.extend_from_slice(tag.as_bytes()); + out.push(b' '); + for part in &command.parts { + match part { + Part::Text(text) => out.extend_from_slice(text), + Part::Literal(bytes) => { + // A literal is announced, and only sent once the server says `+`. + out.extend_from_slice(format!("{{{}}}\r\n", bytes.len()).as_bytes()); + self.wire.write(&out)?; + self.wire.flush()?; + out.clear(); + match self.read_until(&tag, true, on_data)? { + None => {} + // The command can't have succeeded without the rest of it. + Some(line) if line.status == Status::Ok => return Err(ProtoError::Protocol(said!("the server ended the command early"))), + Some(refused) => return Ok(refused), + } + self.wire.write(bytes)?; + } + } + } + out.extend_from_slice(b"\r\n"); + self.wire.write(&out)?; + self.wire.flush()?; + match self.read_until(&tag, false, on_data)? { + Some(line) => Ok(line), + None => Err(ProtoError::Protocol(said!("the server asked for more than the command had"))), + } + } + + /// Read responses up to the command's tagged answer (`Some`) or, when a literal is waiting to + /// be sent, the server's go-ahead (`None`). + fn read_until(&mut self, tag: &str, literal_waiting: bool, on_data: &mut dyn FnMut(Vec<Value>)) -> Result<Option<StatusLine>, ProtoError> { + for _ in 0..self.response_cap { + let response = self.read_response()?; + if self.text_seen > self.text_cap { + return Err(ProtoError::Protocol(said!("the server sent too much in answer to one command"))); + } + match response { + Response::GoAhead if literal_waiting => return Ok(None), + Response::GoAhead => return Err(ProtoError::Protocol(said!("the server asked for more than the command had"))), + Response::Status { tag: Some(answered), line } => { + if answered != tag || !matches!(line.status, Status::Ok | Status::No | Status::Bad) { + return Err(ProtoError::Protocol(said!("the server answered a command that wasn't sent"))); + } + self.note_status(&line); + return Ok(Some(line)); + } + Response::Status { tag: None, line } => { + if line.status == Status::Bye && !self.leaving { + return Err(ProtoError::Io(said!("the server ended the session: {reason}", reason = Arg::said(self.refusal(&line))))); + } + self.note_status(&line); + } + Response::Data(values) => { + self.note_data(&values); + on_data(values); + } + } + } + Err(ProtoError::Protocol(said!("the server sent too many responses to one command"))) + } + + /// A line of the server's text, counted against what one command may take. + fn read_text(&mut self) -> Result<Vec<u8>, ProtoError> { + loop { + let line = if self.skip_long { self.wire.read_line_or_skip()? } else { Some(self.wire.read_line()?) }; + let Some(line) = line else { + self.skipped = true; + self.text_seen = self.text_seen.saturating_add(crate::MAX_LINE); + if self.text_seen > self.text_cap { + return Err(ProtoError::Protocol(said!("the server sent too much in answer to one command"))); + } + continue; + }; + self.text_seen = self.text_seen.saturating_add(line.len()).saturating_add(2); + return Ok(line); + } + } + + fn read_response(&mut self) -> Result<Response, ProtoError> { + let line = self.read_text()?; + if log::log_enabled!(log::Level::Trace) { + log::trace!("S: {}", for_trace(&self.secrets.hide(&String::from_utf8_lossy(&line)))); + } + if line.first() == Some(&b'+') { + return Ok(Response::GoAhead); + } + let Some(rest) = line.strip_prefix(b"* ") else { + // Tagged: `A0001 OK done`. + let text = String::from_utf8_lossy(&line); + let mut words = text.splitn(3, ' '); + let (tag, word, rest) = (words.next().unwrap_or(""), words.next().unwrap_or(""), words.next().unwrap_or("")); + return match Status::parse(word) { + Some(status) if !tag.is_empty() && tag != "*" => { + Ok(Response::Status { tag: Some(tag.to_string()), line: StatusLine::new(status, rest) }) + } + _ => Err(ProtoError::Protocol(said!("\"{line}\" is not an IMAP response", line = tidy(&self.secrets.hide(&text))))), + }; + }; + // `* OK …`, `* BYE …`: the rest is text for people, where `{5}` is no literal. + let word_end = rest.iter().position(|b| *b == b' ').unwrap_or(rest.len()); + let word = String::from_utf8_lossy(rest.get(..word_end).unwrap_or(&[])); + if let Some(status) = Status::parse(&word) { + let text = String::from_utf8_lossy(rest.get(word_end..).unwrap_or(&[])); + return Ok(Response::Status { tag: None, line: StatusLine::new(status, &text) }); + } + // Data: a line, and for as long as a line ends in `{n}`, n bytes and another line. + let mut pieces = Vec::new(); + let mut text = rest.to_vec(); + let (mut text_bytes, mut literal_bytes) = (text.len(), 0usize); + for _ in 0..=MAX_LITERALS { + let Some((_, claimed)) = parse::literal_marker(&text) else { + pieces.push(Piece::Text(text)); + return Ok(Response::Data(parse::values(pieces)?)); + }; + let size = usize::try_from(claimed).ok().filter(|n| literal_bytes.saturating_add(*n) <= MAX_LITERAL).ok_or_else(|| { + ProtoError::Protocol(said!( + "the server sent {claimed} bytes in one piece, more than the {mb} MB MailCraft accepts", + claimed, + mb = MAX_LITERAL >> 20 + )) + })?; + let literal = self.wire.read_block(size)?; + literal_bytes = literal_bytes.saturating_add(size); + log::trace!("S: ({size} bytes)"); + pieces.push(Piece::Text(text)); + pieces.push(Piece::Literal(literal)); + text = self.read_text()?; + text_bytes = text_bytes.saturating_add(text.len()); + if text_bytes > MAX_TEXT { + return Err(ProtoError::Protocol(said!("the server's response is too long"))); + } + } + Err(ProtoError::Protocol(said!("the server's response has too many parts"))) + } + + /// Keep what a status line says in its response code. + fn note_status(&mut self, line: &StatusLine) { + match line.code.as_str() { + "UIDVALIDITY" => self.selected.uid_validity = line.arg.parse().unwrap_or(0), + "UIDNEXT" => self.selected.uid_next = line.arg.parse().unwrap_or(0), + "COPYUID" if self.copied.len() < 2 => self.copied.push(copied_from(&line.arg)), + "APPENDUID" if self.appended.len() < 2 => self.appended.push(appended_from(&line.arg)), + "CAPABILITY" => self.capabilities = Some(line.arg.split_whitespace().take(MAX_CAPABILITIES).map(str::to_ascii_uppercase).collect()), + _ => {} + } + } + + /// Keep what untagged data says about the session, whichever command it arrives during. + fn note_data(&mut self, values: &[Value]) { + match (values.first().and_then(Value::atom), values.get(1).and_then(Value::atom)) { + (Some(count), Some(word)) if word.eq_ignore_ascii_case("EXISTS") => self.selected.exists = count.parse().unwrap_or(0), + (Some(word), _) if word.eq_ignore_ascii_case("CAPABILITY") => { + self.capabilities = Some(values.iter().skip(1).filter_map(Value::atom).take(MAX_CAPABILITIES).map(str::to_ascii_uppercase).collect()); + } + _ => {} + } + } + + /// The server's own words for why it said no, fit to show. + /// What the server said for itself, as it said it; MailCraft's words when it said nothing. + fn refusal(&self, line: &StatusLine) -> Text { + // Hidden before it is shortened: a secret cut in half would no longer be recognised. + let text = tidy(&self.secrets.hide(&line.text)); + if text.is_empty() { said!("the command was refused") } else { Text::verbatim(text) } + } +} + +#[cfg(test)] +mod gmail_labels_tests; +#[cfg(test)] +mod gmail_tests; +#[cfg(test)] +mod limits_tests; +#[cfg(test)] +mod tests; diff --git a/crates/proto/src/imap/parse.rs b/crates/proto/src/imap/parse.rs new file mode 100644 index 000000000..f18ba9299 --- /dev/null +++ b/crates/proto/src/imap/parse.rs @@ -0,0 +1,346 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Reading IMAP responses: the pieces a response arrives in, the values in it, and status lines. + +use crate::ProtoError; +use crate::i18n::said; + +/// Deepest that parenthesised lists may nest. +const MAX_DEPTH: usize = 32; + +/// A response as it came off the wire: lines of text with the literals between them. +#[derive(Debug)] +pub(crate) enum Piece { + Text(Vec<u8>), + Literal(Vec<u8>), +} + +/// One value of a response. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Value { + /// A bare word: a number, a flag, `NIL`, `BODY[]`. + Atom(String), + /// A quoted string or a literal. + Str(Vec<u8>), + List(Vec<Value>), +} + +impl Value { + pub(crate) fn atom(&self) -> Option<&str> { + match self { + Value::Atom(a) => Some(a), + _ => None, + } + } + + pub(crate) fn number(&self) -> Option<u32> { + self.atom()?.parse().ok() + } + + /// The text of a string or a bare word (what the grammar calls an `astring`). + pub(crate) fn into_text(self) -> Option<String> { + match self { + Value::Atom(a) => Some(a), + Value::Str(bytes) => Some(String::from_utf8_lossy(&bytes).into_owned()), + Value::List(_) => None, + } + } +} + +/// Where a line ends in a literal marker (`{123}`, also `{123+}`) outside any quoted string: the +/// marker's position and the size it names. +pub(crate) fn literal_marker(line: &[u8]) -> Option<(usize, u64)> { + let inner_end = line.len().checked_sub(1).filter(|last| line.get(*last) == Some(&b'}'))?; + let open = line.iter().rposition(|b| *b == b'{')?; + let inner = line.get(open + 1..inner_end)?; + let digits = inner.strip_suffix(b"+").unwrap_or(inner); + if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) { + return None; + } + // A brace inside a quoted string is just text. + let (mut quoted, mut escaped) = (false, false); + for b in line.get(..open)? { + if escaped { + escaped = false; + } else if quoted && *b == b'\\' { + escaped = true; + } else if *b == b'"' { + quoted = !quoted; + } + } + if quoted { + return None; + } + // A size beyond u64 is as large as can be, and refused like any other that is too large. + let size = digits.iter().try_fold(0u64, |n, d| n.checked_mul(10)?.checked_add(u64::from(d.wrapping_sub(b'0')))).unwrap_or(u64::MAX); + Some((open, size)) +} + +/// The values of a response. Unbalanced parentheses are forgiven; lists nested too deeply are not. +pub(crate) fn values(pieces: Vec<Piece>) -> Result<Vec<Value>, ProtoError> { + // The list being filled is on top; the response itself is at the bottom. + let mut stack: Vec<Vec<Value>> = vec![Vec::new()]; + let mut pieces = pieces.into_iter().peekable(); + while let Some(piece) = pieces.next() { + match piece { + Piece::Literal(bytes) => push(&mut stack, Value::Str(bytes)), + Piece::Text(text) => { + // The marker of the literal that follows is not a value. + let end = match (pieces.peek(), literal_marker(&text)) { + (Some(Piece::Literal(_)), Some((at, _))) => at, + _ => text.len(), + }; + scan(text.get(..end).unwrap_or(&[]), &mut stack)?; + } + } + } + while stack.len() > 1 { + close(&mut stack); + } + Ok(stack.pop().unwrap_or_default()) +} + +fn push(stack: &mut [Vec<Value>], value: Value) { + if let Some(top) = stack.last_mut() { + top.push(value); + } +} + +fn close(stack: &mut Vec<Vec<Value>>) { + if stack.len() > 1 + && let Some(list) = stack.pop() + { + push(stack, Value::List(list)); + } +} + +fn scan(text: &[u8], stack: &mut Vec<Vec<Value>>) -> Result<(), ProtoError> { + // A `[` only opens a section (`BODY[HEADER.FIELDS (TO)]`) when a `]` follows somewhere. + let last_close = text.iter().rposition(|b| *b == b']'); + let mut i = 0; + // Every arm moves `i` forward. + while let Some(&b) = text.get(i) { + match b { + b' ' | b'\t' => i += 1, + b'(' => { + if stack.len() > MAX_DEPTH { + return Err(ProtoError::Protocol(said!("the server's response is nested too deeply"))); + } + stack.push(Vec::new()); + i += 1; + } + b')' => { + close(stack); + i += 1; + } + b'"' => { + let (string, next) = quoted(text, i + 1); + push(stack, Value::Str(string)); + i = next; + } + _ => { + let fetch_attribute = stack.len() == 2 + && stack.first().and_then(|root| root.get(1)).and_then(Value::atom).is_some_and(|word| word.eq_ignore_ascii_case("FETCH")); + let end = atom_end(text, i, if fetch_attribute { last_close } else { None }); + push(stack, Value::Atom(String::from_utf8_lossy(text.get(i..end).unwrap_or(&[])).into_owned())); + i = end; + } + } + } + Ok(()) +} + +/// The contents of the quoted string that starts at `start` (after its opening quote), and where +/// the text goes on. A string the line ends in the middle of is taken as far as it goes. +fn quoted(text: &[u8], start: usize) -> (Vec<u8>, usize) { + let mut out = Vec::new(); + let mut i = start; + while let Some(&b) = text.get(i) { + match b { + b'"' => return (out, i + 1), + b'\\' => { + out.extend(text.get(i + 1)); + i += 2; + } + _ => { + out.push(b); + i += 1; + } + } + } + (out, i) +} + +/// Where the bare word starting at `start` ends: at a space or parenthesis outside `[…]`. +fn atom_end(text: &[u8], start: usize, last_close: Option<usize>) -> usize { + let mut i = start; + while let Some(&b) = text.get(i) { + match b { + b' ' | b'\t' | b'(' | b')' if i > start => break, + b'[' if last_close.is_some_and(|close| close > i) + && text.get(start..i).is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"BODY") || prefix.eq_ignore_ascii_case(b"BODY.PEEK")) => + { + let close = text.get(i..).and_then(|rest| rest.iter().position(|b| *b == b']')).unwrap_or(0); + i += close + 1; + } + _ => i += 1, + } + } + i +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Status { + Ok, + No, + Bad, + Bye, + Preauth, +} + +impl Status { + pub(crate) fn parse(word: &str) -> Option<Status> { + match word.to_ascii_uppercase().as_str() { + "OK" => Some(Status::Ok), + "NO" => Some(Status::No), + "BAD" => Some(Status::Bad), + "BYE" => Some(Status::Bye), + "PREAUTH" => Some(Status::Preauth), + _ => None, + } + } +} + +/// `OK [UIDVALIDITY 3857529045] UIDs valid`, tagged or not. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct StatusLine { + pub(crate) status: Status, + /// The name of the response code, upper-cased (`UIDVALIDITY`); empty when there is none. + pub(crate) code: String, + /// What follows the name inside the brackets. + pub(crate) arg: String, + /// Everything after the status word, code included. + pub(crate) text: String, +} + +impl StatusLine { + pub(crate) fn new(status: Status, rest: &str) -> StatusLine { + let text = rest.trim(); + let inner = text.strip_prefix('[').and_then(|r| r.split_once(']')).map_or("", |(inner, _)| inner.trim()); + let (code, arg) = inner.split_once(' ').unwrap_or((inner, "")); + StatusLine { status, code: code.to_ascii_uppercase(), arg: arg.trim().to_string(), text: text.to_string() } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + fn text(s: &str) -> Piece { + Piece::Text(s.as_bytes().to_vec()) + } + + fn atom(s: &str) -> Value { + Value::Atom(s.into()) + } + + fn string(s: &str) -> Value { + Value::Str(s.as_bytes().to_vec()) + } + + fn parse(s: &str) -> Vec<Value> { + values(vec![text(s)]).unwrap() + } + + #[test] + fn atoms_strings_and_lists() { + assert_eq!( + parse(r#"LIST (\HasNoChildren \Sent) "/" "Sent \"old\" \\ mail""#), + vec![atom("LIST"), Value::List(vec![atom("\\HasNoChildren"), atom("\\Sent")]), string("/"), string("Sent \"old\" \\ mail")] + ); + assert_eq!( + parse("12 FETCH (UID 7 FLAGS ())"), + vec![atom("12"), atom("FETCH"), Value::List(vec![atom("UID"), atom("7"), atom("FLAGS"), Value::List(vec![])])] + ); + assert_eq!( + parse("a ((b) (c (d))) NIL"), + vec![atom("a"), Value::List(vec![Value::List(vec![atom("b")]), Value::List(vec![atom("c"), Value::List(vec![atom("d")])])]), atom("NIL")] + ); + assert_eq!(parse(""), vec![]); + assert_eq!(parse(" "), vec![]); + } + + #[test] + fn sections_are_part_of_the_word() { + assert_eq!( + parse("12 FETCH (BODY[HEADER.FIELDS (FROM TO)] x BODY[]<0> y)"), + vec![atom("12"), atom("FETCH"), Value::List(vec![atom("BODY[HEADER.FIELDS (FROM TO)]"), atom("x"), atom("BODY[]<0>"), atom("y")])] + ); + assert_eq!(parse(r#"LIST () "/" [Gmail]/Trash"#), vec![atom("LIST"), Value::List(vec![]), string("/"), atom("[Gmail]/Trash")]); + // A bracket that never closes is an ordinary character. + assert_eq!(parse("(a[b c)"), vec![Value::List(vec![atom("a[b"), atom("c")])]); + assert_eq!(parse("[[[[ x"), vec![atom("[[[["), atom("x")]); + } + + #[test] + fn broken_text_is_read_as_far_as_it_goes() { + assert_eq!(parse("(a (b"), vec![Value::List(vec![atom("a"), Value::List(vec![atom("b")])])]); + assert_eq!(parse("a) b))"), vec![atom("a"), atom("b")]); + assert_eq!(parse(r#""never closed"#), vec![string("never closed")]); + assert_eq!(parse(r#""ends in a backslash\"#), vec![string("ends in a backslash")]); + assert_eq!(parse("a\"b c"), vec![atom("a\"b"), atom("c")]); + let deep = "(".repeat(MAX_DEPTH + 5); + assert!(matches!(values(vec![text(&deep)]), Err(ProtoError::Protocol(_)))); + assert!(values(vec![text(&"(".repeat(MAX_DEPTH))]).is_ok()); + } + + #[test] + fn literals_take_the_place_of_their_marker() { + let pieces = + vec![text("1 FETCH (BODY[] {5}"), Piece::Literal(b"a (\"b".to_vec()), text(" UID 3 X {0}"), Piece::Literal(Vec::new()), text(")")]; + assert_eq!( + values(pieces).unwrap(), + vec![atom("1"), atom("FETCH"), Value::List(vec![atom("BODY[]"), string("a (\"b"), atom("UID"), atom("3"), atom("X"), string("")])] + ); + // Without a literal after it, a marker is only a word. + assert_eq!(parse("a {5}"), vec![atom("a"), atom("{5}")]); + } + + #[test] + fn markers() { + assert_eq!(literal_marker(b"* 1 FETCH (BODY[] {123}"), Some((18, 123))); + assert_eq!(literal_marker(b"{0}"), Some((0, 0))); + assert_eq!(literal_marker(b"x {7+}"), Some((2, 7))); + assert_eq!(literal_marker(b"\"quoted\" {7}"), Some((9, 7))); + assert_eq!(literal_marker(b"x {99999999999999999999999}"), Some((2, u64::MAX))); + for not in ["", "}", "{}", "{+}", "{5} ", "{-5}", "{5 }", "\"in a string {5}", "\"a \\\" {5}", "{5}x", "{ 5}", "5}"] { + assert_eq!(literal_marker(not.as_bytes()), None, "{not:?}"); + } + } + + #[test] + fn status_lines() { + let s = StatusLine::new(Status::Ok, " [UIDVALIDITY 3857529045] UIDs valid "); + assert_eq!((s.code.as_str(), s.arg.as_str(), s.text.as_str()), ("UIDVALIDITY", "3857529045", "[UIDVALIDITY 3857529045] UIDs valid")); + let s = StatusLine::new(Status::No, "[alert] disk full"); + assert_eq!((s.code.as_str(), s.arg.as_str()), ("ALERT", "")); + let s = StatusLine::new(Status::Ok, "done [not a code]"); + assert_eq!((s.code.as_str(), s.text.as_str()), ("", "done [not a code]")); + assert_eq!(StatusLine::new(Status::Bad, "[unclosed").code, ""); + assert_eq!(StatusLine::new(Status::Bad, "").text, ""); + assert_eq!(Status::parse("preauth"), Some(Status::Preauth)); + assert_eq!(Status::parse("FETCH"), None); + } + + #[test] + fn values_as_numbers_and_text() { + assert_eq!(atom("42").number(), Some(42)); + assert_eq!(atom("4294967296").number(), None); + assert_eq!(atom("-1").number(), None); + assert_eq!(string("42").number(), None); + assert_eq!(string("Entw&APw-rfe").into_text().as_deref(), Some("Entw&APw-rfe")); + assert_eq!(Value::Str(vec![0xFF, b'a']).into_text().as_deref(), Some("\u{FFFD}a")); + assert_eq!(Value::List(vec![]).into_text(), None); + } +} diff --git a/crates/proto/src/imap/password.rs b/crates/proto/src/imap/password.rs new file mode 100644 index 000000000..acc7d0ec0 --- /dev/null +++ b/crates/proto/src/imap/password.rs @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Password authentication from RFC 4616 and RFC 4959, over an already secured stream. + +use super::{Imap, ProtoError, Read, Status, Write, ignore, said}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; + +impl<S: Read + Write> Imap<S> { + /// Prefer the server's advertised PLAIN mechanism; otherwise use LOGIN. The host must + /// secure the stream first. Unknown capabilities are queried here; known ones are reused. + /// A refusal never triggers a second attempt with another mechanism. + pub fn authenticate_password(&mut self, user: &str, password: &str) -> Result<(), ProtoError> { + if password.is_empty() { + return Err(ProtoError::Auth(said!("enter a password to sign in"))); + } + if user.is_empty() { + return Err(ProtoError::Auth(said!("enter a user name to sign in"))); + } + if self.capabilities.is_none() { + self.capabilities()?; + } + if !self.offers("AUTH=PLAIN") { + return self.login(user, password); + } + if user.contains('\0') || password.contains('\0') { + return Err(ProtoError::Auth(said!("PLAIN needs a user name and password without NUL characters"))); + } + if user.len().saturating_add(password.len()) > 32 * 1024 { + return Err(ProtoError::Auth(said!("the user name or password is too long"))); + } + // Empty authorization identity: the server derives it from the authentication identity. + let response = STANDARD.encode(format!("\0{user}\0{password}").as_bytes()); + self.secrets.add(password); + self.secrets.add(&response); + let inline = self.offers("SASL-IR"); + let tag = self.tag(); + let command = if inline { format!("{tag} AUTHENTICATE PLAIN {response}\r\n") } else { format!("{tag} AUTHENTICATE PLAIN\r\n") }; + log::trace!("C: {tag} AUTHENTICATE PLAIN{}", if inline { " ***" } else { "" }); + self.wire.write(command.as_bytes())?; + self.wire.flush()?; + let mut sent = inline; + let mut cancelled = false; + let verdict = loop { + if let Some(verdict) = self.read_until(&tag, true, &mut ignore)? { + break verdict; + } + if cancelled { + return Err(ProtoError::Protocol(said!("the server continued a cancelled password authentication"))); + } + let answer = if sent { + cancelled = true; + "*" + } else { + sent = true; + response.as_str() + }; + log::trace!("C: ***"); + self.wire.write(format!("{answer}\r\n").as_bytes())?; + self.wire.flush()?; + }; + match verdict.status { + _ if cancelled => Err(ProtoError::Auth(said!("the server requested more than one PLAIN response"))), + Status::Ok if !sent => Err(ProtoError::Protocol(said!("the server accepted a password that was not sent"))), + Status::Ok => { + self.authenticated = true; + Ok(()) + } + Status::No => Err(ProtoError::Auth(self.refusal(&verdict))), + _ => Err(ProtoError::Rejected(self.refusal(&verdict))), + } + } +} diff --git a/crates/proto/src/imap/password_tests.rs b/crates/proto/src/imap/password_tests.rs new file mode 100644 index 000000000..cbd0989fc --- /dev/null +++ b/crates/proto/src/imap/password_tests.rs @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use super::*; +use crate::script::Script; +use base64::{Engine as _, engine::general_purpose::STANDARD}; + +fn greeting(caps: &str, replies: &str) -> String { + format!("* OK [CAPABILITY IMAP4rev1 {caps}] ready\r\n{replies}") +} + +#[test] +fn plain_uses_an_initial_response_only_when_advertised() { + let payload = STANDARD.encode(b"\0user@example.org\0invented"); + for inline in [false, true] { + let caps = if inline { "AUTH=PLAIN SASL-IR LOGINDISABLED" } else { "AUTH=PLAIN LOGINDISABLED" }; + let replies = if inline { "A0001 OK welcome\r\n" } else { "+ continue\r\nA0001 OK welcome\r\n" }; + let mut stream = Script::new(greeting(caps, replies)); + let mut imap = Imap::connect(&mut stream).unwrap(); + imap.authenticate_password("user@example.org", "invented").unwrap(); + assert!(imap.is_authenticated()); + let expected = if inline { format!("A0001 AUTHENTICATE PLAIN {payload}\r\n") } else { format!("A0001 AUTHENTICATE PLAIN\r\n{payload}\r\n") }; + assert_eq!(stream.sent(), expected); + } +} + +#[test] +fn login_remains_available_when_plain_is_not_advertised() { + let mut stream = Script::new(greeting("SASL-IR", "A0001 OK welcome\r\n")); + Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "invented").unwrap(); + assert_eq!(stream.sent(), "A0001 LOGIN \"user@example.org\" \"invented\"\r\n"); +} + +#[test] +fn a_plain_refusal_is_redacted_and_never_retried_with_login() { + let payload = STANDARD.encode(b"\0user@example.org\0invented"); + let mut stream = Script::new(greeting("AUTH=PLAIN SASL-IR", &format!("A0001 NO [AUTHENTICATIONFAILED] invented {payload}\r\n"))); + let mut imap = Imap::connect(&mut stream).unwrap(); + let error = imap.authenticate_password("user@example.org", "invented").unwrap_err(); + assert!(matches!(error, ProtoError::Auth(_))); + assert!(!format!("{error:?} {imap:?}").contains("invented")); + assert!(!format!("{error:?} {imap:?}").contains(&payload)); + assert!(!imap.is_authenticated()); + assert!(!stream.sent().contains(" LOGIN ")); +} + +#[test] +fn a_refusal_before_the_challenge_sends_no_password() { + let mut stream = Script::new(greeting("AUTH=PLAIN", "A0001 NO unavailable\r\n")); + assert!(Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "invented").is_err()); + assert_eq!(stream.sent(), "A0001 AUTHENTICATE PLAIN\r\n"); +} + +#[test] +fn repeated_challenges_cancel_and_never_authenticate() { + for replies in ["+ first\r\n+ second\r\nA0001 OK ignored\r\n", "+ first\r\n+ second\r\n+ third\r\n"] { + let mut stream = Script::new(greeting("AUTH=PLAIN", replies)); + let mut imap = Imap::connect(&mut stream).unwrap(); + assert!(imap.authenticate_password("user@example.org", "invented").is_err()); + assert!(!imap.is_authenticated()); + assert!(stream.sent().ends_with("\r\n*\r\n")); + } +} + +#[test] +fn premature_success_and_invalid_credentials_are_refused() { + let mut stream = Script::new(greeting("AUTH=PLAIN", "A0001 OK too early\r\n")); + assert!(Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "invented").is_err()); + for (user, password) in [("", "invented"), ("user@example.org", ""), ("bad\0user", "invented"), ("user@example.org", "bad\0password")] { + let mut stream = Script::new(greeting("AUTH=PLAIN", "")); + assert!(Imap::connect(&mut stream).unwrap().authenticate_password(user, password).is_err()); + assert!(stream.sent().is_empty()); + } + let mut stream = Script::new(greeting("AUTH=PLAIN", "")); + assert!(Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", &"x".repeat(32769)).is_err()); + assert!(stream.sent().is_empty()); +} + +#[test] +fn utf8_and_line_breaks_are_encoded_not_protocol_lines() { + let mut stream = Script::new(greeting("auth=plain sasl-ir", "A0001 OK welcome\r\n")); + Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "päss\r\nword").unwrap(); + assert_eq!(stream.sent().lines().count(), 1); + assert!(stream.sent().contains(&STANDARD.encode("\0user@example.org\0päss\r\nword".as_bytes()))); +} + +#[test] +fn unknown_capabilities_are_queried_once_by_password_authentication() { + let mut stream = Script::new("* OK ready\r\n* CAPABILITY IMAP4rev1 AUTH=PLAIN SASL-IR\r\nA0001 OK done\r\nA0002 OK welcome\r\n"); + Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "invented").unwrap(); + assert!(stream.sent().starts_with("A0001 CAPABILITY\r\nA0002 AUTHENTICATE PLAIN ")); + assert_eq!(stream.sent().matches(" CAPABILITY").count(), 1); +} +#[test] +fn a_missing_password_has_its_own_message_without_network_commands() { + let mut stream = Script::new("* OK ready\r\n"); + let error = Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "").unwrap_err(); + assert!(error.to_string().contains("enter a password")); + assert!(!error.to_string().contains("NUL")); + assert!(stream.sent().is_empty()); +} + +#[test] +fn an_empty_user_name_is_explained_before_any_commands() { + for text in ["* OK ready\r\n".to_string(), greeting("AUTH=PLAIN", ""), greeting("", "")] { + let mut stream = Script::new(text); + let error = Imap::connect(&mut stream).unwrap().authenticate_password("", "invented").unwrap_err(); + assert!(error.to_string().contains("enter a user name")); + assert!(!error.to_string().contains("NUL")); + assert!(stream.sent().is_empty()); + } +} diff --git a/crates/proto/src/imap/status.rs b/crates/proto/src/imap/status.rs new file mode 100644 index 000000000..3c378308a --- /dev/null +++ b/crates/proto/src/imap/status.rs @@ -0,0 +1,164 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! STATUS (RFC 3501 §6.3.10): what a mailbox holds, asked without opening it, for a program to +//! tell whether it has changed since it was last read (#276). Many mailboxes are asked in one +//! go: the commands are written together and the answers read together (pipelining, RFC 3501 +//! §5.5), so a hundred mailboxes cost about one round trip, not a hundred. + +use std::io::{Read, Write}; + +use super::parse::{Status, Value}; +use super::{Command, Imap, MAX_COMMAND_TEXT, MAX_QUOTED, Part, Response}; +use crate::i18n::said; +use crate::{ProtoError, for_trace}; + +/// Most mailboxes asked in one go: their commands are a few kilobytes at most, so the server +/// can't be left waiting to be read while we write. +pub const MAX_STATUS_BATCH: usize = 50; + +/// What STATUS says of a mailbox: all four counts, or nothing at all (a server that leaves one +/// out gets its mailbox read, never passed over on a guess). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct FolderStatus { + /// How many messages there are. + pub messages: u32, + /// The UID the next message to arrive gets. + pub uid_next: u32, + pub uid_validity: u32, + /// How many are not marked `\Seen`. + pub unseen: u32, +} + +/// From `STATUS name (MESSAGES 3 UIDNEXT 9 …)`; `None` when it isn't one, or a count is missing. +fn status_from(values: Vec<Value>) -> Option<FolderStatus> { + let mut values = values.into_iter(); + if !values.next()?.atom()?.eq_ignore_ascii_case("STATUS") { + return None; + } + values.next()?; + let Value::List(pairs) = values.next()? else { return None }; + let (mut messages, mut uid_next, mut uid_validity, mut unseen) = (None, None, None, None); + let mut pairs = pairs.into_iter(); + while let (Some(name), Some(value)) = (pairs.next(), pairs.next()) { + let Some(number) = value.number() else { continue }; + match name.atom().map(str::to_ascii_uppercase).as_deref() { + Some("MESSAGES") => messages = Some(number), + Some("UIDNEXT") => uid_next = Some(number), + Some("UIDVALIDITY") => uid_validity = Some(number), + Some("UNSEEN") => unseen = Some(number), + _ => {} + } + } + Some(FolderStatus { messages: messages?, uid_next: uid_next?, uid_validity: uid_validity?, unseen: unseen? }) +} + +fn command(raw_name: &str) -> Command<'_> { + Command::new("STATUS").string(raw_name.as_bytes()).arg("(MESSAGES UIDNEXT UIDVALIDITY UNSEEN)") +} + +impl<S: Read + Write> Imap<S> { + /// STATUS of one mailbox; `None` when the server refuses or leaves a count out. + pub fn status(&mut self, raw_name: &str) -> Result<Option<FolderStatus>, ProtoError> { + let mut found = None; + let line = self.exchange(command(raw_name), &mut |values| { + if found.is_none() { + found = status_from(values); + } + })?; + Ok(found.filter(|_| line.status == Status::Ok)) + } + + /// STATUS of each of `raw_names`, in the same order, `None` for one the server refuses or + /// leaves a count out of. At most [`MAX_STATUS_BATCH`] are asked in one go; a name that + /// can't go in a quoted string is asked alone. + /// + /// An error is the connection's: the answers read before it are lost with it. + pub fn status_many(&mut self, raw_names: &[&str]) -> Result<Vec<Option<FolderStatus>>, ProtoError> { + let mut out = Vec::with_capacity(raw_names.len()); + for batch in raw_names.chunks(MAX_STATUS_BATCH) { + let plain = batch.iter().all(|name| name.len() <= MAX_QUOTED && name.bytes().all(|b| matches!(b, b' '..=b'~'))); + if plain && batch.len() > 1 { + out.extend(self.status_batch(batch)?); + } else { + for name in batch { + out.push(self.status(name)?); + } + } + } + Ok(out) + } + + /// One batch, written together: the answers come in the order of the commands. + fn status_batch(&mut self, batch: &[&str]) -> Result<Vec<Option<FolderStatus>>, ProtoError> { + let mut tags = Vec::with_capacity(batch.len()); + let mut out = Vec::with_capacity(batch.len().saturating_mul(64)); + for name in batch { + let command = command(name); + if command.unsendable { + return Err(ProtoError::Protocol(said!("the text has a character that can't be sent"))); + } + let tag = self.tag(); + if log::log_enabled!(log::Level::Trace) { + log::trace!("C: {tag} {}", for_trace(&self.secrets.hide(&command.for_log()))); + } + out.extend_from_slice(tag.as_bytes()); + out.push(b' '); + for part in &command.parts { + if let Part::Text(text) = part { + out.extend_from_slice(text); + } + } + out.extend_from_slice(b"\r\n"); + tags.push(tag); + } + self.wire.write(&out)?; + self.wire.flush()?; + self.text_seen = 0; + let mut found: Vec<Option<FolderStatus>> = vec![None; batch.len()]; + let mut answered = 0usize; + // Each command brings one STATUS and its tagged answer; the rest is slack for what a + // server says unasked. + let cap = batch.len().saturating_mul(2).saturating_add(64); + for _ in 0..cap { + if answered >= tags.len() { + break; + } + match self.read_response()? { + Response::GoAhead => return Err(ProtoError::Protocol(said!("the server asked for more than the command had"))), + Response::Status { tag: Some(tag), line } => { + if tags.get(answered) != Some(&tag) || !matches!(line.status, Status::Ok | Status::No | Status::Bad) { + return Err(ProtoError::Protocol(said!("the server answered a command that wasn't sent"))); + } + self.note_status(&line); + if line.status != Status::Ok + && let Some(slot) = found.get_mut(answered) + { + *slot = None; + } + answered += 1; + } + Response::Status { tag: None, line } => { + if line.status == Status::Bye && !self.leaving { + return Err(ProtoError::Io(said!("the server ended the session"))); + } + self.note_status(&line); + } + Response::Data(values) => { + if self.text_seen > MAX_COMMAND_TEXT { + return Err(ProtoError::Protocol(said!("the server sent too much in answer to one command"))); + } + self.note_data(&values); + if let Some(slot) = found.get_mut(answered) + && slot.is_none() + { + *slot = status_from(values); + } + } + } + } + if answered < tags.len() { + return Err(ProtoError::Protocol(said!("the server sent too many responses to one command"))); + } + Ok(found) + } +} diff --git a/crates/proto/src/imap/status_tests.rs b/crates/proto/src/imap/status_tests.rs new file mode 100644 index 000000000..a0f252b35 --- /dev/null +++ b/crates/proto/src/imap/status_tests.rs @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use proptest::prelude::*; + +use super::*; +use crate::script::Script; + +fn status(messages: u32, uid_next: u32, uid_validity: u32, unseen: u32) -> FolderStatus { + FolderStatus { messages, uid_next, uid_validity, unseen } +} + +#[test] +fn one_mailbox_is_asked_its_four_counts() { + let mut s = Script::new("* STATUS \"Work\" (MESSAGES 3 UIDNEXT 9 UIDVALIDITY 77 UNSEEN 1)\r\nA0001 OK done\r\n"); + let got = Imap::resume(&mut s).status("Work").unwrap(); + assert_eq!(got, Some(status(3, 9, 77, 1))); + assert_eq!(s.sent(), "A0001 STATUS \"Work\" (MESSAGES UIDNEXT UIDVALIDITY UNSEEN)\r\n"); +} + +#[test] +fn a_count_left_out_or_a_refusal_is_no_status() { + let mut s = Script::new("* STATUS Work (MESSAGES 3 UIDNEXT 9 UIDVALIDITY 77)\r\nA0001 OK done\r\nA0002 NO [NONEXISTENT] no such mailbox\r\n"); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.status("Work").unwrap(), None); + assert_eq!(imap.status("Gone").unwrap(), None); +} + +#[test] +fn many_mailboxes_are_asked_in_one_write() { + let mut s = Script::new( + "* STATUS A (MESSAGES 1 UIDNEXT 2 UIDVALIDITY 5 UNSEEN 0)\r\nA0001 OK done\r\n\ + A0002 NO [NONEXISTENT] no\r\n\ + * STATUS \"C d\" (UNSEEN 4 UIDVALIDITY 7 UIDNEXT 8 MESSAGES 9 HIGHESTMODSEQ 12)\r\nA0003 OK done\r\n", + ); + let got = Imap::resume(&mut s).status_many(&["A", "B", "C d"]).unwrap(); + assert_eq!(got, vec![Some(status(1, 2, 5, 0)), None, Some(status(9, 8, 7, 4))]); + let sent = s.sent(); + assert_eq!(sent.matches("STATUS").count(), 3); + assert!(sent.starts_with("A0001 STATUS \"A\" ") && sent.contains("A0003 STATUS \"C d\" "), "{sent}"); +} + +#[test] +fn answers_out_of_turn_or_too_many_end_the_session_not_the_program() { + let mut s = Script::new("A0002 OK done\r\n"); + assert!(matches!(Imap::resume(&mut s).status_many(&["A", "B"]), Err(ProtoError::Protocol(_)))); + let flood = "* 1 EXISTS\r\n".repeat(500); + let mut s = Script::new(flood); + assert!(matches!(Imap::resume(&mut s).status_many(&["A", "B"]), Err(ProtoError::Protocol(_)))); + let mut s = Script::new("* BYE going\r\n"); + assert!(matches!(Imap::resume(&mut s).status_many(&["A", "B"]), Err(ProtoError::Io(_)))); +} + +#[test] +fn a_name_that_needs_a_literal_is_asked_alone() { + let mut s = Script::new("+ go\r\n* STATUS x (MESSAGES 1 UIDNEXT 2 UIDVALIDITY 3 UNSEEN 0)\r\nA0001 OK done\r\n"); + let got = Imap::resume(&mut s).status_many(&["é", "A"]).unwrap_or_default(); + assert!(got.len() <= 2); +} + +proptest! { + #[test] + fn arbitrary_server_bytes_never_panic_in_status(server in proptest::collection::vec(any::<u8>(), 0..600), names in 0usize..120) { + let list: Vec<String> = (0..names).map(|n| format!("F{n}")).collect(); + let refs: Vec<&str> = list.iter().map(String::as_str).collect(); + let mut s = Script::new(&server); + let got = Imap::resume(&mut s).status_many(&refs); + if let Ok(got) = got { + prop_assert_eq!(got.len(), names); + } + } + + #[test] + fn any_status_line_is_read_or_not(line in "[ -~]{0,80}") { + let mut s = Script::new(format!("* STATUS {line}\r\nA0001 OK done\r\n")); + let _ = Imap::resume(&mut s).status("x"); + } +} diff --git a/crates/proto/src/imap/tests.rs b/crates/proto/src/imap/tests.rs new file mode 100644 index 000000000..c384d0154 --- /dev/null +++ b/crates/proto/src/imap/tests.rs @@ -0,0 +1,1068 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use std::io::ErrorKind; + +use proptest::prelude::*; + +use super::*; +use crate::script::{Broken, Script}; + +fn mailbox(name: &str, raw: &str, delimiter: Option<char>, flags: &[&str]) -> Mailbox { + Mailbox { name: name.into(), raw: raw.into(), delimiter, flags: flags.iter().map(|f| f.to_string()).collect() } +} + +fn fetched(uid: u32, flags: &[&str]) -> Fetched { + Fetched { uid, flags: flags.iter().map(|f| f.to_string()).collect(), internal_date: None, body: None, gmail_id: None, gmail_labels: None } +} + +/// A FETCH response carrying `body` as a literal, between `before` and `after`. +fn with_literal(before: &str, body: &[u8], after: &str) -> Vec<u8> { + let mut out = format!("{before}{{{}}}\r\n", body.len()).into_bytes(); + out.extend_from_slice(body); + out.extend_from_slice(after.as_bytes()); + out +} + +#[test] +fn greetings() { + let mut s = Script::new("* OK [CAPABILITY IMAP4rev1 STARTTLS] mail.example.org ready\r\n"); + let imap = Imap::connect(&mut s).unwrap(); + assert!(!imap.is_authenticated()); + assert_eq!(imap.capabilities, Some(vec!["IMAP4REV1".to_string(), "STARTTLS".to_string()])); + + let mut s = Script::new("* PREAUTH welcome back\r\n"); + assert!(Imap::connect(&mut s).unwrap().is_authenticated()); + + let mut s = Script::new("* BYE overloaded, try later\r\n"); + assert_eq!(Imap::connect(&mut s).unwrap_err(), ProtoError::Rejected("overloaded, try later".into())); + + for junk in ["hello\r\n", "+ go on\r\n", "* 3 EXISTS\r\n", "A0001 OK early\r\n", "* NO\r\n", "\r\n", "*\r\n", "220 smtp.example.org ESMTP\r\n"] { + let mut s = Script::new(junk); + assert!(matches!(Imap::connect(&mut s), Err(ProtoError::Protocol(_))), "{junk:?}"); + } + let mut s = Script::new(""); + assert!(matches!(Imap::connect(&mut s), Err(ProtoError::Io(_)))); +} + +#[test] +fn capabilities_are_upper_cased() { + let mut s = Script::new( + "* CAPABILITY IMAP4rev1 StartTLS special-use AUTH=PLAIN\r\nA0001 OK done\r\nA0002 OK [CAPABILITY IMAP4rev1 IDLE] done\r\nA0003 OK none\r\n", + ); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.capabilities().unwrap(), ["IMAP4REV1", "STARTTLS", "SPECIAL-USE", "AUTH=PLAIN"]); + // Some servers answer in the tagged line. + assert_eq!(imap.capabilities().unwrap(), ["IMAP4REV1", "IDLE"]); + assert_eq!(imap.capabilities().unwrap(), Vec::<String>::new()); + assert_eq!(s.sent(), "A0001 CAPABILITY\r\nA0002 CAPABILITY\r\nA0003 CAPABILITY\r\n"); +} + +#[test] +fn login_quotes_its_strings() { + let mut s = Script::new("A0001 OK [CAPABILITY IMAP4rev1] welcome\r\n"); + let mut imap = Imap::resume(&mut s); + imap.login(r#"ada "the" \ lovelace"#, r#"p"w\d {5}"#).unwrap(); + assert!(imap.is_authenticated()); + assert_eq!(s.sent(), "A0001 LOGIN \"ada \\\"the\\\" \\\\ lovelace\" \"p\\\"w\\\\d {5}\"\r\n"); +} + +#[test] +fn login_sends_what_quotes_cannot_carry_as_literals() { + let mut s = Script::new("+ go on\r\nA0001 OK welcome\r\n"); + let mut imap = Imap::resume(&mut s); + imap.login("ada", "pässwörd").unwrap(); + assert_eq!(s.sent(), "A0001 LOGIN \"ada\" {10}\r\npässwörd\r\n"); + + // Both as literals, each after its own go-ahead; a line break can't end the command early. + let mut s = Script::new("+ go on\r\n+ go on\r\nA0001 OK welcome\r\n"); + let mut imap = Imap::resume(&mut s); + imap.login("ädä", "two\r\nA0002 LOGOUT").unwrap(); + assert_eq!(s.sent(), "A0001 LOGIN {5}\r\nädä {17}\r\ntwo\r\nA0002 LOGOUT\r\n"); + + // A very long password too. + let long = "x".repeat(MAX_QUOTED + 1); + let mut s = Script::new("+ go on\r\nA0001 OK welcome\r\n"); + Imap::resume(&mut s).login("ada", &long).unwrap(); + assert!(s.sent().starts_with("A0001 LOGIN \"ada\" {1001}\r\nxxx")); +} + +#[test] +fn a_wrong_password_is_an_auth_error_that_never_shows_it() { + // A careless server repeats what it was sent. + let mut s = Script::new("A0001 NO [AUTHENTICATIONFAILED] no user ada with password hunter2\r\n"); + let mut imap = Imap::resume(&mut s); + let err = imap.login("ada", "hunter2").unwrap_err(); + assert_eq!(err, ProtoError::Auth("[AUTHENTICATIONFAILED] no user ada with password ***".into())); + assert!(!imap.is_authenticated()); + assert!(!format!("{err} {err:?} {imap:?}").contains("hunter2")); + + // BAD is not about the password. + let mut s = Script::new("A0001 BAD what\r\n"); + assert_eq!(Imap::resume(&mut s).login("ada", "hunter2"), Err(ProtoError::Rejected("what".into()))); + + // Refused before the literal went out: the password is never sent. + let mut s = Script::new("A0001 NO no literals here\r\n"); + assert!(matches!(Imap::resume(&mut s).login("ada", "pässwörd"), Err(ProtoError::Auth(_)))); + assert_eq!(s.sent(), "A0001 LOGIN \"ada\" {10}\r\n"); + + // Nothing at all is sent when it can't be. + let mut s = Script::new("A0001 OK welcome\r\n"); + assert!(matches!(Imap::resume(&mut s).login("ada", "nul\0"), Err(ProtoError::Auth(_)))); + assert_eq!(s.sent(), ""); +} + +#[test] +fn no_password_for_a_server_that_disabled_login() { + let mut s = Script::new("* OK [CAPABILITY IMAP4rev1 STARTTLS LOGINDISABLED] ready\r\nA0001 OK welcome\r\n"); + let mut imap = Imap::connect(&mut s).unwrap(); + assert!(matches!(imap.login("ada", "hunter2"), Err(ProtoError::Auth(_)))); + assert_eq!(s.sent(), ""); +} + +const TOKEN: &str = "tok.en-123"; + +/// What goes out for `ada@example.org` with [`TOKEN`]. +fn bearer() -> String { + let payload = xoauth2("ada@example.org", TOKEN).unwrap(); + assert_eq!(payload, "dXNlcj1hZGFAZXhhbXBsZS5vcmcBYXV0aD1CZWFyZXIgdG9rLmVuLTEyMwEB"); + payload +} + +#[test] +fn a_token_goes_with_the_command_when_the_server_takes_it_that_way() { + let mut s = Script::new("* OK [CAPABILITY IMAP4rev1 SASL-IR AUTH=PLAIN AUTH=XOAUTH2] ready\r\nA0001 OK [CAPABILITY IMAP4rev1 IDLE] welcome\r\n"); + let mut imap = Imap::connect(&mut s).unwrap(); + imap.authenticate_xoauth2("ada@example.org", TOKEN).unwrap(); + assert!(imap.is_authenticated()); + // What the server can do once signed in is noted. + assert_eq!(imap.capabilities, Some(vec!["IMAP4REV1".to_string(), "IDLE".to_string()])); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE XOAUTH2 {}\r\n", bearer())); + assert!(s.finished()); +} + +#[test] +fn a_token_waits_for_the_go_ahead_otherwise() { + // A server that hasn't said what it can do, one without SASL-IR, and one that has SASL-IR + // but didn't list the mechanism: each is asked first. + for greeting in ["", "* OK [CAPABILITY IMAP4rev1 AUTH=XOAUTH2] ready\r\n", "* OK [CAPABILITY IMAP4rev1 SASL-IR AUTH=PLAIN] ready\r\n"] { + let mut s = Script::new(format!("{greeting}+ \r\n* CAPABILITY IMAP4rev1 IDLE\r\nA0001 OK welcome\r\n")); + let mut imap = if greeting.is_empty() { Imap::resume(&mut s) } else { Imap::connect(&mut s).unwrap() }; + imap.authenticate_xoauth2("ada@example.org", TOKEN).unwrap(); + assert!(imap.is_authenticated(), "{greeting:?}"); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE XOAUTH2\r\n{}\r\n", bearer()), "{greeting:?}"); + } +} + +#[test] +fn a_refused_token_is_an_auth_error_that_never_shows_it() { + let payload = bearer(); + let caps = "* OK [CAPABILITY IMAP4rev1 SASL-IR AUTH=XOAUTH2] ready\r\n"; + // The reasons come first (JSON in base64) and the verdict after an empty line; a careless + // server repeats what it was sent. + let reasons = "+ eyJzdGF0dXMiOiI0MDEiLCJzY2hlbWVzIjoiYmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZXhhbXBsZS5vcmcvIn0=\r\n"; + let mut s = Script::new(format!("{caps}{reasons}A0001 NO [AUTHENTICATIONFAILED] no good: {TOKEN} ({payload})\r\n")); + let mut imap = Imap::connect(&mut s).unwrap(); + let err = imap.authenticate_xoauth2("ada@example.org", TOKEN).unwrap_err(); + assert_eq!(err, ProtoError::Auth("[AUTHENTICATIONFAILED] no good: *** (***)".into())); + assert!(!imap.is_authenticated()); + assert!(!format!("{err} {err:?} {imap:?}").contains(TOKEN)); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE XOAUTH2 {payload}\r\n\r\n")); + assert!(s.finished()); + + // The same after a go-ahead. + let mut s = Script::new(format!("+ \r\n{reasons}A0001 NO AUTHENTICATE failed.\r\n")); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.authenticate_xoauth2("ada@example.org", TOKEN), Err(ProtoError::Auth("AUTHENTICATE failed.".into()))); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE XOAUTH2\r\n{payload}\r\n\r\n")); + + // Refused in one word, without reasons. + let mut s = Script::new("+ \r\nA0001 NO AUTHENTICATE failed.\r\n"); + assert_eq!(Imap::resume(&mut s).authenticate_xoauth2("ada@example.org", TOKEN), Err(ProtoError::Auth("AUTHENTICATE failed.".into()))); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE XOAUTH2\r\n{payload}\r\n")); + + // A token echoed in a long answer is hidden before the answer is shortened. + let long = format!("head.{}.tail", "x".repeat(2_000)); + let mut s = Script::new(format!("+ \r\nA0001 NO {} bad token {long}\r\n", "no ".repeat(80))); + let err = Imap::resume(&mut s).authenticate_xoauth2("ada@example.org", &long).unwrap_err(); + let shown = format!("{err} {err:?}"); + assert!(matches!(err, ProtoError::Auth(_))); + assert!(!shown.contains("head.") && !shown.contains("xxxx"), "{shown}"); +} + +#[test] +fn a_server_without_the_mechanism_never_sees_the_token() { + for (server, expected) in [ + ("A0001 NO [CANNOT] unsupported authentication mechanism\r\n", ProtoError::Auth("[CANNOT] unsupported authentication mechanism".into())), + ("A0001 BAD what\r\n", ProtoError::Rejected("what".into())), + // "Signed in" without having been shown anything can't be true. + ("A0001 OK welcome\r\n", ProtoError::Protocol(said!("the server ended the command early"))), + ] { + let mut s = Script::new(format!("* OK [CAPABILITY IMAP4rev1 AUTH=PLAIN] ready\r\n{server}")); + let mut imap = Imap::connect(&mut s).unwrap(); + assert_eq!(imap.authenticate_xoauth2("ada@example.org", TOKEN), Err(expected), "{server:?}"); + assert!(!imap.is_authenticated()); + assert_eq!(s.sent(), "A0001 AUTHENTICATE XOAUTH2\r\n", "{server:?}"); + } +} + +#[test] +fn questions_a_token_has_no_answer_to_end_the_sign_in() { + // After the reasons, another question: the exchange is cancelled. + let mut s = Script::new("+ \r\n+ e30=\r\n+ more?\r\nA0001 BAD cancelled\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.authenticate_xoauth2("ada@example.org", TOKEN), Err(ProtoError::Auth(_)))); + assert!(s.sent().ends_with("\r\n\r\n*\r\n")); + // A server that calls a cancelled exchange a success is not believed. + let mut s = Script::new("+ \r\n+ e30=\r\n+ more?\r\nA0001 OK welcome\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.authenticate_xoauth2("ada@example.org", TOKEN), Err(ProtoError::Auth(_)))); + assert!(!imap.is_authenticated()); + // One that never stops asking. + let mut s = Script::new("+ \r\n".repeat(50)); + assert!(matches!(Imap::resume(&mut s).authenticate_xoauth2("ada@example.org", TOKEN), Err(ProtoError::Protocol(_)))); + assert_eq!(s.sent().matches("\r\n").count(), 4); +} + +#[test] +fn a_token_or_name_that_cannot_be_sent_is_refused() { + let mut s = Script::new("+ \r\nA0001 OK welcome\r\n"); + let mut imap = Imap::resume(&mut s); + for (user, token) in + [("ada", ""), ("ada", "tok\r\nA0002 LOGOUT"), ("ada", "tok\x01"), ("ada\x01auth=Bearer x", "tok"), ("a\0da", "tok"), ("ada\n", "tok")] + { + assert!(matches!(imap.authenticate_xoauth2(user, token), Err(ProtoError::Auth(_))), "{user:?} {token:?}"); + } + assert!(!imap.is_authenticated()); + assert_eq!(s.sent(), ""); +} + +#[test] +fn mailboxes_are_listed_with_names_in_every_form() { + let mut server = String::new(); + server += "* LIST (\\HasNoChildren) \"/\" INBOX\r\n"; + server += "* LIST (\\HasNoChildren \\Sent) \"/\" \"Sent Items\"\r\n"; + server += "* LIST (\\Noselect \\HasChildren) \"/\" \"[Gmail]\"\r\n"; + server += "* LIST (\\HasNoChildren \\Trash) \"/\" [Gmail]/Trash\r\n"; + server += "* LIST () NIL \"Entw&APw-rfe\"\r\n"; + server += "* LIST (\\HasNoChildren) \".\" {12}\r\nINBOX.&Jjo-!\r\n"; + server += "* LIST () \"/\" \"quoted \\\"name\\\" \\\\ here\"\r\n"; + server += "* LSUB () \"/\" subscribed\r\n"; + server += "* 5 EXISTS\r\n"; + server += "* LIST (\\HasNoChildren) \"/\" INBOX\r\n"; + server += "* LIST broken\r\n"; + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let list = Imap::resume(&mut s).list().unwrap(); + assert_eq!(s.sent(), "A0001 LIST \"\" \"*\"\r\n"); + assert_eq!( + list, + [ + mailbox("INBOX", "INBOX", Some('/'), &["\\HasNoChildren"]), + mailbox("Sent Items", "Sent Items", Some('/'), &["\\HasNoChildren", "\\Sent"]), + mailbox("[Gmail]", "[Gmail]", Some('/'), &["\\Noselect", "\\HasChildren"]), + mailbox("[Gmail]/Trash", "[Gmail]/Trash", Some('/'), &["\\HasNoChildren", "\\Trash"]), + mailbox("Entwürfe", "Entw&APw-rfe", None, &[]), + mailbox("INBOX.☺!", "INBOX.&Jjo-!", Some('.'), &["\\HasNoChildren"]), + mailbox("quoted \"name\" \\ here", "quoted \"name\" \\ here", Some('/'), &[]), + ] + ); + assert!(list[2].has_flag("\\NOSELECT") && !list[0].has_flag("\\Noselect")); +} + +#[test] +fn opening_a_mailbox() { + let mut server = String::new(); + server += "* 172 EXISTS\r\n* 1 RECENT\r\n* OK [UNSEEN 12] Message 12 is first unseen\r\n"; + server += "* OK [UIDVALIDITY 3857529045] UIDs valid\r\n* OK [UIDNEXT 4392] Predicted next UID\r\n"; + server += "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n* OK [PERMANENTFLAGS ()] No permanent flags permitted\r\n"; + server += "A0001 OK [READ-ONLY] EXAMINE completed\r\n"; + // The next one is empty and says little. + server += "* 0 EXISTS\r\n* OK [UIDVALIDITY 7]\r\nA0002 OK [READ-WRITE] SELECT completed\r\n"; + server += "A0003 NO [NONEXISTENT] no such mailbox\r\n"; + server += "+ go on\r\n* 3 EXISTS\r\n* OK [UIDVALIDITY 99999999999] too large to be one\r\nA0004 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.select("Sent Items", true).unwrap(), Selected { exists: 172, uid_validity: 3_857_529_045, uid_next: 4392 }); + assert_eq!(imap.select("INBOX", false).unwrap(), Selected { exists: 0, uid_validity: 7, uid_next: 0 }); + assert_eq!(imap.select("Nowhere", true), Err(ProtoError::Rejected("[NONEXISTENT] no such mailbox".into()))); + // A name the server wrote in UTF-8 goes back as a literal. + assert_eq!(imap.select("Entwürfe", true).unwrap(), Selected { exists: 3, uid_validity: 0, uid_next: 0 }); + assert_eq!(s.sent(), "A0001 EXAMINE \"Sent Items\"\r\nA0002 SELECT \"INBOX\"\r\nA0003 EXAMINE \"Nowhere\"\r\nA0004 EXAMINE {9}\r\nEntwürfe\r\n"); +} + +#[test] +fn flags_of_every_message_with_other_news_in_between() { + let mut server = String::new(); + server += "* 1 FETCH (UID 4 FLAGS (\\Seen \\Answered))\r\n"; + server += "* 2 FETCH (FLAGS (\\Flagged $Forwarded) UID 7)\r\n"; + server += "* 3 EXPUNGE\r\n* 9 EXISTS\r\n* 1 RECENT\r\n* FLAGS (\\Seen)\r\n"; + // Text for people may end like a literal without being one. + server += "* OK [ALERT] still here {5}\r\n"; + // Without a UID there is no telling which message this is. + server += "* 4 FETCH (FLAGS (\\Deleted))\r\n"; + server += "* 3 FETCH (UID 9 FLAGS ())\r\n"; + // The later word about a message counts. + server += "* 2 FETCH (UID 7 FLAGS (\\Seen))\r\n"; + // A message named without its flags is there all the same, and one named again keeps the flags it had. + server += "* 5 FETCH (UID 2 RFC822.SIZE 100)\r\n"; + server += "* 1 FETCH (UID 4)\r\n"; + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_flags("1:*").unwrap(); + assert_eq!(got, [fetched(2, &[]), fetched(4, &["\\Seen", "\\Answered"]), fetched(7, &["\\Seen"]), fetched(9, &[])]); + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS)\r\n"); + + let mut s = Script::new("A0001 OK nothing there\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_flags("5,9,12:20").unwrap(), []); + assert_eq!(s.sent(), "A0001 UID FETCH 5,9,12:20 (UID FLAGS)\r\n"); +} + +#[test] +fn sizes() { + let mut s = + Script::new("* 2 FETCH (RFC822.SIZE 99999999999 UID 9)\r\n* 1 FETCH (UID 4 RFC822.SIZE 2048)\r\n* 3 FETCH (UID 5)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_sizes("4:9").unwrap(), [(4, 2048), (9, 99_999_999_999)]); + assert_eq!(s.sent(), "A0001 UID FETCH 4:9 (UID RFC822.SIZE)\r\n"); +} + +#[test] +fn sets_that_are_not_sets_are_never_sent() { + for bad in ["", "1:* (BODY[])", "1 2", "a", "1:*\r\nA0002 LOGOUT"] { + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.uid_fetch_flags(bad), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert!(matches!(imap.uid_fetch_sizes(bad), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert_eq!(s.sent(), "", "{bad:?}"); + } +} + +#[test] +fn a_message_arrives_whole_whatever_is_in_it() { + // A body full of things that look like protocol. + let body = b"Subject: Hi\r\n\r\nA0001 OK fake\r\n* 1 FETCH (UID 2)\r\n{5}\r\n\"(\\\r\n)"; + let mut server = with_literal("* 5 FETCH (UID 12 FLAGS (\\Seen $Forwarded) INTERNALDATE \"17-Jul-1996 02:44:25 -0700\" BODY[] ", body, ")\r\n"); + server.extend_from_slice(b"A0001 OK done\r\n"); + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_message(12).unwrap().unwrap(); + assert_eq!( + got, + Fetched { + uid: 12, + flags: vec!["\\Seen".into(), "$Forwarded".into()], + internal_date: Some("17-Jul-1996 02:44:25 -0700".into()), + body: Some(body.to_vec()), + gmail_id: None, + gmail_labels: None + } + ); + assert_eq!(s.sent(), "A0001 UID FETCH 12 (UID FLAGS INTERNALDATE BODY.PEEK[])\r\n"); + assert!(s.finished()); +} + +#[test] +fn fetch_items_come_in_any_order() { + let body = b"From: ada@example.org\r\n\r\nBody\r\n"; + let mut server = with_literal( + "* 5 FETCH (BODY[] ", + body, + " INTERNALDATE \" 7-Jul-1996 02:44:25 +0000\" RFC822.SIZE 31 FLAGS () UID 12 X-UNKNOWN (a (b)))\r\n", + ); + server.extend_from_slice(b"A0001 OK done\r\n"); + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_message(12).unwrap().unwrap(); + assert_eq!( + (got.uid, got.flags.len(), got.internal_date.as_deref(), got.body.as_deref()), + (12, 0, Some(" 7-Jul-1996 02:44:25 +0000"), Some(&body[..])) + ); +} + +#[test] +fn bodies_at_the_edges() { + // Empty, as a literal of no bytes. + let mut s = Script::new("* 1 FETCH (UID 3 BODY[] {0}\r\n)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3).unwrap().unwrap().body, Some(Vec::new())); + // Short, in quotes. + let mut s = Script::new("* 1 FETCH (UID 3 BODY[] \"tiny \\\"body\\\"\")\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3).unwrap().unwrap().body, Some(b"tiny \"body\"".to_vec())); + // Under its old name. + let mut s = Script::new("* 1 FETCH (UID 3 RFC822 {2}\r\nok)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3).unwrap().unwrap().body, Some(b"ok".to_vec())); + // Flags in one response, the body in another. + let mut s = Script::new("* 1 FETCH (UID 3 FLAGS (\\Seen))\r\n* 1 FETCH (UID 3 BODY[] {2}\r\nok)\r\nA0001 OK done\r\n"); + let got = Imap::resume(&mut s).uid_fetch_message(3).unwrap().unwrap(); + assert_eq!((got.flags, got.body), (vec!["\\Seen".to_string()], Some(b"ok".to_vec()))); + // A megabyte in one piece. + let big = vec![b'x'; 1 << 20]; + let mut server = with_literal("* 1 FETCH (UID 3 BODY[] ", &big, ")\r\n"); + server.extend_from_slice(b"A0001 OK done\r\n"); + let mut s = Script::whole(server); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3).unwrap().unwrap().body, Some(big)); +} + +#[test] +fn a_message_that_is_gone_is_none() { + for server in [ + "A0001 OK nothing\r\n", + "* 1 FETCH (UID 3 BODY[] NIL)\r\nA0001 OK done\r\n", + "* 1 FETCH (UID 3 FLAGS (\\Seen))\r\nA0001 OK done\r\n", + "* 1 FETCH (UID 4 BODY[] {2}\r\nno)\r\n* 2 EXPUNGE\r\nA0001 OK done\r\n", + "* 1 FETCH (BODY[] {2}\r\nno)\r\nA0001 OK done\r\n", + ] { + let mut s = Script::new(server); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Ok(None), "{server:?}"); + } + // There is no message 0 to ask for. + let mut s = Script::new(""); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(0), Ok(None)); + assert_eq!(s.sent(), ""); + let mut s = Script::new("A0001 NO [SERVERBUG] can't read it\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Rejected("[SERVERBUG] can't read it".into()))); +} + +#[test] +fn a_header_arrives_alone() { + let header = b"From: ada@example.org\r\nSubject: Sixty megabytes\r\n\r\n"; + let mut server = with_literal("* 5 FETCH (UID 12 FLAGS (\\Seen) INTERNALDATE \"17-Jul-1996 02:44:25 -0700\" BODY[HEADER] ", header, ")\r\n"); + server.extend_from_slice(b"A0001 OK done\r\n"); + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_header(12).unwrap().unwrap(); + assert_eq!( + got, + Fetched { + uid: 12, + flags: vec!["\\Seen".into()], + internal_date: Some("17-Jul-1996 02:44:25 -0700".into()), + body: Some(header.to_vec()), + gmail_id: None, + gmail_labels: None + } + ); + assert_eq!(s.sent(), "A0001 UID FETCH 12 (UID FLAGS INTERNALDATE BODY.PEEK[HEADER])\r\n"); + assert!(s.finished()); + // Under its old name, and empty. + let mut s = Script::new("* 1 FETCH (UID 3 RFC822.HEADER {2}\r\n\r\n)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_header(3).unwrap().unwrap().body, Some(b"\r\n".to_vec())); + // A server that sends the whole message when asked for its header is not taken at its word, + // nor is a header taken for a message. + let mut s = Script::new("* 1 FETCH (UID 3 BODY[] {2}\r\nok)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_header(3), Ok(None)); + let mut s = Script::new("* 1 FETCH (UID 3 BODY[HEADER] {2}\r\nok)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Ok(None)); + // Gone, never there, refused. + let mut s = Script::new("A0001 OK nothing\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_header(3), Ok(None)); + let mut s = Script::new(""); + assert_eq!(Imap::resume(&mut s).uid_fetch_header(0), Ok(None)); + assert_eq!(s.sent(), ""); + let mut s = Script::new("A0001 NO [SERVERBUG] can't read it\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_header(3), Err(ProtoError::Rejected("[SERVERBUG] can't read it".into()))); + // A header as large as no header is: refused unread, like a message. + let mut s = Script::new(format!("* 1 FETCH (UID 3 BODY[HEADER] {{{}}}\r\nxxxx", MAX_LITERAL + 1)); + assert!(matches!(Imap::resume(&mut s).uid_fetch_header(3), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn the_stream_can_be_reached_between_commands() { + let mut s = Script::new("A0001 OK done\r\nA0002 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.select("INBOX", true).unwrap(); + // Looked at, not read from: the session goes on where it was. + assert_eq!(imap.get_mut().sent(), "A0001 EXAMINE \"INBOX\"\r\n"); + imap.select("Sent", true).unwrap(); + assert!(s.finished()); +} + +#[test] +fn oversized_literals_are_refused_unread() { + for size in [(MAX_LITERAL + 1).to_string(), "99999999999999999999999999".to_string(), u64::MAX.to_string()] { + let mut s = Script::new(format!("* 1 FETCH (UID 3 BODY[] {{{size}}}\r\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")); + let err = Imap::resume(&mut s).uid_fetch_message(3).unwrap_err(); + assert!(matches!(&err, ProtoError::Protocol(text) if text.to_string().contains("64 MB")), "{err:?}"); + // The x's were not read as if they were the message. + assert!(!s.finished()); + } + // Several literals that are only too much together. + let mut s = Script::new(format!("* 1 FETCH (A {{2}}\r\nab B {{{}}}\r\n", MAX_LITERAL - 1)); + assert!(matches!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn responses_without_end_are_refused() { + // More literals than any response has. + let mut s = Script::whole(format!("* 1 FETCH ({}", "X {0}\r\n ".repeat(MAX_LITERALS + 2))); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Protocol(said!("the server's response has too many parts")))); + // More text than any response has. + let line = format!("{} {{0}}\r\n", "x".repeat(MAX_LINE - 100)); + let mut s = Script::whole(format!("* 1 FETCH ({}", line.repeat(6))); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Protocol(said!("the server's response is too long")))); + // A line that never ends. + let mut s = Script::whole(format!("* 1 FETCH ({}", "x".repeat(MAX_LINE * 2))); + assert!(matches!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Protocol(_)))); + // Lists inside lists inside lists. + let mut s = Script::new(format!("* 1 FETCH {}\r\nA0001 OK done\r\n", "(".repeat(200))); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Protocol(said!("the server's response is nested too deeply")))); +} + +#[test] +fn storing_flags() { + let mut s = Script::new("A0001 OK done\r\nA0002 OK done\r\nA0003 NO [READ-ONLY] mailbox is read-only\r\n"); + let mut imap = Imap::resume(&mut s); + imap.uid_store(7, true, &["\\Seen", "\\Flagged"]).unwrap(); + imap.uid_store(7, false, &["$Forwarded"]).unwrap(); + assert_eq!(imap.uid_store(8, true, &["\\Deleted"]), Err(ProtoError::Rejected("[READ-ONLY] mailbox is read-only".into()))); + assert_eq!( + s.sent(), + "A0001 UID STORE 7 +FLAGS.SILENT (\\Seen \\Flagged)\r\nA0002 UID STORE 7 -FLAGS.SILENT ($Forwarded)\r\nA0003 UID STORE 8 +FLAGS.SILENT (\\Deleted)\r\n" + ); + + // Nothing to store, or nothing to store it on: the server isn't asked. + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.uid_store(7, true, &[]), Ok(())); + assert!(matches!(imap.uid_store(0, true, &["\\Seen"]), Err(ProtoError::Protocol(_)))); + assert_eq!(s.sent(), ""); + + for bad in ["", "\\", "two words", "\\Seen) (\\Deleted", "\\\\Seen", "a\r\nb", "sée"] { + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.uid_store(7, true, &[bad]), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert!(matches!(imap.append("Sent", &["\\Seen", bad], b"x"), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert_eq!(s.sent(), "", "{bad:?}"); + } +} + +#[test] +fn flags_are_stored_for_many_messages_at_once() { + let mut s = Script::new("A0001 OK done\r\nA0002 OK done\r\nA0003 NO [READ-ONLY] mailbox is read-only\r\n"); + let mut imap = Imap::resume(&mut s); + imap.uid_store_set("4,7:9,12", true, &["\\Seen"]).unwrap(); + imap.uid_store_set("5", false, &["\\Flagged", "\\Answered"]).unwrap(); + assert_eq!(imap.uid_store_set("6", true, &["\\Deleted"]), Err(ProtoError::Rejected("[READ-ONLY] mailbox is read-only".into()))); + assert_eq!( + s.sent(), + "A0001 UID STORE 4,7:9,12 +FLAGS.SILENT (\\Seen)\r\nA0002 UID STORE 5 -FLAGS.SILENT (\\Flagged \\Answered)\r\nA0003 UID STORE 6 +FLAGS.SILENT (\\Deleted)\r\n" + ); +} + +#[test] +fn a_set_for_a_change_names_its_messages() { + // Nothing that reaches for messages nobody looked at, and nothing that isn't a set at all. + let long = format!("1:{}", MAX_SET_UIDS + 1); + for bad in ["1:*", "*", "", "0", "5:3", "1,,2", "1:2:3", "4 5", "+4", "4,", "4\r\nA0002 EXPUNGE", "4294967296", long.as_str()] { + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["UIDPLUS".into(), "MOVE".into()]); + assert!(matches!(imap.uid_store_set(bad, true, &["\\Deleted"]), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert!(matches!(imap.uid_move(bad, "Archive"), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert!(matches!(imap.uid_copy(bad, "Archive"), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert!(matches!(imap.uid_expunge(bad), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert_eq!(s.sent(), "", "{bad:?}"); + } + // Reading may ask for everything. + let mut s = Script::new("A0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_flags("1:*").unwrap(), []); +} + +#[test] +fn moving_and_copying_say_where_the_messages_went() { + // A copy answers in its last line, a move before the messages leave (RFC 6851). + let mut server = String::new(); + server += "A0001 OK [COPYUID 38505 304,319:320 3956:3958] Done\r\n"; + server += "* OK [COPYUID 432432 42:43 1202:1203] moved\r\n* 2 EXPUNGE\r\n* 1 EXPUNGE\r\nA0002 OK Done\r\n"; + // Nothing matched, or a server without UIDPLUS: done, and nothing known. + server += "A0003 OK No messages\r\nA0004 OK done\r\n"; + server += "A0005 NO [TRYCREATE] no such mailbox\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + assert_eq!( + imap.uid_copy("304,319:320", "Archive").unwrap(), + Some(Copied { uid_validity: 38_505, uids: vec![(304, 3956), (319, 3957), (320, 3958)] }) + ); + assert_eq!(imap.uid_move("42:43", "Entw&APw-rfe").unwrap(), Some(Copied { uid_validity: 432_432, uids: vec![(42, 1202), (43, 1203)] })); + assert_eq!(imap.uid_move("99", "Archive"), Ok(None)); + assert_eq!(imap.uid_copy("7", "Sent \"old\" mail"), Ok(None)); + assert_eq!(imap.uid_copy("7", "Nowhere"), Err(ProtoError::Rejected("[TRYCREATE] no such mailbox".into()))); + assert_eq!( + s.sent(), + "A0001 UID COPY 304,319:320 \"Archive\"\r\nA0002 UID MOVE 42:43 \"Entw&APw-rfe\"\r\nA0003 UID MOVE 99 \"Archive\"\r\n\ + A0004 UID COPY 7 \"Sent \\\"old\\\" mail\"\r\nA0005 UID COPY 7 \"Nowhere\"\r\n" + ); +} + +#[test] +fn a_doubtful_copyuid_is_no_answer() { + // A wrong pairing would tie a message here to another one there: anything short of certain + // counts as not said. + for doubtful in [ + "[COPYUID 7 4 9,10]", + "[COPYUID 7 4,5 9]", + "[COPYUID 7 5,4 9,10]", + "[COPYUID 7 4:5 10:9]", + "[COPYUID 7 5:4 9:10]", + "[COPYUID 7 4,4 9,10]", + "[COPYUID 7 4,5 9,9]", + "[COPYUID 0 4 9]", + "[COPYUID 7 0 9]", + "[COPYUID 7 4 0]", + "[COPYUID 7 4 *]", + "[COPYUID 7 1:* 1:*]", + "[COPYUID 7 4 9 12]", + "[COPYUID 7 4]", + "[COPYUID 7]", + "[COPYUID]", + "[COPYUID x 4 9]", + "[COPYUID 7 +4 9]", + "[COPYUID -7 4 9]", + "[COPYUID 99999999999 4 9]", + "[COPYUID 7 4 99999999999]", + "[COPYUID 7 1:4000000000 1:4000000000]", + "[COPYUID 7 4, 9]", + "COPYUID 7 4 9", + ] { + let mut s = Script::new(format!("A0001 OK {doubtful} done\r\n")); + assert_eq!(Imap::resume(&mut s).uid_copy("4:5", "Archive"), Ok(None), "{doubtful}"); + } + // Said twice is said in two ways, even when one can be read; and what was said during + // another command says nothing about this one. + let mut s = Script::new("* OK [COPYUID 7 4 9] moved\r\nA0001 OK [COPYUID 7 4 10] done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_move("4", "Archive"), Ok(None)); + let mut s = Script::new("* OK [COPYUID 7 4 9] moved\r\n* OK [COPYUID 7 nonsense] moved\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_move("4", "Archive"), Ok(None)); + let mut s = Script::new("* OK [COPYUID 7 4 9] out of the blue\r\nA0001 OK done\r\nA0002 OK done\r\nA0003 OK [COPYUID 7 4 11] done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.select("INBOX", false).unwrap(); + assert_eq!(imap.uid_copy("4", "Archive"), Ok(None)); + assert_eq!(imap.uid_copy("4", "Archive"), Ok(Some(Copied { uid_validity: 7, uids: vec![(4, 11)] }))); + // A refused move knows nothing either. + let mut s = Script::new("* OK [COPYUID 7 4 9] moved\r\nA0001 NO [OVERQUOTA] full\r\n"); + assert_eq!(Imap::resume(&mut s).uid_move("4", "Archive"), Err(ProtoError::Rejected("[OVERQUOTA] full".into()))); + // As many as one set names are taken; more is more than was asked about. + let all = format!("1:{MAX_SET_UIDS}"); + let mut s = Script::new(format!("A0001 OK [COPYUID 7 {all} {all}] done\r\n")); + assert_eq!(Imap::resume(&mut s).uid_copy(&all, "Archive").unwrap().map(|c| c.uids.len()), Some(MAX_SET_UIDS)); +} + +#[test] +fn single_messages_are_removed_only_by_a_server_that_can() { + // A server that didn't say UIDPLUS only knows the EXPUNGE that takes every marked message: + // it is never asked. + for capabilities in [None, Some(vec!["IMAP4REV1".to_string(), "MOVE".to_string()])] { + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.capabilities = capabilities; + assert!(matches!(imap.uid_expunge("4"), Err(ProtoError::Protocol(_)))); + assert_eq!(s.sent(), ""); + } + let mut s = Script::new( + "* CAPABILITY IMAP4rev1 UIDPLUS\r\nA0001 OK done\r\n* 3 EXPUNGE\r\n* 3 EXPUNGE\r\nA0002 OK gone\r\nA0003 NO [NOPERM] not yours\r\n", + ); + let mut imap = Imap::resume(&mut s); + imap.capabilities().unwrap(); + imap.uid_expunge("4,7:8").unwrap(); + assert_eq!(imap.uid_expunge("9"), Err(ProtoError::Rejected("[NOPERM] not yours".into()))); + assert_eq!(s.sent(), "A0001 CAPABILITY\r\nA0002 UID EXPUNGE 4,7:8\r\nA0003 UID EXPUNGE 9\r\n"); +} + +#[test] +fn mailboxes_are_made_and_subscribed_to() { + let mut s = Script::new("A0001 OK made\r\nA0002 OK done\r\nA0003 NO [ALREADYEXISTS] there is one\r\n+ go on\r\nA0004 OK made\r\n"); + let mut imap = Imap::resume(&mut s); + let name = format!("Projects/{}", encode_utf7("Entwürfe & Pläne")); + imap.create(&name).unwrap(); + imap.subscribe(&name).unwrap(); + assert_eq!(imap.create("INBOX"), Err(ProtoError::Rejected("[ALREADYEXISTS] there is one".into()))); + // A name that isn't in the mailbox encoding still can't break the command. + imap.create("Pläne\r\nA0005 LOGOUT").unwrap(); + assert!(matches!(imap.create("nul\0here"), Err(ProtoError::Protocol(_)))); + assert!(matches!(imap.subscribe("nul\0here"), Err(ProtoError::Protocol(_)))); + assert_eq!( + s.sent(), + "A0001 CREATE \"Projects/Entw&APw-rfe &- Pl&AOQ-ne\"\r\nA0002 SUBSCRIBE \"Projects/Entw&APw-rfe &- Pl&AOQ-ne\"\r\nA0003 CREATE \"INBOX\"\r\n\ + A0004 CREATE {20}\r\nPläne\r\nA0005 LOGOUT\r\n" + ); +} + +#[test] +fn uids_are_written_as_short_exact_sets() { + let texts = |uids: &[u32]| uid_sets(uids).into_iter().map(|(text, _)| text).collect::<Vec<_>>(); + assert_eq!(texts(&[]), Vec::<String>::new()); + assert_eq!(texts(&[0]), Vec::<String>::new()); + assert_eq!(texts(&[7]), ["7"]); + assert_eq!(texts(&[9, 4, 8, 7, 12, 4, 0]), ["4,7:9,12"]); + assert_eq!(texts(&[u32::MAX, u32::MAX - 1, 1]), ["1,4294967294:4294967295"]); + assert_eq!(uid_sets(&[9, 4, 8]), [("4,8:9".to_string(), vec![4, 8, 9])]); + // A long run is cut where a set is full, not stretched over it. + let run: Vec<u32> = (10..10 + 2 * MAX_SET_UIDS as u32 + 3).collect(); + assert_eq!(texts(&run), ["10:509", "510:1009", "1010:1012"]); + // Scattered numbers fill a set by its length first. + let scattered: Vec<u32> = (0..400).map(|n| 4_000_000_000 + 2 * n).collect(); + let sets = uid_sets(&scattered); + assert!(sets.len() > 1 && sets.iter().all(|(text, _)| text.len() <= MAX_SET_TEXT)); + assert_eq!(sets.iter().map(|(_, uids)| uids.len()).sum::<usize>(), 400); +} + +#[test] +fn appending_waits_for_the_go_ahead() { + let message = b"Subject: Sent\r\n\r\nKept.\r\n"; + let mut s = Script::new("+ Ready for literal data\r\nA0001 OK [APPENDUID 38505 3955] done\r\n+ go\r\nA0002 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.append("Sent Items", &["\\Seen"], message).unwrap(); + imap.append("Entw&APw-rfe", &[], b"").unwrap(); + assert_eq!(s.sent(), "A0001 APPEND \"Sent Items\" (\\Seen) {24}\r\nSubject: Sent\r\n\r\nKept.\r\n\r\nA0002 APPEND \"Entw&APw-rfe\" {0}\r\n\r\n"); + + // Refused before the message was sent: it stays here. + let mut s = Script::new("A0001 NO [TRYCREATE] no such mailbox\r\n"); + assert_eq!(Imap::resume(&mut s).append("Nowhere", &[], message), Err(ProtoError::Rejected("[TRYCREATE] no such mailbox".into()))); + assert_eq!(s.sent(), "A0001 APPEND \"Nowhere\" {24}\r\n"); + + // Refused after. + let mut s = Script::new("+ go\r\nA0001 NO [OVERQUOTA] mailbox full\r\n"); + assert_eq!(Imap::resume(&mut s).append("Sent", &[], message), Err(ProtoError::Rejected("[OVERQUOTA] mailbox full".into()))); + + // "Done" before the message was sent can't be true. + let mut s = Script::new("A0001 OK done already\r\n"); + assert!(matches!(Imap::resume(&mut s).append("Sent", &[], message), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn appending_with_a_date_says_where_the_message_went() { + let message = b"Subject: Moved\r\n\r\nKept.\r\n"; + let date = "01-Jul-2003 09:52:37 +0000"; + let mut s = Script::new("+ go\r\nA0001 OK [APPENDUID 38505 3955] done\r\n+ go\r\nA0002 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.append_at("INBOX", &["\\Seen"], Some(date), message), Ok(Some(Appended { uid_validity: 38505, uid: 3955 }))); + // A server that doesn't say: nothing is known of where it went. + assert_eq!(imap.append_at("INBOX", &[], Some(" 1-Jul-2003 09:52:37 -0700"), message), Ok(None)); + assert_eq!( + s.sent(), + "A0001 APPEND \"INBOX\" (\\Seen) \"01-Jul-2003 09:52:37 +0000\" {25}\r\nSubject: Moved\r\n\r\nKept.\r\n\r\n\ + A0002 APPEND \"INBOX\" \" 1-Jul-2003 09:52:37 -0700\" {25}\r\nSubject: Moved\r\n\r\nKept.\r\n\r\n" + ); + // An answer that doesn't pair one message with one UID beyond doubt is no answer. + for code in ["[APPENDUID 0 5]", "[APPENDUID 38505 0]", "[APPENDUID 38505 1:3]", "[APPENDUID 38505]", "[APPENDUID 38505 7 8]", "[APPENDUID x 7]"] { + let mut s = Script::new(format!("+ go\r\nA0001 OK {code} done\r\n")); + assert_eq!(Imap::resume(&mut s).append_at("INBOX", &[], None, message), Ok(None), "{code}"); + } + // Two answers to one message might disagree: neither is taken. + let mut s = Script::new("+ go\r\n* OK [APPENDUID 1 2] one\r\nA0001 OK [APPENDUID 1 3] two\r\n"); + assert_eq!(Imap::resume(&mut s).append_at("INBOX", &[], None, message), Ok(None)); + // A date that isn't one is never sent, nor is what it carries. + for bad in + ["1-Jul-2003 09:52:37 +0000", "01-Jul-2003 09:52:37", "01-Jul-2003 09:52:37 +0000\r\nA2 DELETE INBOX", "01-Jul-2003 09:52:37 +00\"0", ""] + { + let mut s = Script::new("+ go\r\nA0001 OK done\r\n"); + assert!(matches!(Imap::resume(&mut s).append_at("INBOX", &[], Some(bad), message), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert_eq!(s.sent(), "", "{bad:?}"); + } +} + +#[test] +fn searching_a_header_answers_the_uids_it_names() { + let mut s = Script::new("* SEARCH 9 4 0 x 4 4294967295\r\n* 3 EXISTS\r\nA0001 OK done\r\nA0002 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + // In UID order and once each; what isn't a UID is passed over. + assert_eq!(imap.uid_search_header("Message-ID", "<a.1@example.org>"), Ok(vec![4, 9, u32::MAX])); + // Quotes in the text are quoted. + assert_eq!(imap.uid_search_header("Message-ID", "<say\"hi\"@example.org>"), Ok(vec![])); + assert_eq!( + s.sent(), + "A0001 UID SEARCH UNDELETED HEADER Message-ID \"<a.1@example.org>\"\r\n\ + A0002 UID SEARCH UNDELETED HEADER Message-ID \"<say\\\"hi\\\"@example.org>\"\r\n" + ); + // A refusal is said. + let mut s = Script::new("A0001 NO no searching here\r\n"); + assert!(matches!(Imap::resume(&mut s).uid_search_header("Message-ID", "<a@example.org>"), Err(ProtoError::Rejected(_)))); + // What could end the command early, or isn't text, is never sent. + for (field, text) in [ + ("Message-ID", "<a@example.org>\r\nA2 DELETE INBOX"), + ("Message-ID", "<ä@example.org>"), + ("Message-ID", ""), + ("Message ID", "<a@example.org>"), + ("", "<a>"), + ] { + let mut s = Script::new("A0001 OK done\r\n"); + assert!(matches!(Imap::resume(&mut s).uid_search_header(field, text), Err(ProtoError::Protocol(_))), "{field:?} {text:?}"); + assert_eq!(s.sent(), "", "{field:?} {text:?}"); + } + // A server that names more messages than are ever looked for is taken at its first word. + let many: String = (1..=5000).map(|n| format!(" {n}")).collect(); + let mut s = Script::new(format!("* SEARCH{many}\r\nA0001 OK done\r\n")); + assert_eq!(Imap::resume(&mut s).uid_search_header("Message-ID", "<a@example.org>").map(|uids| uids.len()), Ok(MAX_FOUND)); +} + +#[test] +fn starttls_hands_the_stream_back() { + let mut s = Script::new("* OK ready\r\n* CAPABILITY IMAP4rev1 STARTTLS\r\nA0001 OK done\r\nA0002 OK begin TLS now\r\n"); + let mut imap = Imap::connect(&mut s).unwrap(); + assert!(imap.capabilities().unwrap().contains(&"STARTTLS".to_string())); + let stream = imap.starttls().unwrap(); + assert_eq!(stream.sent(), "A0001 CAPABILITY\r\nA0002 STARTTLS\r\n"); + // The session starts afresh inside TLS. + let mut s = Script::new("A0001 OK done\r\n"); + Imap::resume(&mut s).capabilities().unwrap(); + + let mut s = Script::new("A0001 BAD no TLS here\r\n"); + assert_eq!(Imap::resume(&mut s).starttls().unwrap_err(), ProtoError::Rejected("no TLS here".into())); +} + +#[test] +fn text_slipped_in_before_tls_is_refused() { + // Both lines arrive in one read, as an attacker in the middle would send them. + let mut s = Script::whole("A0001 OK begin TLS now\r\nA0002 OK [CAPABILITY IMAP4rev1] injected\r\n"); + assert!(matches!(Imap::resume(&mut s).starttls(), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn logging_out() { + let mut s = Script::new("* BYE logging out\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).logout(), Ok(())); + assert_eq!(s.sent(), "A0001 LOGOUT\r\n"); + // A server that hangs up without the last word has logged us out too. + for server in ["* BYE\r\n", ""] { + let mut s = Script::new(server); + assert_eq!(Imap::resume(&mut s).logout(), Ok(()), "{server:?}"); + } + let mut s = Script::new("A0001 BAD what\r\n"); + assert!(matches!(Imap::resume(&mut s).logout(), Err(ProtoError::Rejected(_)))); +} + +#[test] +fn a_server_that_says_bye_has_ended_the_session() { + let mut s = Script::new("* 3 EXISTS\r\n* BYE [UNAVAILABLE] shutting down\r\n"); + assert_eq!( + Imap::resume(&mut s).select("INBOX", true), + Err(ProtoError::Io(said!("the server ended the session: {reason}", reason = Arg::said("[UNAVAILABLE] shutting down".into())))) + ); +} + +#[test] +fn tags_count_up_and_must_match() { + let mut s = Script::new("* OK ready\r\nA0001 OK one\r\nA0002 OK two\r\nA0003 OK three\r\nA0009 OK not ours\r\n"); + let mut imap = Imap::connect(&mut s).unwrap(); + imap.capabilities().unwrap(); + imap.list().unwrap(); + imap.select("INBOX", true).unwrap(); + assert_eq!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(said!("the server answered a command that wasn't sent")))); + assert_eq!(s.sent(), "A0001 CAPABILITY\r\nA0002 LIST \"\" \"*\"\r\nA0003 EXAMINE \"INBOX\"\r\nA0004 UID FETCH 1:* (UID FLAGS)\r\n"); +} + +#[test] +fn junk_in_a_session_is_a_protocol_error() { + for junk in ["+ send more\r\n", "garbage\r\n", "A0001 FETCH x\r\n", "A0001 BYE\r\n", "A0001 PREAUTH hi\r\n", "\r\n", "A0001\r\n", " OK\r\n"] { + let mut s = Script::new(junk); + assert!(matches!(Imap::resume(&mut s).capabilities(), Err(ProtoError::Protocol(_))), "{junk:?}"); + } + // Refusals keep the server's words; one without words still says something. + let mut s = Script::new("A0001 NO\r\n"); + assert_eq!(Imap::resume(&mut s).capabilities(), Err(ProtoError::Rejected(said!("the command was refused")))); +} + +#[test] +fn a_dead_connection_is_an_io_error() { + // In the middle of a line, and in the middle of a literal. + for server in ["* 1 FETCH (UID 3 BO", "* 1 FETCH (UID 3 BODY[] {50}\r\nonly this much", "* 1 FETCH (UID 3 BODY[] {5}\r\nabcde"] { + let mut s = Script::new(server); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Io(said!("the server closed the connection"))), "{server:?}"); + } + assert!(matches!(Imap::connect(Broken(ErrorKind::TimedOut)), Err(ProtoError::Io(_)))); + assert!(matches!(Imap::resume(Broken(ErrorKind::ConnectionReset)).list(), Err(ProtoError::Io(_)))); +} + +#[test] +fn text_that_cannot_be_sent_is_refused() { + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.select("nul\0here", true), Err(ProtoError::Protocol(_)))); + assert!(matches!(imap.append("nul\0here", &[], b"x"), Err(ProtoError::Protocol(_)))); + assert_eq!(s.sent(), ""); +} + +/// Everything a client does, against whatever the "server" says. +fn drive(server: &[u8]) { + let mut s = Script::new(server); + if let Ok(mut imap) = Imap::connect(&mut s) { + let _ = imap.capabilities(); + let _ = imap.login("ada", "hunter2"); + let _ = imap.login("ädä", "pässword"); + let _ = imap.list(); + let _ = imap.select("INBOX", true); + let _ = imap.uid_fetch_flags("1:*"); + let _ = imap.uid_fetch_sizes("1:*"); + let _ = imap.uid_fetch_message(1); + let _ = imap.uid_fetch_header(1); + let _ = imap.uid_store(1, true, &["\\Seen"]); + let _ = imap.uid_store_set("1:3,7", false, &["\\Flagged"]); + let _ = imap.uid_move("1:3", "Archive"); + let _ = imap.uid_copy("7", "Entw&APw-rfe"); + let _ = imap.uid_expunge("7"); + let _ = imap.create("Projects/New"); + let _ = imap.subscribe("Projects/New"); + let _ = imap.append("Sent", &["\\Seen"], b"Subject: x\r\n\r\n"); + let _ = imap.uid_search_header("Message-ID", "<a.1@example.org>"); + let _ = imap.uid_fetch_flags_gmail("1:*"); + let _ = imap.uid_search_gmail("1:500", "category:social"); + let _ = imap.logout(); + } + // Changes, by a session that was told it may make them. + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["MOVE".into(), "UIDPLUS".into()]); + let _ = imap.select("INBOX", false); + let _ = imap.uid_move("1,3:5", "Archive"); + let _ = imap.uid_copy("1", "Archive"); + let _ = imap.uid_expunge("1,3:5"); + let _ = imap.uid_store_set("2", true, &["\\Deleted"]); + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + let _ = imap.uid_fetch_message(1); + let _ = imap.uid_fetch_header(1); + let _ = imap.list(); + let _ = imap.uid_fetch_flags("1:*"); + let _ = imap.starttls(); + // With a token: after a go-ahead, and with the command. + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + let _ = imap.authenticate_xoauth2("ada@example.org", "tok.en-123"); + let _ = imap.list(); + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["SASL-IR".into(), "AUTH=XOAUTH2".into()]); + let _ = imap.authenticate_xoauth2("ada@example.org", "tok.en-123"); + let _ = imap.select("INBOX", true); +} + +const WORDS: [&str; 43] = [ + "SEARCH ", + "4294967295 ", + "BODY[HEADER] ", + "[COPYUID 7 1 9] ", + "[COPYUID 7 1,3:5 9:12] ", + "[COPYUID ", + "1:4 ", + "9,10 ", + "EXPUNGE", + "* ", + "A0001 ", + "A0002 ", + "A0003 ", + "OK ", + "NO ", + "BAD ", + "BYE ", + "PREAUTH ", + "+ ", + "1 ", + "FETCH ", + "LIST ", + "EXISTS", + "CAPABILITY ", + "(", + ")", + "UID 1 ", + "FLAGS ", + "BODY[] ", + "INTERNALDATE ", + "RFC822.SIZE 9 ", + "{3}\r\n", + "{0}\r\n", + "{99999999999}\r\n", + "abc", + "\"", + "\\", + "NIL ", + "\r\n", + "[UIDNEXT 5] ", + "[", + "]", + "é", +]; + +proptest! { + #[test] + fn arbitrary_server_bytes_never_panic_or_hang(server in proptest::collection::vec(any::<u8>(), 0..600)) { + drive(&server); + // And after a proper greeting, so the session gets going. + let mut greeted = b"* OK ready\r\n".to_vec(); + greeted.extend_from_slice(&server); + drive(&greeted); + } + + #[test] + fn response_shaped_noise_never_panics(words in proptest::collection::vec(proptest::sample::select(&WORDS[..]), 0..80), greeted in any::<bool>()) { + let server = format!("{}{}", if greeted { "* OK ready\r\n" } else { "" }, words.concat()); + drive(server.as_bytes()); + } + + #[test] + fn any_body_arrives_as_it_was_sent(body in proptest::collection::vec(any::<u8>(), 0..2000), flags_first in any::<bool>()) { + let mut server = if flags_first { + with_literal("* 1 FETCH (UID 9 FLAGS (\\Seen) BODY[] ", &body, ")\r\n") + } else { + with_literal("* 1 FETCH (BODY[] ", &body, " FLAGS (\\Seen) UID 9)\r\n") + }; + server.extend_from_slice(b"A0001 OK done\r\n"); + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_message(9).unwrap().unwrap(); + prop_assert_eq!(got.body, Some(body)); + prop_assert_eq!(got.flags, vec!["\\Seen".to_string()]); + } + + #[test] + fn any_uids_are_named_once_each_by_sets_that_read_back(uids in proptest::collection::vec(prop_oneof![1u32..40, 1u32..3000, any::<u32>()], 0..1500)) { + let mut expected: Vec<u32> = uids.iter().copied().filter(|uid| *uid != 0).collect(); + expected.sort_unstable(); + expected.dedup(); + let mut named_in_all = Vec::new(); + for (text, named_here) in uid_sets(&uids) { + // A set says what it is said to say, and is one a changing command takes. + prop_assert_eq!(uids_of(&text), Some(named_here.clone()), "{}", text); + prop_assert!(named(&text).is_ok() && is_set(&text), "{}", text); + prop_assert!(text.len() <= MAX_SET_TEXT && !named_here.is_empty() && named_here.len() <= MAX_SET_UIDS); + named_in_all.extend(named_here); + } + prop_assert_eq!(named_in_all, expected); + } + + #[test] + fn any_copyuid_text_is_read_or_not(text in "[0-9,:*+ -]{0,40}") { + if let Some(copied) = copied_from(&text) { + prop_assert!(copied.uid_validity != 0 && copied.uids.len() <= MAX_SET_UIDS); + prop_assert!(copied.uids.iter().all(|(from, to)| *from != 0 && *to != 0)); + prop_assert!(copied.uids.iter().zip(copied.uids.iter().skip(1)).all(|(a, b)| a.0 < b.0 && a.1 != b.1)); + } + } + + #[test] + fn any_mailbox_name_survives_quoting(name in "[ -~]{1,40}") { + // What the client would send as a quoted string, a server sends back in LIST. + let mut s = Script::new("A0001 OK done\r\n"); + Imap::resume(&mut s).select(&name, true).unwrap(); + let sent = s.sent(); + let quoted = sent.strip_prefix("A0001 EXAMINE ").unwrap().strip_suffix("\r\n").unwrap(); + let mut s = Script::new(format!("* LIST () \"/\" {quoted}\r\nA0001 OK done\r\n")); + let list = Imap::resume(&mut s).list().unwrap(); + prop_assert_eq!(list.len(), 1); + prop_assert_eq!(&list[0].raw, &name); + } +} + +#[test] +fn namespace_reads_personal_prefix_and_delimiter() { + let mut s = Script::new("* NAMESPACE ((\"INBOX.\" \".\")) NIL NIL\r\nA0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["IMAP4REV1".into(), "NAMESPACE".into()]); + assert_eq!(imap.namespace().unwrap(), Some(Namespace { prefix: "INBOX.".into(), delimiter: Some('.') })); + assert_eq!(s.sent(), "A0001 NAMESPACE\r\n"); + + let mut s = Script::new("* NAMESPACE ((\"\" \"/\")) NIL NIL\r\nA0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["IMAP4REV1".into(), "NAMESPACE".into()]); + assert_eq!(imap.namespace().unwrap(), Some(Namespace { prefix: String::new(), delimiter: Some('/') })); + + let mut s = Script::new(""); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["IMAP4REV1".into()]); + assert_eq!(imap.namespace().unwrap(), None); + assert_eq!(s.sent(), ""); +} diff --git a/crates/proto/src/imap/utf7.rs b/crates/proto/src/imap/utf7.rs new file mode 100644 index 000000000..7c7990e76 --- /dev/null +++ b/crates/proto/src/imap/utf7.rs @@ -0,0 +1,175 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Modified UTF-7, the encoding of mailbox names (RFC 3501 §5.1.3). +//! +//! Printable ASCII stands for itself, except `&`, which is written `&-`. Everything else is +//! UTF-16 in base64 (with `,` in place of `/`, and no padding) between `&` and `-`. + +const DIGITS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,"; + +fn digit(six_bits: u32) -> char { + DIGITS.get((six_bits & 0x3F) as usize).map_or('A', |b| char::from(*b)) +} + +/// A mailbox name as people read it. Text that isn't valid modified UTF-7 is kept as it is. +pub fn decode_utf7(name: &str) -> String { + let mut out = String::with_capacity(name.len()); + let mut rest = name; + // Every round takes at least the `&` off `rest`. + while let Some(at) = rest.find('&') { + out.push_str(rest.get(..at).unwrap_or("")); + let after = rest.get(at + 1..).unwrap_or(""); + rest = match after.find('-') { + Some(0) => { + out.push('&'); + after.get(1..).unwrap_or("") + } + Some(end) => match shifted(after.get(..end).unwrap_or("")) { + Some(text) => { + out.push_str(&text); + after.get(end + 1..).unwrap_or("") + } + // Not base64 after all: an ampersand like any other character. + None => { + out.push('&'); + after + } + }, + None => { + out.push('&'); + after + } + }; + } + out.push_str(rest); + out +} + +/// The text of one base64 run, or `None` when it isn't one. +fn shifted(encoded: &str) -> Option<String> { + let mut units = Vec::with_capacity(encoded.len() * 3 / 8 + 1); + let (mut bits, mut count) = (0u32, 0u32); + for b in encoded.bytes() { + let value = DIGITS.iter().position(|d| *d == b)? as u32; + bits = (bits << 6) | value; + count += 6; + if count >= 16 { + count -= 16; + units.push((bits >> count) as u16); + bits &= (1 << count) - 1; + } + } + // What is left over is padding: less than one digit's worth. + if count >= 6 || units.is_empty() { + return None; + } + String::from_utf16(&units).ok() +} + +/// A mailbox name as a server wants it. +pub fn encode_utf7(name: &str) -> String { + let mut out = String::with_capacity(name.len()); + let mut pending: Vec<u16> = Vec::new(); + for c in name.chars() { + if matches!(c, ' '..='~') { + flush(&mut pending, &mut out); + out.push(c); + if c == '&' { + out.push('-'); + } + } else { + let mut units = [0u16; 2]; + pending.extend_from_slice(c.encode_utf16(&mut units)); + } + } + flush(&mut pending, &mut out); + out +} + +/// Write the characters waiting to be encoded as one base64 run. +fn flush(pending: &mut Vec<u16>, out: &mut String) { + if pending.is_empty() { + return; + } + out.push('&'); + let (mut bits, mut count) = (0u32, 0u32); + for unit in pending.drain(..) { + bits = (bits << 16) | u32::from(unit); + count += 16; + while count >= 6 { + count -= 6; + out.push(digit(bits >> count)); + } + bits &= (1 << count) - 1; + } + if count > 0 { + out.push(digit(bits << (6 - count))); + } + out.push('-'); +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use proptest::prelude::*; + + use super::*; + + #[test] + fn the_examples_of_the_rfc() { + // RFC 3501 §5.1.3. + assert_eq!(decode_utf7("~peter/mail/&U,BTFw-/&ZeVnLIqe-"), "~peter/mail/台北/日本語"); + assert_eq!(encode_utf7("~peter/mail/台北/日本語"), "~peter/mail/&U,BTFw-/&ZeVnLIqe-"); + assert_eq!(decode_utf7("&Jjo-!"), "☺!"); + assert_eq!(encode_utf7("☺!"), "&Jjo-!"); + } + + #[test] + fn ordinary_names() { + assert_eq!(encode_utf7("INBOX"), "INBOX"); + assert_eq!(encode_utf7("Tom & Jerry"), "Tom &- Jerry"); + assert_eq!(decode_utf7("Tom &- Jerry"), "Tom & Jerry"); + assert_eq!(encode_utf7("Entwürfe"), "Entw&APw-rfe"); + assert_eq!(decode_utf7("Entw&APw-rfe"), "Entwürfe"); + assert_eq!(encode_utf7("Gelöschte Elemente"), "Gel&APY-schte Elemente"); + // Outside the basic plane: a surrogate pair. + assert_eq!(decode_utf7(&encode_utf7("📬 Post")), "📬 Post"); + assert_eq!(encode_utf7("📬"), "&2D3c7A-"); + // Control characters are encoded too. + assert_eq!(encode_utf7("a\tb"), "a&AAk-b"); + assert_eq!(encode_utf7(""), ""); + } + + #[test] + fn junk_is_kept_as_it_is() { + for junk in ["&", "a&b", "&&&", "&!!!-", "&A-", "&AAAAA-x", "R&D", "&2D0-", "&-&", "é&é-"] { + let decoded = decode_utf7(junk); + assert!(!decoded.is_empty(), "{junk}"); + } + assert_eq!(decode_utf7("R&D"), "R&D"); + assert_eq!(decode_utf7("&!!!-"), "&!!!-"); + // A lone surrogate is not text. + assert_eq!(decode_utf7("&2D0-"), "&2D0-"); + assert_eq!(decode_utf7("AT&T-Mobile"), "AT&T-Mobile"); + } + + proptest! { + #[test] + fn any_name_round_trips(name in "\\PC{0,40}") { + let encoded = encode_utf7(&name); + prop_assert!(encoded.bytes().all(|b| (0x20..=0x7E).contains(&b)), "{encoded}"); + prop_assert_eq!(decode_utf7(&encoded), name); + } + + #[test] + fn any_text_round_trips_with_control_characters(name in proptest::collection::vec(any::<char>(), 0..40)) { + let name: String = name.into_iter().collect(); + prop_assert_eq!(decode_utf7(&encode_utf7(&name)), name); + } + + #[test] + fn decoding_never_panics(name in "[&A-Za-z0-9+,\\-é ]{0,60}") { + let _ = decode_utf7(&name); + } + } +} diff --git a/crates/proto/src/lib.rs b/crates/proto/src/lib.rs new file mode 100644 index 000000000..08833beca --- /dev/null +++ b/crates/proto/src/lib.rs @@ -0,0 +1,229 @@ +// SPDX-FileCopyrightText: Craft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Mail protocols without sockets. +//! +//! [`smtp::Smtp`] and [`imap::Imap`] speak SMTP (RFC 5321, 3207, 4954) and IMAP4rev1 (RFC 3501, +//! 4315, 4959, 6154, 6851) over any `Read + Write` stream: a TLS socket on the desktop, a scripted +//! transcript in the tests. Everything a server sends is treated as hostile: lines, literals and +//! response counts are capped, and nothing here panics on junk. +//! +//! Passwords and access tokens never reach a log or an error text, even when a server echoes +//! them back. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod i18n; +pub mod imap; +mod line; +pub mod smtp; + +#[cfg(test)] +mod script; + +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use i18n::{Arg, Text}; + +pub(crate) use i18n::{for_trace, tidy}; + +/// Longest line a server may send. +pub const MAX_LINE: usize = 64 * 1024; +/// Largest counted block (an IMAP literal, so: the largest message) a server may send. +pub const MAX_LITERAL: usize = 64 * 1024 * 1024; +/// Longest user name and access token, together, that one sign-in may carry. +const MAX_XOAUTH2: usize = 32 * 1024; + +/// What went wrong. Each holds the reason as a [`Text`]: Craft's own words are a template +/// displayed in its language ([`said!`]), and what a server or the system said is kept as +/// it said it ([`Text::verbatim`]). The English ([`Display`](std::fmt::Display)) is what the CLI, MCP +/// and the log read, and it is the same either way. + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProtoError { + Io(Text), + Protocol(Text), + /// The server refused the command (IMAP NO/BAD, SMTP 4xx/5xx); the text is the server's. + Rejected(Text), + Auth(Text), +} + +impl ProtoError { + /// The underlying reason, without its error category prefix. + pub fn reason(&self) -> &Text { + match self { + Self::Io(why) | Self::Protocol(why) | Self::Rejected(why) | Self::Auth(why) => why, + } + } + + /// The error as the user is told it: what kind of trouble, and why. + pub fn said(&self) -> Text { + match self { + ProtoError::Io(why) => said!("connection problem: {reason}", reason = Arg::said(why.clone())), + ProtoError::Protocol(why) => said!("unexpected server response: {reason}", reason = Arg::said(why.clone())), + ProtoError::Rejected(why) => said!("the server said: {reason}", reason = Arg::said(why.clone())), + ProtoError::Auth(why) => said!("sign-in failed: {reason}", reason = Arg::said(why.clone())), + } + } +} + +impl std::fmt::Display for ProtoError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(&self.said(), f) + } +} + +impl std::error::Error for ProtoError {} + +/// Secrets: passwords and tokens, never shown in logs or errors. +#[derive(Default)] +pub(crate) struct Secrets(Vec<zeroize::Zeroizing<String>>); + +impl Secrets { + pub(crate) fn add(&mut self, secret: &str) { + if !secret.is_empty() && !self.0.iter().any(|s| s.as_str() == secret) { + self.0.push(zeroize::Zeroizing::new(secret.to_owned())); + // Longer overlapping secrets must be hidden before their prefixes. + self.0.sort_by_key(|s| std::cmp::Reverse(s.len())); + } + } + + pub(crate) fn hide(&self, text: &str) -> String { + self.0.iter().fold(text.to_owned(), |text, secret| text.replace(secret.as_str(), "***")) + } +} + +/// Build a bounded, base64-encoded SASL XOAUTH2 initial response. +pub(crate) fn xoauth2(user: &str, token: &str) -> Result<String, ProtoError> { + if user.is_empty() || token.is_empty() || user.chars().chain(token.chars()).any(char::is_control) { + return Err(ProtoError::Auth(said!("the user name or token has a character that can't be sent"))); + } + if user.len().saturating_add(token.len()) > MAX_XOAUTH2 { + return Err(ProtoError::Auth(said!("the user name or token is too long"))); + } + let plain = zeroize::Zeroizing::new(format!("user={user}\x01auth=Bearer {token}\x01\x01")); + Ok(STANDARD.encode(plain.as_bytes())) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + #[test] + fn secrets_redact_overlapping_values() { + let mut secrets = Secrets::default(); + secrets.add("token"); + secrets.add("token-long"); + assert_eq!(secrets.hide("token-long token"), "*** ***"); + } + + #[test] + fn xoauth2_rejects_injection_and_oversized_values() { + assert!(xoauth2("user\x01auth=Bearer injected", "token").is_err()); + assert!(xoauth2("user", &"x".repeat(MAX_XOAUTH2)).is_err()); + } + + #[test] + fn error_display() { + let err = ProtoError::Io(said!("connection problem")); + assert_eq!(err.to_string(), "connection problem: connection problem"); + assert_eq!(err.reason().to_string(), "connection problem"); + } + + #[test] + fn error_said() { + let err = ProtoError::Auth(said!("invalid password")); + assert_eq!(err.said().to_string(), "sign-in failed: invalid password"); + } + + #[test] + fn xoauth2_format() { + let result = xoauth2("user@example.com", "token123").unwrap(); + let result = String::from_utf8(STANDARD.decode(result).unwrap()).unwrap(); + assert!(result.contains("user=user@example.com")); + assert!(result.contains("auth=Bearer token123")); + } +} + +#[cfg(test)] +mod source_regression_tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + #[test] + fn the_wire_trace_keeps_keywords_and_no_address_name_or_text() { + // (Line, what the trace shows.) + for (line, _old_shown) in [ + ("A0001 OK ada@example.org authenticated (Success)\r\n", "A0001 OK … (39 bytes)"), + ("A0002 LOGIN ***", "A0002 LOGIN ***"), + ("MAIL FROM:<ada@example.org> SIZE=120", "MAIL FROM: … (26 bytes)"), + ("RCPT TO:<bob@example.org>", "RCPT TO: … (17 bytes)"), + ("550 5.1.1 <bob@example.org>: Recipient address rejected", "550 5.1.1 … (45 bytes)"), + ("250-mx.example.org at your service", "250- … (30 bytes)"), + ("250-AUTH LOGIN PLAIN XOAUTH2", "250-AUTH LOGIN PLAIN XOAUTH2"), + ("A0003 SELECT \"Letters from Grace\"", "A0003 SELECT … (20 bytes)"), + ("* LIST (\\HasNoChildren) \"/\" Grace", "* LIST … (26 bytes)"), + ("* 12 FETCH (UID 40 FLAGS (\\Seen) BODY[HEADER.FIELDS (SUBJECT)] \"Subject: Quarterly figures\")", "* 12 FETCH … (81 bytes)"), + ("* 3 EXISTS", "* 3 EXISTS"), + ("UID FETCH 1:40,42 (UID FLAGS)", "UID FETCH 1:40,42 … (11 bytes)"), + ("hello there", "(11 bytes)"), + ("", ""), + ] { + let traced = for_trace(line); + assert!(traced.len() <= line.len().saturating_add(32), "{line:?}"); + for private in ["ada", "bob", "Grace", "Quarterly", "mx.example"] { + assert!(!traced.contains(private), "{line:?}: {traced}"); + } + } + assert!(for_trace(&format!("A0001 OK {}", "X ".repeat(500))).len() < 160); + assert_eq!(for_trace("ünïcödé ä"), "(14 bytes)"); + } + + #[test] + fn uppercase_private_text_is_not_protocol_structure() { + assert_eq!(for_trace("550 CUSTOMER ALICE PAYMENT OVERDUE"), "550 … (30 bytes)"); + assert_eq!(for_trace("A0003 SELECT PRIVATE_MAILBOX"), "A0003 SELECT … (15 bytes)"); + assert_eq!(for_trace("250-PRIVATE_CUSTOMER_DOMAIN"), "250- … (23 bytes)"); + assert_eq!(for_trace("A0001 OK PRIVATE CUSTOMER"), "A0001 OK … (16 bytes)"); + } + + #[test] + fn secrets_are_hidden_longest_first() { + let mut s = Secrets::default(); + s.add("hunter2"); + s.add("hunter2-and-more"); + s.add(""); + assert_eq!(s.hide("no hunter2-and-more, no hunter2, nothing"), "no ***, no ***, nothing"); + assert_eq!(Secrets::default().hide("plain"), "plain"); + } + + #[test] + fn the_xoauth2_response_is_user_and_bearer_token_between_control_a() { + let decoded = |payload: String| STANDARD.decode(payload).unwrap(); + assert_eq!(decoded(xoauth2("ada@example.org", "tok.en-123").unwrap()), b"user=ada@example.org\x01auth=Bearer tok.en-123\x01\x01"); + // The example of the mechanism's description. + assert_eq!( + xoauth2("someuser@example.com", "ya29.vF9dft4qmTc2Nvb3RlckBhdHRhdmlzdGEuY29tCg").unwrap(), + "dXNlcj1zb21ldXNlckBleGFtcGxlLmNvbQFhdXRoPUJlYXJlciB5YTI5LnZGOWRmdDRxbVRjMk52YjNSbGNrQmhkSFJoZG1semRHRXVZMjl0Q2cBAQ==" + ); + assert_eq!(decoded(xoauth2("ädä", "t").unwrap()), "user=ädä\x01auth=Bearer t\x01\x01".as_bytes()); + // Nothing that could end the name, the token or the line early. + for (user, token) in [("ada\x01auth=Bearer other", "t"), ("ada", "t\x01"), ("ada\r\n", "t"), ("ada", "t\nQUIT"), ("a\0", "t"), ("ada", "\0")] + { + assert!(matches!(xoauth2(user, token), Err(ProtoError::Auth(_))), "{user:?} {token:?}"); + } + assert!(matches!(xoauth2("ada", ""), Err(ProtoError::Auth(_)))); + assert!(xoauth2("ada", &"t".repeat(MAX_XOAUTH2 - 3)).is_ok()); + let err = xoauth2("ada", &"t".repeat(MAX_XOAUTH2)).unwrap_err(); + assert!(matches!(&err, ProtoError::Auth(why) if why.to_string().len() < 100), "{err:?}"); + } + + #[test] + fn server_text_is_tidied() { + assert_eq!(tidy(" 5.7.8\tBad\r\n credentials \u{7}"), "5.7.8 Bad credentials"); + let long = tidy(&"é".repeat(1000)); + assert_eq!(long.chars().count(), 301); + assert!(long.ends_with('…')); + assert_eq!(tidy(""), ""); + } +} diff --git a/crates/proto/src/line.rs b/crates/proto/src/line.rs new file mode 100644 index 000000000..90d0937f1 --- /dev/null +++ b/crates/proto/src/line.rs @@ -0,0 +1,318 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! The bounded reader both protocols share: lines and counted blocks from a stream that may be hostile. + +use std::io::{ErrorKind, Read, Write}; + +use crate::said; +use crate::{MAX_LINE, MAX_LITERAL, ProtoError}; + +/// How much is asked of the stream in one read. +const CHUNK: usize = 16 * 1024; +/// Most bytes of one over-long untagged line read past ([`Wire::read_line_or_skip`]). +const MAX_SKIPPED: usize = 4 * 1024 * 1024; +/// Reads interrupted in a row before giving up. +const MAX_INTERRUPTS: u32 = 1_000; + +/// A stream with the bytes read ahead of what was asked for. +pub(crate) struct Wire<S> { + stream: S, + /// Bytes read from the stream and not handed out yet (from `start`). + buf: Vec<u8>, + start: usize, + // Bytes already searched for a newline in the current pending polling line. + poll_scanned: usize, +} + +fn closed() -> ProtoError { + ProtoError::Io(said!("the server closed the connection")) +} + +fn io_error(e: &std::io::Error) -> ProtoError { + match e.kind() { + ErrorKind::TimedOut | ErrorKind::WouldBlock => ProtoError::Io(said!("the server took too long to answer")), + ErrorKind::UnexpectedEof | ErrorKind::ConnectionAborted | ErrorKind::ConnectionReset | ErrorKind::BrokenPipe => closed(), + // The system's own words, as it said them. + _ => ProtoError::Io(crate::tidy(&e.to_string()).into()), + } +} + +impl<S> Wire<S> { + pub(crate) fn new(stream: S) -> Self { + Wire { stream, buf: Vec::new(), start: 0, poll_scanned: 0 } + } + + /// Whether the server sent more than has been read so far. + pub(crate) fn has_pending(&self) -> bool { + self.start < self.buf.len() + } + + pub(crate) fn into_inner(self) -> S { + self.stream + } + + /// The stream itself, for its owner to set up (what a socket waits for, say). Reading from + /// it or writing to it here would take the session apart. + pub(crate) fn get_mut(&mut self) -> &mut S { + &mut self.stream + } +} + +impl<S: Read + Write> Wire<S> { + /// Read some more into the buffer; the end of the stream is an error. + fn fill(&mut self) -> Result<(), ProtoError> { + self.poll_scanned = 0; + if self.start > 0 { + self.buf.drain(..self.start.min(self.buf.len())); + self.start = 0; + } + let mut tmp = vec![0u8; CHUNK]; + let n = read_some(&mut self.stream, &mut tmp)?; + self.buf.extend_from_slice(tmp.get(..n).unwrap_or(&[])); + Ok(()) + } + + /// The next line without its line ending (CRLF, or a bare LF). + pub(crate) fn read_line(&mut self) -> Result<Vec<u8>, ProtoError> { + self.next_line(false)?.ok_or_else(too_long) + } + + /// The next line, or `None` for an untagged one (`* …`) longer than [`MAX_LINE`], which is + /// read past to its end (at most [`MAX_SKIPPED`] bytes of it) so that the session goes on. + /// Any other line that long is an error, as for [`Wire::read_line`]. + pub(crate) fn read_line_or_skip(&mut self) -> Result<Option<Vec<u8>>, ProtoError> { + self.next_line(true) + } + + fn next_line(&mut self, skip: bool) -> Result<Option<Vec<u8>>, ProtoError> { + self.poll_scanned = 0; + // How much of the pending bytes has been searched for a line feed already. + let mut scanned = 0usize; + // Bytes of an over-long line dropped so far, when one is being read past. + let mut skipped: Option<usize> = None; + loop { + let pending = self.buf.get(self.start..).unwrap_or(&[]); + if let Some(i) = pending.get(scanned..).and_then(|rest| rest.iter().position(|b| *b == b'\n')) { + let end = scanned.saturating_add(i); + let line = pending.get(..end).unwrap_or(&[]); + let line = line.strip_suffix(b"\r").unwrap_or(line); + let line = if skipped.is_some() { + None + } else if line.len() > MAX_LINE { + if !(skip && line.starts_with(b"* ")) { + return Err(too_long()); + } + None + } else { + Some(line.to_vec()) + }; + self.start = self.start.saturating_add(end).saturating_add(1); + return Ok(line); + } + scanned = pending.len(); + // The limit is on the line itself; a CR may still come on top. + if scanned > MAX_LINE + 1 { + let dropped = match skipped { + Some(n) => n, + None if skip && pending.starts_with(b"* ") => 0, + None => return Err(too_long()), + }; + let dropped = dropped.saturating_add(scanned); + if dropped > MAX_SKIPPED { + return Err(too_long()); + } + skipped = Some(dropped); + self.start = self.buf.len(); + scanned = 0; + } + // Each round reads at least one byte, so this ends at the line feed, the cap or the end of the stream. + self.fill()?; + } + } + + /// The next line after at most one underlying read; `None` for a partial line or when + /// the stream times out (IDLE waits like this, a second at a time, so that its owner can + /// look at the clock and at whether it was told to stop). Bytes of a line that came so far are + /// kept for the next call. A line over [`MAX_LINE`] is an error, as for [`Wire::read_line`]. + pub(crate) fn poll_line(&mut self) -> Result<Option<Vec<u8>>, ProtoError> { + let mut read_once = false; + loop { + let pending = self.buf.get(self.start..).unwrap_or(&[]); + let scanned = self.poll_scanned.min(pending.len()); + if let Some(offset) = pending.get(scanned..).unwrap_or(&[]).iter().position(|b| *b == b'\n') { + let end = scanned.saturating_add(offset); + let line = pending.get(..end).unwrap_or(&[]); + let line = line.strip_suffix(b"\r").unwrap_or(line); + if line.len() > MAX_LINE { + return Err(too_long()); + } + let line = line.to_vec(); + self.start = self.start.saturating_add(end).saturating_add(1); + self.poll_scanned = 0; + return Ok(Some(line)); + } + if pending.len() > MAX_LINE + 1 { + return Err(too_long()); + } + self.poll_scanned = pending.len(); + // One underlying read per poll lets the caller check cancellation even when + // a hostile peer trickles bytes without ever triggering the read timeout. + if read_once { + return Ok(None); + } + if self.start > 0 { + self.buf.drain(..self.start.min(self.buf.len())); + self.start = 0; + } + let mut tmp = vec![0u8; CHUNK]; + read_once = true; + match self.stream.read(&mut tmp) { + Ok(0) => return Err(closed()), + Ok(n) => self.buf.extend_from_slice(tmp.get(..n.min(tmp.len())).unwrap_or(&[])), + Err(e) if matches!(e.kind(), ErrorKind::TimedOut | ErrorKind::WouldBlock | ErrorKind::Interrupted) => return Ok(None), + Err(e) => return Err(io_error(&e)), + } + } + } + + /// Exactly `n` bytes (at most [`MAX_LITERAL`]). + pub(crate) fn read_block(&mut self, n: usize) -> Result<Vec<u8>, ProtoError> { + self.poll_scanned = 0; + if n > MAX_LITERAL { + return Err(ProtoError::Protocol(said!("the server sent {n} bytes in one piece, more than MailCraft accepts", n))); + } + // The size is the server's word: memory is taken as the bytes arrive. + let mut out = Vec::with_capacity(n.min(CHUNK)); + let pending = self.buf.get(self.start..).unwrap_or(&[]); + let take = pending.len().min(n); + out.extend_from_slice(pending.get(..take).unwrap_or(&[])); + self.start = self.start.saturating_add(take); + let mut tmp = vec![0u8; CHUNK]; + while out.len() < n { + let want = (n - out.len()).min(tmp.len()); + let got = read_some(&mut self.stream, tmp.get_mut(..want).unwrap_or(&mut []))?; + out.extend_from_slice(tmp.get(..got.min(want)).unwrap_or(&[])); + } + Ok(out) + } + + pub(crate) fn write(&mut self, mut bytes: &[u8]) -> Result<(), ProtoError> { + // Not `write_all`: that retries an interrupted write for ever. + let mut interrupts = 0; + while !bytes.is_empty() { + match self.stream.write(bytes) { + Ok(0) => return Err(closed()), + Ok(n) => bytes = bytes.get(n..).unwrap_or(&[]), + Err(e) if e.kind() == ErrorKind::Interrupted && interrupts < MAX_INTERRUPTS => interrupts += 1, + Err(e) => return Err(io_error(&e)), + } + } + Ok(()) + } + + pub(crate) fn flush(&mut self) -> Result<(), ProtoError> { + self.stream.flush().map_err(|e| io_error(&e)) + } +} + +fn too_long() -> ProtoError { + ProtoError::Protocol(said!("the server sent a line longer than {kb} KB", kb = MAX_LINE / 1024)) +} + +/// One read of at least one byte; the end of the stream is an error. +fn read_some<S: Read>(stream: &mut S, buf: &mut [u8]) -> Result<usize, ProtoError> { + let mut interrupts = 0; + loop { + match stream.read(buf) { + Ok(0) => return Err(closed()), + // A stream that claims more than the buffer holds is lying. + Ok(n) => return Ok(n.min(buf.len())), + Err(e) if e.kind() == ErrorKind::Interrupted && interrupts < MAX_INTERRUPTS => interrupts += 1, + Err(e) => return Err(io_error(&e)), + } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + use crate::script::{Broken, Script}; + + #[test] + fn polling_reads_once_and_retains_linear_scan_progress() { + struct ByteAtATime { + bytes: std::io::Cursor<Vec<u8>>, + reads: usize, + } + impl Read for ByteAtATime { + fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> { + self.reads += 1; + self.bytes.read(&mut out[..1]) + } + } + impl Write for ByteAtATime { + fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut wire = Wire::new(ByteAtATime { bytes: std::io::Cursor::new(b"abc\n".to_vec()), reads: 0 }); + for scanned in 1..=3 { + assert_eq!(wire.poll_line().unwrap(), None); + assert_eq!(wire.poll_scanned, scanned); + assert_eq!(wire.get_mut().reads, scanned); + } + assert_eq!(wire.poll_line().unwrap(), Some(b"abc".to_vec())); + assert_eq!(wire.get_mut().reads, 4); + assert_eq!(wire.poll_scanned, 0); + } + + #[test] + fn lines_and_blocks_arrive_in_pieces() { + let mut s = Script::new("first\r\nsecond\nab\r\ncd\r\nlast\r\n"); + let mut w = Wire::new(&mut s); + assert_eq!(w.read_line().unwrap(), b"first"); + assert_eq!(w.read_line().unwrap(), b"second"); + assert_eq!(w.read_block(6).unwrap(), b"ab\r\ncd"); + assert_eq!(w.read_block(0).unwrap(), b""); + assert_eq!(w.read_line().unwrap(), b""); + assert_eq!(w.read_line().unwrap(), b"last"); + assert!(!w.has_pending()); + } + + #[test] + fn the_end_of_the_stream_is_an_error() { + let mut s = Script::new("no line ending"); + let mut w = Wire::new(&mut s); + assert_eq!(w.read_line(), Err(ProtoError::Io(said!("the server closed the connection")))); + let mut s = Script::new("short"); + assert!(matches!(Wire::new(&mut s).read_block(10), Err(ProtoError::Io(_)))); + } + + #[test] + fn long_lines_and_large_blocks_are_refused() { + let mut s = Script::whole(vec![b'x'; MAX_LINE + CHUNK * 2]); + assert!(matches!(Wire::new(&mut s).read_line(), Err(ProtoError::Protocol(_)))); + // A line of exactly the limit is fine. + let mut ok = vec![b'x'; MAX_LINE]; + ok.extend_from_slice(b"\r\n"); + let mut s = Script::whole(ok); + assert_eq!(Wire::new(&mut s).read_line().unwrap().len(), MAX_LINE); + // The claim alone is refused: nothing is read or allocated. + let mut s = Script::new(""); + assert!(matches!(Wire::new(&mut s).read_block(MAX_LITERAL + 1), Err(ProtoError::Protocol(_)))); + } + + #[test] + fn stream_errors_become_connection_problems() { + let mut w = Wire::new(Broken(ErrorKind::TimedOut)); + assert_eq!(w.read_line(), Err(ProtoError::Io(said!("the server took too long to answer")))); + assert!(matches!(w.write(b"x"), Err(ProtoError::Io(_)))); + // A stream that is interrupted for ever hangs neither the reader nor the writer. + assert!(matches!(Wire::new(Broken(ErrorKind::Interrupted)).read_line(), Err(ProtoError::Io(_)))); + assert!(matches!(Wire::new(Broken(ErrorKind::Interrupted)).write(b"x"), Err(ProtoError::Io(_)))); + } +} diff --git a/crates/proto/src/script.rs b/crates/proto/src/script.rs new file mode 100644 index 000000000..a3d952efb --- /dev/null +++ b/crates/proto/src/script.rs @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Test streams: a scripted server, and a stream that only fails. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use std::io::{Error, ErrorKind, Read, Write}; + +/// A canned server: reads hand out what the server "says" (a few bytes at a time, so every +/// boundary gets split somewhere), writes are kept for the test to look at. +#[derive(Debug)] +pub(crate) struct Script { + input: Vec<u8>, + pos: usize, + step: usize, + trickle: bool, + pub(crate) written: Vec<u8>, +} + +impl Script { + /// Hands the bytes out 1–7 at a time. + pub(crate) fn new(server: impl AsRef<[u8]>) -> Script { + Script { input: server.as_ref().to_vec(), pos: 0, step: 0, trickle: true, written: Vec::new() } + } + + /// Hands out as much as each read asks for. + pub(crate) fn whole(server: impl AsRef<[u8]>) -> Script { + Script { trickle: false, ..Script::new(server) } + } + + /// What the client wrote, as text. + pub(crate) fn sent(&self) -> String { + String::from_utf8_lossy(&self.written).into_owned() + } + + /// Whether the client read everything the script had. + pub(crate) fn finished(&self) -> bool { + self.pos >= self.input.len() + } +} + +impl Read for Script { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { + let left = &self.input[self.pos.min(self.input.len())..]; + let mut n = left.len().min(buf.len()); + if self.trickle { + n = n.min([3, 1, 7, 2, 5, 4, 6][self.step % 7]); + self.step += 1; + } + buf[..n].copy_from_slice(&left[..n]); + self.pos += n; + Ok(n) + } +} + +impl Write for Script { + fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { + self.written.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// A stream whose every read and write fails. +#[derive(Debug)] +pub(crate) struct Broken(pub(crate) ErrorKind); + +impl Read for Broken { + fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> { + Err(Error::from(self.0)) + } +} + +impl Write for Broken { + fn write(&mut self, _: &[u8]) -> std::io::Result<usize> { + Err(Error::from(self.0)) + } + + fn flush(&mut self) -> std::io::Result<()> { + Err(Error::from(self.0)) + } +} diff --git a/crates/proto/src/smtp/mod.rs b/crates/proto/src/smtp/mod.rs new file mode 100644 index 000000000..cbf5034c4 --- /dev/null +++ b/crates/proto/src/smtp/mod.rs @@ -0,0 +1,419 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! An SMTP client (RFC 5321) with STARTTLS (RFC 3207) and AUTH PLAIN / LOGIN / XOAUTH2 (RFC 4954). + +use std::io::{Read, Write}; + +use base64::{Engine as _, engine::general_purpose::STANDARD}; + +use crate::i18n::{Arg, Text}; +use crate::line::Wire; +use crate::said; +use crate::{ProtoError, Secrets, for_trace, tidy, xoauth2}; + +/// Most lines one reply may have. +const MAX_REPLY_LINES: usize = 256; +/// Longest command line without its line ending (RFC 5321 §4.5.3.1.4). +const MAX_COMMAND: usize = 510; +/// Longest address (RFC 5321 §4.5.3.1.3 allows 256; some servers take more). +const MAX_ADDRESS: usize = 320; +/// Most recipients one message may have. +const MAX_RECIPIENTS: usize = 10_000; + +/// An SMTP session on a stream. +pub struct Smtp<S> { + wire: Wire<S>, + ext: Extensions, + secrets: Secrets, +} + +/// What the server offered in its answer to EHLO. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Extensions { + pub starttls: bool, + pub auth_plain: bool, + pub auth_login: bool, + /// The server takes an OAuth access token instead of a password (SASL XOAUTH2). + pub auth_xoauth2: bool, + /// The largest message the server takes; `Some(0)` when it names no limit. + pub size: Option<u64>, + pub eight_bit_mime: bool, +} + +/// Neither the stream nor anything secret is shown. +impl<S> std::fmt::Debug for Smtp<S> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Smtp").field("extensions", &self.ext).finish_non_exhaustive() + } +} + +/// One reply: `250-first`, `250 last`. +struct Reply { + code: u16, + lines: Vec<String>, +} + +impl Reply { + fn class(&self) -> u16 { + self.code / 100 + } + + /// `550 5.1.1 No such user`, as the server wrote it. + fn text(&self) -> String { + format!("{} {}", self.code, self.lines.join(" ")) + } +} + +impl<S: Read + Write> Smtp<S> { + /// Read the 220 greeting. + pub fn connect(stream: S) -> Result<Self, ProtoError> { + let mut smtp = Self::resume(stream); + let greeting = smtp.reply()?; + if greeting.code == 220 { Ok(smtp) } else { Err(smtp.refused(&greeting)) } + } + + /// Continue on a stream that already greeted (after the caller wrapped it in TLS). + pub fn resume(stream: S) -> Self { + Smtp { wire: Wire::new(stream), ext: Extensions::default(), secrets: Secrets::default() } + } + + /// What the last [`hello`](Self::hello) learned. + pub fn extensions(&self) -> &Extensions { + &self.ext + } + + /// The stream the session runs on, for its owner to set up between commands (how long a + /// socket waits, say). Reading from it or writing to it would take the session apart. + pub fn get_mut(&mut self) -> &mut S { + self.wire.get_mut() + } + + /// EHLO (falling back to HELO); remembers and returns what the server offers. + pub fn hello(&mut self, client_name: &str) -> Result<Extensions, ProtoError> { + // A name that could break the command line is not sent. + let name = if is_word(client_name) { client_name } else { "localhost" }; + let reply = self.command(&format!("EHLO {name}"))?; + if reply.code == 250 { + self.ext = extensions(&reply.lines); + return Ok(self.ext.clone()); + } + if reply.class() != 5 { + return Err(self.refused(&reply)); + } + // A server from before 1995 (or one hiding its extensions). + let reply = self.command(&format!("HELO {name}"))?; + if reply.code != 250 { + return Err(self.refused(&reply)); + } + self.ext = Extensions::default(); + Ok(self.ext.clone()) + } + + /// Send STARTTLS and hand the stream back for the caller to wrap; call `resume` + `hello` afterwards. + pub fn starttls(mut self) -> Result<S, ProtoError> { + let reply = self.command("STARTTLS")?; + if reply.code != 220 { + return Err(self.refused(&reply)); + } + // Anything after the go-ahead was slipped in before encryption started (RFC 3207 §6). + if self.wire.has_pending() { + return Err(ProtoError::Protocol(said!("the server sent data before the secure connection started"))); + } + Ok(self.wire.into_inner()) + } + + /// AUTH PLAIN when offered, else AUTH LOGIN. 535 and friends → `ProtoError::Auth`. + pub fn auth(&mut self, user: &str, password: &str) -> Result<(), ProtoError> { + if user.contains('\0') || password.contains('\0') { + return Err(ProtoError::Auth(said!("the user name or password has a character that can't be sent"))); + } + self.secrets.add(password); + if self.ext.auth_plain { + let payload = STANDARD.encode(format!("\0{user}\0{password}")); + self.secrets.add(&payload); + let line = format!("AUTH PLAIN {payload}"); + let reply = if line.len() <= MAX_COMMAND { + self.secret_command(&line, "AUTH PLAIN ***")? + } else { + // Too long for one line: wait for the server to ask (RFC 4954 §4). + let ask = self.command("AUTH PLAIN")?; + if ask.code != 334 { + return Err(self.sign_in_failed(&ask)); + } + self.secret_command(&payload, "***")? + }; + return self.signed_in(&reply); + } + if self.ext.auth_login { + let ask = self.command("AUTH LOGIN")?; + if ask.code != 334 { + return Err(self.sign_in_failed(&ask)); + } + let ask = self.secret_command(&STANDARD.encode(user), "***")?; + if ask.code != 334 { + return Err(self.sign_in_failed(&ask)); + } + let encoded = STANDARD.encode(password); + self.secrets.add(&encoded); + let reply = self.secret_command(&encoded, "***")?; + return self.signed_in(&reply); + } + Err(ProtoError::Auth(said!("the server offers no way to sign in with a password"))) + } + + /// AUTH XOAUTH2: an OAuth access token in place of a password. A server that doesn't offer + /// it isn't shown the token. 535 and friends → `ProtoError::Auth`. + pub fn auth_xoauth2(&mut self, user: &str, token: &str) -> Result<(), ProtoError> { + let payload = xoauth2(user, token)?; + if !self.ext.auth_xoauth2 { + return Err(ProtoError::Auth(said!("the server offers no way to sign in with an access token"))); + } + self.secrets.add(token); + self.secrets.add(&payload); + let line = format!("AUTH XOAUTH2 {payload}"); + let reply = if line.len() <= MAX_COMMAND { + self.secret_command(&line, "AUTH XOAUTH2 ***")? + } else { + // Too long for one line, as tokens mostly are: wait for the server to ask (RFC 4954 §4). + let ask = self.command("AUTH XOAUTH2")?; + if ask.code != 334 { + return Err(self.sign_in_failed(&ask)); + } + self.secret_command(&payload, "***")? + }; + match reply.code { + 235 => Ok(()), + 334 => { + // A refusal comes in two parts: the reasons (JSON in base64), and, once an empty + // line has acknowledged them, the verdict. + let verdict = self.command("")?; + match verdict.code { + 235 => Ok(()), + 334 => { + let _ = self.command("*"); + Err(ProtoError::Auth(said!("the server asked for more than a user name and access token"))) + } + _ => Err(self.sign_in_failed(&verdict)), + } + } + _ => Err(self.sign_in_failed(&reply)), + } + } + + /// MAIL FROM, RCPT TO (every recipient must be accepted), DATA with CRLF normalisation and dot-stuffing. + pub fn send(&mut self, from: &str, recipients: &[&str], message: &[u8]) -> Result<(), ProtoError> { + // Nothing is sent unless every address is safe to put on a command line. + if !from.is_empty() && !is_address(from) { + return Err(bad_address(from)); + } + if recipients.is_empty() { + return Err(ProtoError::Protocol(said!("the message has no recipients"))); + } + if recipients.len() > MAX_RECIPIENTS { + return Err(ProtoError::Protocol(said!("the message has too many recipients"))); + } + if let Some(bad) = recipients.iter().find(|r| !is_address(r)) { + return Err(bad_address(bad)); + } + let (data, size) = data_block(message); + let mut mail = format!("MAIL FROM:<{from}>"); + if self.ext.size.is_some() { + mail.push_str(&format!(" SIZE={size}")); + } + if self.ext.eight_bit_mime && !message.is_ascii() { + mail.push_str(" BODY=8BITMIME"); + } + let reply = self.command(&mail)?; + if reply.class() != 2 { + return Err(self.refused(&reply)); + } + for rcpt in recipients { + let reply = self.command(&format!("RCPT TO:<{rcpt}>"))?; + if reply.class() != 2 { + let refused = match self.refused(&reply) { + // (The address, then what the server said of it: no words of MailCraft's to say.) + ProtoError::Rejected(text) => { + ProtoError::Rejected(Text::new("{rcpt}: {text}", vec![("rcpt", Arg::Plain(rcpt.to_string())), ("text", Arg::said(text))])) + } + other => other, + }; + return Err(self.give_up(refused)); + } + } + let reply = self.command("DATA")?; + if reply.code != 354 { + let refused = self.refused(&reply); + return Err(self.give_up(refused)); + } + log::trace!("C: ({size} bytes)"); + self.wire.write(&data)?; + self.wire.flush()?; + let reply = self.reply()?; + if reply.class() != 2 { + return Err(self.refused(&reply)); + } + Ok(()) + } + + /// QUIT. A server that hangs up without answering has quit all the same. + pub fn quit(mut self) -> Result<(), ProtoError> { + match self.command("QUIT") { + Ok(reply) if reply.class() == 2 => Ok(()), + Ok(reply) => Err(self.refused(&reply)), + // A server that hangs up instead of saying goodbye has quit all the same. + Err(ProtoError::Io(_)) => Ok(()), + Err(e) => Err(e), + } + } + + /// Forget the message being composed, so the session can go on; hands the error back. + fn give_up(&mut self, error: ProtoError) -> ProtoError { + let _ = self.command("RSET"); + error + } + + fn command(&mut self, line: &str) -> Result<Reply, ProtoError> { + self.secret_command(line, line) + } + + /// Send `line`; the log gets `shown` instead. + fn secret_command(&mut self, line: &str, shown: &str) -> Result<Reply, ProtoError> { + log::trace!("C: {}", for_trace(&self.secrets.hide(shown))); + let mut out = Vec::with_capacity(line.len() + 2); + out.extend_from_slice(line.as_bytes()); + out.extend_from_slice(b"\r\n"); + self.wire.write(&out)?; + self.wire.flush()?; + self.reply() + } + + fn reply(&mut self) -> Result<Reply, ProtoError> { + let mut reply = Reply { code: 0, lines: Vec::new() }; + for n in 0..MAX_REPLY_LINES { + let raw = self.wire.read_line()?; + let line = String::from_utf8_lossy(&raw); + log::trace!("S: {}", for_trace(&self.secrets.hide(&line))); + // Three digits, then `-` (more lines follow), a space or nothing (the last line). + let code = line.get(..3).filter(|d| d.bytes().all(|b| b.is_ascii_digit())).and_then(|d| d.parse::<u16>().ok()); + let rest = line.get(3..).unwrap_or(""); + let more = match (code, rest.chars().next()) { + (Some(code), Some('-')) if n == 0 || code == reply.code => true, + (Some(code), Some(' ') | None) if n == 0 || code == reply.code => false, + _ => return Err(ProtoError::Protocol(said!("\"{line}\" is not an SMTP reply", line = tidy(&self.secrets.hide(&line))))), + }; + reply.code = code.unwrap_or(0); + reply.lines.push(rest.get(1..).unwrap_or("").to_string()); + if !more { + return Ok(reply); + } + } + Err(ProtoError::Protocol(said!("the server's reply has too many lines"))) + } + + /// The error for a reply that isn't the one hoped for. + fn refused(&self, reply: &Reply) -> ProtoError { + // Hidden before it is shortened: a secret cut in half would no longer be recognised. + let text = tidy(&self.secrets.hide(&reply.text())); + if matches!(reply.class(), 4 | 5) { ProtoError::Rejected(text.into()) } else { ProtoError::Protocol(text.into()) } + } + + fn sign_in_failed(&mut self, reply: &Reply) -> ProtoError { + match self.refused(reply) { + ProtoError::Rejected(text) => ProtoError::Auth(text), + other => other, + } + } + + fn signed_in(&mut self, reply: &Reply) -> Result<(), ProtoError> { + match reply.code { + 235 => Ok(()), + 334 => { + // Another question we have no answer to: cancel the exchange (RFC 4954 §4). + let _ = self.command("*"); + Err(ProtoError::Auth(said!("the server asked for more than a user name and password"))) + } + _ => Err(self.sign_in_failed(reply)), + } + } +} + +/// The extensions named in an EHLO reply (its first line is the server's name). +fn extensions(lines: &[String]) -> Extensions { + let mut ext = Extensions::default(); + for line in lines.iter().skip(1) { + let upper = line.to_ascii_uppercase(); + // `AUTH=PLAIN LOGIN` is how some old servers spell `AUTH PLAIN LOGIN`. + let mut words = upper.split([' ', '\t', '=']).filter(|w| !w.is_empty()); + match words.next() { + Some("STARTTLS") => ext.starttls = true, + Some("8BITMIME") => ext.eight_bit_mime = true, + Some("SIZE") => ext.size = Some(words.next().and_then(|n| n.parse().ok()).unwrap_or(0)), + Some("AUTH") => { + for mechanism in words { + match mechanism { + "PLAIN" => ext.auth_plain = true, + "LOGIN" => ext.auth_login = true, + "XOAUTH2" => ext.auth_xoauth2 = true, + _ => {} + } + } + } + _ => {} + } + } + ext +} + +/// Visible ASCII without spaces: safe as one word of a command line. +fn is_word(s: &str) -> bool { + !s.is_empty() && s.len() <= 255 && s.bytes().all(|b| b.is_ascii_graphic()) +} + +/// An address that can go between `<` and `>` as it is. +fn is_address(s: &str) -> bool { + is_word(s) && s.len() <= MAX_ADDRESS && !s.contains(['<', '>']) +} + +fn bad_address(address: &str) -> ProtoError { + ProtoError::Protocol(said!("\"{address}\" can't be used as an address", address = tidy(address))) +} + +/// The message as DATA wants it: every line ending CRLF, a leading dot doubled, the closing +/// `.` line added. Also returns the size without the added dots and closing line (RFC 1870). +fn data_block(message: &[u8]) -> (Vec<u8>, usize) { + let mut out = Vec::with_capacity(message.len().saturating_add(message.len() / 32).saturating_add(8)); + let mut dots = 0usize; + let mut line_start = true; + let mut bytes = message.iter().copied().peekable(); + while let Some(b) = bytes.next() { + match b { + b'\r' => { + bytes.next_if_eq(&b'\n'); + out.extend_from_slice(b"\r\n"); + line_start = true; + } + b'\n' => { + out.extend_from_slice(b"\r\n"); + line_start = true; + } + b'.' if line_start => { + out.extend_from_slice(b".."); + dots += 1; + line_start = false; + } + _ => { + out.push(b); + line_start = false; + } + } + } + if !line_start { + out.extend_from_slice(b"\r\n"); + } + let size = out.len().saturating_sub(dots); + out.extend_from_slice(b".\r\n"); + (out, size) +} + +#[cfg(test)] +mod tests; diff --git a/crates/proto/src/smtp/tests.rs b/crates/proto/src/smtp/tests.rs new file mode 100644 index 000000000..37777d5e8 --- /dev/null +++ b/crates/proto/src/smtp/tests.rs @@ -0,0 +1,455 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use std::io::ErrorKind; + +use proptest::prelude::*; + +use super::*; +use crate::script::{Broken, Script}; + +const EHLO: &str = + "250-mail.example.org greets you\r\n250-SIZE 35882577\r\n250-8BITMIME\r\n250-STARTTLS\r\n250-AUTH LOGIN PLAIN XOAUTH2\r\n250 HELP\r\n"; + +fn rejected(r: Result<(), ProtoError>) -> String { + match r { + Err(ProtoError::Rejected(text)) => text.to_string(), + other => panic!("expected a rejection, got {other:?}"), + } +} + +#[test] +fn a_whole_session() { + let mut s = Script::new(format!( + "220-mail.example.org ESMTP\r\n220 ready\r\n{EHLO}235 2.7.0 Accepted\r\n250 OK\r\n250 OK\r\n251 will forward\r\n354 go ahead\r\n250 queued as 1\r\n221 bye\r\n" + )); + let mut smtp = Smtp::connect(&mut s).unwrap(); + let ext = smtp.hello("[127.0.0.1]").unwrap(); + assert_eq!( + ext, + Extensions { starttls: true, auth_plain: true, auth_login: true, auth_xoauth2: true, size: Some(35_882_577), eight_bit_mime: true } + ); + assert_eq!(smtp.extensions(), &ext); + smtp.auth("ada@example.org", "hunter2").unwrap(); + smtp.send("ada@example.org", &["bob@example.org", "carol@example.org"], b"Subject: Hi\r\n\r\nHello.\r\n").unwrap(); + smtp.quit().unwrap(); + assert!(s.finished()); + assert_eq!( + s.sent(), + "EHLO [127.0.0.1]\r\n\ + AUTH PLAIN AGFkYUBleGFtcGxlLm9yZwBodW50ZXIy\r\n\ + MAIL FROM:<ada@example.org> SIZE=23\r\n\ + RCPT TO:<bob@example.org>\r\n\ + RCPT TO:<carol@example.org>\r\n\ + DATA\r\n\ + Subject: Hi\r\n\r\nHello.\r\n.\r\n\ + QUIT\r\n" + ); +} + +#[test] +fn the_plain_payload_is_nul_user_nul_password() { + let mut s = Script::new("250-x\r\n250 AUTH PLAIN\r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + smtp.auth("grace", "pässword \"1\"").unwrap(); + let sent = s.sent(); + let payload = sent.lines().nth(1).unwrap().strip_prefix("AUTH PLAIN ").unwrap(); + assert_eq!(STANDARD.decode(payload).unwrap(), "\0grace\0pässword \"1\"".as_bytes()); +} + +#[test] +fn a_long_plain_payload_waits_for_the_server_to_ask() { + let mut s = Script::new("250-x\r\n250 AUTH PLAIN\r\n334 \r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + let password = "p".repeat(600); + smtp.auth("grace", &password).unwrap(); + let sent = s.sent(); + let lines: Vec<&str> = sent.lines().collect(); + assert_eq!(lines[1], "AUTH PLAIN"); + assert_eq!(STANDARD.decode(lines[2]).unwrap(), format!("\0grace\0{password}").as_bytes()); +} + +#[test] +fn login_is_used_when_plain_is_not_offered() { + let mut s = Script::new("250-x\r\n250 AUTH=LOGIN CRAM-MD5\r\n334 VXNlcm5hbWU6\r\n334 UGFzc3dvcmQ6\r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + let ext = smtp.hello("localhost").unwrap(); + assert!(ext.auth_login && !ext.auth_plain); + smtp.auth("ada", "hunter2").unwrap(); + assert_eq!(s.sent(), "EHLO localhost\r\nAUTH LOGIN\r\nYWRh\r\naHVudGVyMg==\r\n"); +} + +#[test] +fn a_wrong_password_is_an_auth_error_that_never_shows_it() { + // A careless server repeats what it was sent. + let echo = "535-5.7.8 no such password: hunter2\r\n535 5.7.8 (AGFkYQBodW50ZXIy)\r\n"; + let mut s = Script::new(format!("250-x\r\n250 AUTH PLAIN\r\n{echo}")); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + let err = smtp.auth("ada", "hunter2").unwrap_err(); + assert_eq!(err, ProtoError::Auth("535 5.7.8 no such password: *** 5.7.8 (***)".into())); + assert!(!format!("{err} {err:?} {smtp:?}").contains("hunter2")); + + // The same over LOGIN, where the password travels alone. + let mut s = Script::new("250-x\r\n250 AUTH LOGIN\r\n334 VXNlcm5hbWU6\r\n334 UGFzc3dvcmQ6\r\n535 bad aHVudGVyMg== / hunter2\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert_eq!(smtp.auth("ada", "hunter2"), Err(ProtoError::Auth("535 bad *** / ***".into()))); +} + +#[test] +fn sign_in_needs_a_method_and_sendable_text() { + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert!(matches!(smtp.auth("ada", "hunter2"), Err(ProtoError::Auth(_)))); + assert!(matches!(smtp.auth("ada", "hun\0ter2"), Err(ProtoError::Auth(_)))); + // Neither attempt put anything on the wire. + assert_eq!(s.sent(), "EHLO localhost\r\n"); +} + +/// What an XOAUTH2 response says under its base64. +fn bearer(payload: &str) -> String { + String::from_utf8(STANDARD.decode(payload).unwrap()).unwrap() +} + +#[test] +fn a_token_signs_in_with_xoauth2() { + let mut s = Script::new("250-x\r\n250 AUTH LOGIN XOAUTH2\r\n235 2.7.0 Authentication successful\r\n"); + let mut smtp = Smtp::resume(&mut s); + assert!(smtp.hello("localhost").unwrap().auth_xoauth2); + smtp.auth_xoauth2("ada@example.org", "tok.en-123").unwrap(); + assert!(s.finished()); + let sent = s.sent(); + let lines: Vec<&str> = sent.lines().collect(); + assert_eq!(lines.len(), 2); + assert_eq!(bearer(lines[1].strip_prefix("AUTH XOAUTH2 ").unwrap()), "user=ada@example.org\x01auth=Bearer tok.en-123\x01\x01"); +} + +#[test] +fn a_long_token_waits_for_the_server_to_ask() { + // Real tokens run to a couple of thousand characters. + let token = "t".repeat(2_000); + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n334 \r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + smtp.auth_xoauth2("ada@example.org", &token).unwrap(); + let sent = s.sent(); + let lines: Vec<&str> = sent.lines().collect(); + assert_eq!(lines[1], "AUTH XOAUTH2"); + assert_eq!(bearer(lines[2]), format!("user=ada@example.org\x01auth=Bearer {token}\x01\x01")); + + // The longest that still fits goes in one line. + let token = "t".repeat(349); + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + smtp.auth_xoauth2("ada", &token).unwrap(); + let sent = s.sent(); + assert_eq!((sent.lines().count(), sent.lines().nth(1).unwrap().len()), (2, MAX_COMMAND - 1)); + + // A server that won't ask is not shown the token. + let token = "t".repeat(2_000); + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n504 5.5.4 not that way\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert_eq!(smtp.auth_xoauth2("ada", &token), Err(ProtoError::Auth("504 5.5.4 not that way".into()))); + assert_eq!(s.sent(), "EHLO localhost\r\nAUTH XOAUTH2\r\n"); +} + +#[test] +fn a_refused_token_is_an_auth_error_that_never_shows_it() { + let payload = xoauth2("ada", "tok.en-123").unwrap(); + let reasons = STANDARD.encode(r#"{"status":"401","schemes":"bearer","scope":"https://mail.example.org/"}"#); + // The reasons come first and the verdict after an empty line; a careless server repeats what it was sent. + let mut s = Script::new(format!("250-x\r\n250 AUTH XOAUTH2\r\n334 {reasons}\r\n535-5.7.3 no good: tok.en-123\r\n535 5.7.3 ({payload})\r\n")); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + let err = smtp.auth_xoauth2("ada", "tok.en-123").unwrap_err(); + assert_eq!(err, ProtoError::Auth("535 5.7.3 no good: *** 5.7.3 (***)".into())); + assert!(!format!("{err} {err:?} {smtp:?}").contains("tok.en-123")); + assert_eq!(s.sent(), format!("EHLO localhost\r\nAUTH XOAUTH2 {payload}\r\n\r\n")); + assert!(s.finished()); + + // The same when the token went on a line of its own. + let token = "t".repeat(2_000); + let mut s = Script::new(format!("250-x\r\n250 AUTH XOAUTH2\r\n334 \r\n334 {reasons}\r\n535 5.7.3 Authentication unsuccessful\r\n")); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert_eq!(smtp.auth_xoauth2("ada", &token), Err(ProtoError::Auth("535 5.7.3 Authentication unsuccessful".into()))); + assert_eq!(s.sent(), format!("EHLO localhost\r\nAUTH XOAUTH2\r\n{}\r\n\r\n", xoauth2("ada", &token).unwrap())); + assert!(s.finished()); + + // Refused in one word, without reasons. + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n535 5.7.3 Authentication unsuccessful\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert_eq!(smtp.auth_xoauth2("ada", "tok.en-123"), Err(ProtoError::Auth("535 5.7.3 Authentication unsuccessful".into()))); + assert_eq!(s.sent(), format!("EHLO localhost\r\nAUTH XOAUTH2 {payload}\r\n")); + + // A question after the reasons has no answer: the exchange is cancelled. + let mut s = Script::new(format!("250-x\r\n250 AUTH XOAUTH2\r\n334 {reasons}\r\n334 more?\r\n501 cancelled\r\n")); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert!(matches!(smtp.auth_xoauth2("ada", "tok.en-123"), Err(ProtoError::Auth(_)))); + assert!(s.sent().ends_with("\r\n\r\n*\r\n")); +} + +#[test] +fn a_token_echoed_in_a_long_reply_is_hidden_whole() { + // The reply is shortened for the error text: not before the token is out of it. + let token = format!("head.{}.tail", "x".repeat(2_000)); + let mut s = Script::new(format!("250-x\r\n250 AUTH XOAUTH2\r\n334 \r\n535 5.7.3 {} bad token {token}\r\n", "no ".repeat(80))); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + let err = smtp.auth_xoauth2("ada", &token).unwrap_err(); + let shown = format!("{err} {err:?}"); + assert!(matches!(err, ProtoError::Auth(_))); + assert!(!shown.contains("head.") && !shown.contains("xxxx"), "{shown}"); +} + +#[test] +fn a_token_needs_a_server_that_takes_one_and_sendable_text() { + let mut s = Script::new("250-x\r\n250 AUTH PLAIN LOGIN\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert_eq!(smtp.auth_xoauth2("ada", "tok.en-123"), Err(ProtoError::Auth(said!("the server offers no way to sign in with an access token")))); + assert_eq!(s.sent(), "EHLO localhost\r\n"); + + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + for (user, token) in + [("ada", ""), ("ada", "tok\r\nQUIT"), ("ada", "tok\x01"), ("ada\x01auth=Bearer x", "tok"), ("a\0da", "tok"), ("ada\n", "tok")] + { + assert!(matches!(smtp.auth_xoauth2(user, token), Err(ProtoError::Auth(_))), "{user:?} {token:?}"); + } + assert_eq!(s.sent(), "EHLO localhost\r\n"); +} + +#[test] +fn an_unexpected_second_question_cancels_the_sign_in() { + let mut s = Script::new("250-x\r\n250 AUTH PLAIN\r\n334 more?\r\n501 cancelled\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert!(matches!(smtp.auth("ada", "hunter2"), Err(ProtoError::Auth(_)))); + assert!(s.sent().ends_with("\r\n*\r\n")); +} + +#[test] +fn helo_is_the_fallback() { + let mut s = Script::new("220 old.example.org\r\n502 what?\r\n250 old.example.org\r\n"); + let mut smtp = Smtp::connect(&mut s).unwrap(); + assert_eq!(smtp.hello("localhost").unwrap(), Extensions::default()); + assert_eq!(s.sent(), "EHLO localhost\r\nHELO localhost\r\n"); + + // A server on its way out is not asked twice. + let mut s = Script::new("421 shutting down\r\n"); + assert_eq!(Smtp::resume(&mut s).hello("localhost"), Err(ProtoError::Rejected("421 shutting down".into()))); + assert_eq!(s.sent(), "EHLO localhost\r\n"); +} + +#[test] +fn a_client_name_that_could_break_the_line_is_replaced() { + for bad in ["", "two words", "evil\r\nMAIL FROM:<x>", "nön-ascii"] { + let mut s = Script::new("250 ok\r\n"); + Smtp::resume(&mut s).hello(bad).unwrap(); + assert_eq!(s.sent(), "EHLO localhost\r\n", "{bad:?}"); + } +} + +#[test] +fn extensions_are_read_whatever_their_case() { + let mut s = Script::new("250-x\r\n250-starttls\r\n250-Size\r\n250-auth plain\r\n250 8bitmime\r\n"); + let ext = Smtp::resume(&mut s).hello("localhost").unwrap(); + assert_eq!(ext, Extensions { starttls: true, auth_plain: true, auth_login: false, auth_xoauth2: false, size: Some(0), eight_bit_mime: true }); + let mut s = Script::new("250-x\r\n250 auth=login xoauth2 OAUTHBEARER\r\n"); + let ext = Smtp::resume(&mut s).hello("localhost").unwrap(); + assert_eq!(ext, Extensions { auth_login: true, auth_xoauth2: true, ..Default::default() }); +} + +#[test] +fn starttls_hands_the_stream_back() { + let mut s = Script::new("220 hi\r\n250-x\r\n250 STARTTLS\r\n220 go ahead\r\n"); + let mut smtp = Smtp::connect(&mut s).unwrap(); + assert!(smtp.hello("localhost").unwrap().starttls); + let stream = smtp.starttls().unwrap(); + assert_eq!(stream.sent(), "EHLO localhost\r\nSTARTTLS\r\n"); + + let mut s = Script::new("454 TLS not available\r\n"); + assert_eq!(Smtp::resume(&mut s).starttls().unwrap_err(), ProtoError::Rejected("454 TLS not available".into())); +} + +#[test] +fn text_slipped_in_before_tls_is_refused() { + // Both lines arrive in one read, as an attacker in the middle would send them. + let mut s = Script::whole("220 go ahead\r\n250 injected\r\n"); + assert!(matches!(Smtp::resume(&mut s).starttls(), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn data_is_normalised_and_dot_stuffed() { + let message = b"Subject: dots\n\n.leading\r\n..two\rbare CR\n.\nno dot. here\n\nlast line without an ending"; + let mut s = Script::new("250 ok\r\n250 ok\r\n354 go\r\n250 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.send("ada@example.org", &["bob@example.org"], message).unwrap(); + let sent = s.sent(); + let data = sent.split_once("DATA\r\n").unwrap().1; + assert_eq!(data, "Subject: dots\r\n\r\n..leading\r\n...two\r\nbare CR\r\n..\r\nno dot. here\r\n\r\nlast line without an ending\r\n.\r\n"); + // No SIZE or BODY parameter for a server that didn't offer them. + assert!(sent.starts_with("MAIL FROM:<ada@example.org>\r\n")); +} + +#[test] +fn data_blocks() { + assert_eq!(data_block(b""), (b".\r\n".to_vec(), 0)); + assert_eq!(data_block(b"a"), (b"a\r\n.\r\n".to_vec(), 3)); + assert_eq!(data_block(b"."), (b"..\r\n.\r\n".to_vec(), 3)); + assert_eq!(data_block(b"\r\r\n\n"), (b"\r\n\r\n\r\n.\r\n".to_vec(), 6)); + assert_eq!(data_block(b"a\r"), (b"a\r\n.\r\n".to_vec(), 3)); +} + +#[test] +fn eight_bit_mail_says_so_when_the_server_takes_it() { + let mut s = Script::new("250-x\r\n250 8BITMIME\r\n250 ok\r\n250 ok\r\n354 go\r\n250 ok\r\n250 ok\r\n250 ok\r\n354 go\r\n250 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + smtp.send("ada@example.org", &["bob@example.org"], "Subject: é\r\n\r\n".as_bytes()).unwrap(); + smtp.send("", &["bob@example.org"], b"Subject: e\r\n\r\n").unwrap(); + let sent = s.sent(); + assert!(sent.contains("MAIL FROM:<ada@example.org> BODY=8BITMIME\r\n")); + // An empty sender is the bounce address. + assert!(sent.contains("MAIL FROM:<>\r\n")); +} + +#[test] +fn a_refused_recipient_stops_the_message_and_resets() { + let mut s = Script::new("250 ok\r\n250 ok\r\n550 5.1.1 no such user\r\n250 reset\r\n"); + let mut smtp = Smtp::resume(&mut s); + let text = rejected(smtp.send("ada@example.org", &["bob@example.org", "nobody@example.org", "carol@example.org"], b"x")); + assert_eq!(text, "nobody@example.org: 550 5.1.1 no such user"); + assert!(s.sent().ends_with("RCPT TO:<nobody@example.org>\r\nRSET\r\n")); +} + +#[test] +fn refusals_at_each_step() { + // MAIL FROM. + let mut s = Script::new("552 5.3.4 too big\r\n"); + assert_eq!(rejected(Smtp::resume(&mut s).send("a@example.org", &["b@example.org"], b"x")), "552 5.3.4 too big"); + // DATA. + let mut s = Script::new("250 ok\r\n250 ok\r\n554 no\r\n250 reset\r\n"); + assert_eq!(rejected(Smtp::resume(&mut s).send("a@example.org", &["b@example.org"], b"x")), "554 no"); + assert!(s.sent().ends_with("DATA\r\nRSET\r\n")); + // After the message. + let mut s = Script::new("250 ok\r\n250 ok\r\n354 go\r\n451 4.3.0 try later\r\n"); + assert_eq!(rejected(Smtp::resume(&mut s).send("a@example.org", &["b@example.org"], b"x")), "451 4.3.0 try later"); + // The greeting. + let mut s = Script::new("554 no service for you\r\n"); + assert_eq!(Smtp::connect(&mut s).unwrap_err(), ProtoError::Rejected("554 no service for you".into())); +} + +#[test] +fn unsafe_addresses_are_never_sent() { + let cases: [(&str, &[&str]); 6] = [ + ("ada@example.org", &[]), + ("ada@example.org", &["bob@example.org>\r\nRCPT TO:<eve@example.org"]), + ("ada@example.org", &["bob smith@example.org"]), + ("ada@example.org", &[""]), + ("ada@example.org\r\nDATA", &["bob@example.org"]), + ("ada@example.org", &["bøb@example.org"]), + ]; + for (from, to) in cases { + let mut s = Script::new("250 ok\r\n250 ok\r\n354 go\r\n250 ok\r\n"); + assert!(matches!(Smtp::resume(&mut s).send(from, to, b"x"), Err(ProtoError::Protocol(_))), "{from:?} {to:?}"); + assert_eq!(s.sent(), "", "{from:?} {to:?}"); + } +} + +#[test] +fn junk_replies_are_protocol_errors() { + for junk in ["hello there\r\n", "25 ok\r\n", "250ok\r\n", "250-first\r\n251 second\r\n", "\r\n", "2éé ok\r\n"] { + let mut s = Script::new(junk); + assert!(matches!(Smtp::resume(&mut s).hello("localhost"), Err(ProtoError::Protocol(_))), "{junk:?}"); + } + // A reply that never ends. + let mut s = Script::whole("250-more\r\n".repeat(MAX_REPLY_LINES + 1)); + assert_eq!(Smtp::resume(&mut s).hello("localhost"), Err(ProtoError::Protocol(said!("the server's reply has too many lines")))); + // A greeting that is a success code but not 220. + let mut s = Script::new("250 hello\r\n"); + assert!(matches!(Smtp::connect(&mut s), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn a_dead_connection_is_an_io_error() { + let mut s = Script::new("250-half a rep"); + assert_eq!(Smtp::resume(&mut s).hello("localhost"), Err(ProtoError::Io(said!("the server closed the connection")))); + assert!(matches!(Smtp::connect(Broken(ErrorKind::TimedOut)), Err(ProtoError::Io(_)))); + assert!(matches!(Smtp::resume(Broken(ErrorKind::ConnectionReset)).send("a@example.org", &["b@example.org"], b"x"), Err(ProtoError::Io(_)))); +} + +#[test] +fn quitting() { + let mut s = Script::new("221 bye\r\n"); + assert_eq!(Smtp::resume(&mut s).quit(), Ok(())); + // A server that just hangs up has quit too. + let mut s = Script::new(""); + assert_eq!(Smtp::resume(&mut s).quit(), Ok(())); + assert_eq!(s.sent(), "QUIT\r\n"); + let mut s = Script::new("500 what\r\n"); + assert!(matches!(Smtp::resume(&mut s).quit(), Err(ProtoError::Rejected(_)))); +} + +/// Everything a client does, against whatever the "server" says. +fn drive(server: &[u8]) { + let mut s = Script::new(server); + if let Ok(mut smtp) = Smtp::connect(&mut s) { + let _ = smtp.hello("localhost"); + let _ = smtp.auth("ada@example.org", "hunter2"); + let _ = smtp.send("ada@example.org", &["bob@example.org"], b"Subject: x\r\n\r\n.\r\n"); + let _ = smtp.quit(); + } + let mut s = Script::new(server); + let mut smtp = Smtp::resume(&mut s); + smtp.ext = Extensions { auth_login: true, ..Default::default() }; + let _ = smtp.auth("ada", "hunter2"); + let _ = smtp.starttls(); + // With a token, on one line and on its own. + for token in ["tok.en-123".to_string(), "t".repeat(700)] { + let mut s = Script::new(server); + let mut smtp = Smtp::resume(&mut s); + smtp.ext = Extensions { auth_xoauth2: true, ..Default::default() }; + let _ = smtp.auth_xoauth2("ada@example.org", &token); + let _ = smtp.send("ada@example.org", &["bob@example.org"], b"x"); + } +} + +proptest! { + #[test] + fn arbitrary_server_bytes_never_panic_or_hang(server in proptest::collection::vec(any::<u8>(), 0..600)) { + drive(&server); + } + + #[test] + fn reply_shaped_noise_never_panics(lines in proptest::collection::vec(("[0-9]{3}", "[- ]?", "[ -~]{0,30}"), 0..40)) { + let server: String = lines.iter().map(|(code, sep, text)| format!("{code}{sep}{text}\r\n")).collect(); + drive(server.as_bytes()); + } + + #[test] + fn data_blocks_never_end_early(message in proptest::collection::vec(prop_oneof![Just(b'.'), Just(b'\r'), Just(b'\n'), any::<u8>()], 0..300)) { + let (data, size) = data_block(&message); + prop_assert!(data.ends_with(b".\r\n")); + let body = &data[..data.len() - 3]; + prop_assert!(body.is_empty() || body.ends_with(b"\r\n")); + // No bare CR or LF, and no line that is just a dot before the end. + let text = String::from_utf8_lossy(body); + prop_assert_eq!(body.iter().filter(|b| **b == b'\r').count(), body.iter().filter(|b| **b == b'\n').count()); + prop_assert!(!text.contains("\r\n.\r\n") && !text.starts_with(".\r\n")); + prop_assert_eq!(body.windows(2).filter(|w| w[0] == b'\r' && w[1] == b'\n').count(), body.iter().filter(|b| **b == b'\n').count()); + // Taking the stuffing out gives the size that was announced. + let unstuffed: usize = body.split_inclusive(|b| *b == b'\n').map(|l| l.len() - usize::from(l.starts_with(b"."))).sum(); + prop_assert_eq!(unstuffed, size); + } +} diff --git a/crates/ps/Cargo.toml b/crates/ps/Cargo.toml new file mode 100644 index 000000000..baa9050e4 --- /dev/null +++ b/crates/ps/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "craft-ps" +description = "PostScript and EPS for Craft apps: an EPS interpreter that paints into PDF" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[features] +default = [] +read = ["dep:craft-eps", "dep:pdf-writer", "dep:miniz_oxide", "dep:weezl", "dep:skrifa", "dep:kurbo"] + +[dependencies] +craft-eps = { workspace = true, optional = true } +pdf-writer = { workspace = true, optional = true } +miniz_oxide = { workspace = true, optional = true } +weezl = { workspace = true, optional = true } +skrifa = { workspace = true, optional = true } +kurbo = { workspace = true, optional = true } + +[[example]] +name = "eps2pdf" +required-features = ["read"] diff --git a/crates/ps/README.md b/crates/ps/README.md new file mode 100644 index 000000000..51deedcc2 --- /dev/null +++ b/crates/ps/README.md @@ -0,0 +1,50 @@ +# craft-ps + +PostScript and EPS for the Craft apps. No feature is enabled by default. + +| Feature | Provides | +| --- | --- | +| `read` | An EPS interpreter: runs the program and returns what it paints as a one-page PDF | + +Writing PostScript and EPS (craft-libs #115) is planned as a separate feature next to `read`. + +## Reading EPS + +`read::eps_to_pdf(bytes, limits)` runs an EPS (plain, or DOS EPS with a binary header) and +returns a one-page PDF 1.4 the size of its bounding box: vectors stay vectors, CMYK and spot +colours stay as they are, so an app can draw and export the result as a placed PDF. +`read::cached_pdf` converts with the default limits and remembers the result by content. +`is_eps`, `bounding_box` and `postscript_section` read the file without running it. +EPS binary sections and DSC comments are read by `craft-eps`. + +It is written from the PostScript Language Reference (third edition), the EPS specification, +the Type 1 Font Format and Adobe Technical Notes 5012 (Type 42), 5176 (CFF) and 5177 (Type 2 +charstrings); no GPL code was used. It covers what EPS files use: + +- the language: Level 3 operators, an explicit execution stack (no Rust recursion for + PostScript control flow), `stopped`, resources, `eexec`; +- graphics: paths, painting, clipping, `strokepath`, user paths and forms; +- colour: device spaces, Separation and DeviceN, Indexed, ICCBased, Lab; +- images, with filters decoded as they are read (ASCIIHex, ASCII85, RunLength, LZW, Flate with + predictors, SubFile, ReusableStream; JPEG is passed through); +- smooth shadings (types 1–7, meshes included), shading and tiling patterns; +- text in Type 1, Type 3, Type 42 and CFF fonts (`StartData`), CIDFonts and composite fonts + through CMaps, horizontal and vertical. + +Not covered: Level 2 binary tokens, CIDFontType 0 with Type 1 charstrings, CIDFontType 1 and +the old composite FMapTypes other than 2 and 9. + +## Limits + +`Limits { steps, memory, stack_overflow_noop, skip_images, keep_unpainted, zero_division_zero, fallback_font }` bounds one conversion. The optional font callback supplies host stand-ins for missing fonts; booleans let a host retain prior operand-overflow, image, partial-page, and numeric-coercion behavior. Every operator charges the work it does in +proportion to its operands (elements copied or searched, path segments, glyphs, samples) +against `steps` as it goes, and every byte read or decoded at any filter level counts too, so +the step limit bounds run time. `memory` bounds everything a conversion makes, copies +included. The defaults are 50 million steps and 1 GiB, or 20 million and 256 MiB on wasm32; +real EPS files use at most a few million steps and tens of megabytes, and a program that runs +into the limits ends within seconds. By default a program that fails or exceeds them before +painting anything gives `Err`; setting `keep_unpainted` returns a blank page with the warning. +One that fails later keeps what it painted (with a warning). + +`cargo run -p craft-ps --features read --example eps2pdf -- in.eps out.pdf` converts one file +and prints the steps and memory it used. diff --git a/crates/ps/examples/eps2pdf.rs b/crates/ps/examples/eps2pdf.rs new file mode 100644 index 000000000..a3cbfe0cf --- /dev/null +++ b/crates/ps/examples/eps2pdf.rs @@ -0,0 +1,41 @@ +//! `cargo run -p craft-ps --features read --example eps2pdf -- in.eps out.pdf`: convert one EPS. + +fn main() -> std::process::ExitCode { + let args: Vec<String> = std::env::args().skip(1).collect(); + let (Some(input), Some(output)) = (args.first(), args.get(1)) else { + eprintln!("usage: eps2pdf in.eps out.pdf"); + return std::process::ExitCode::FAILURE; + }; + let bytes = match std::fs::read(input) { + Ok(b) => b, + Err(e) => { + eprintln!("{input}: {e}"); + return std::process::ExitCode::FAILURE; + } + }; + let t = std::time::Instant::now(); + match craft_ps::read::eps_to_pdf(&bytes, craft_ps::read::Limits::default()) { + Ok(c) => { + eprintln!( + "{input}: {:.0} ms, bbox {:?}, {} warnings, {} steps, {} KiB", + t.elapsed().as_secs_f64() * 1000.0, + c.bbox, + c.warnings.len(), + c.steps, + c.memory / 1024 + ); + for w in c.warnings.iter().take(20) { + eprintln!(" {w}"); + } + if let Err(e) = std::fs::write(output, &c.pdf) { + eprintln!("{output}: {e}"); + return std::process::ExitCode::FAILURE; + } + std::process::ExitCode::SUCCESS + } + Err(e) => { + eprintln!("{input}: {e} ({:.0} ms)", t.elapsed().as_secs_f64() * 1000.0); + std::process::ExitCode::FAILURE + } + } +} diff --git a/crates/ps/src/lib.rs b/crates/ps/src/lib.rs new file mode 100644 index 000000000..ab5383259 --- /dev/null +++ b/crates/ps/src/lib.rs @@ -0,0 +1,9 @@ +//! PostScript and EPS for the Craft apps. +//! +//! - [`read`] (feature `read`): runs an EPS and gives what it paints as a one-page vector PDF, +//! for apps that place EPS files as graphics. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +#[cfg(feature = "read")] +pub mod read; diff --git a/crates/ps/src/read/cff.rs b/crates/ps/src/read/cff.rs new file mode 100644 index 000000000..bbf7c4c8d --- /dev/null +++ b/crates/ps/src/read/cff.rs @@ -0,0 +1,604 @@ +//! CFF font sets and Type 2 charstrings (Adobe Technical Notes 5176 and 5177): name-keyed and +//! CID-keyed fonts, as `StartData` defines them. + +use crate::read::gstate::Seg; +use crate::read::type1::Glyph; + +/// The most glyphs, subroutines or INDEX entries read. +const MAX_ENTRIES: usize = 200_000; +const MAX_OPS: usize = 200_000; +const MAX_DEPTH: usize = 10; + +#[derive(Debug, Clone, Default)] +struct Private { + subrs: Vec<(usize, usize)>, + default_width: f64, + nominal_width: f64, +} + +#[derive(Debug, Clone)] +pub struct Font { + pub name: Vec<u8>, + pub matrix: [f64; 6], + pub bbox: [f64; 4], + /// Glyph names (name-keyed) by glyph index. + pub names: Vec<Vec<u8>>, + /// Code → glyph index (name-keyed fonts). + pub encoding: Vec<(u8, u32)>, + /// CID by glyph index (CID-keyed fonts), and the registry/ordering/supplement. + pub cids: Option<Vec<u32>>, + pub ros: Option<(Vec<u8>, Vec<u8>, i64)>, + /// CID → glyph index, made on first lookup. + by_cid: std::cell::OnceCell<std::collections::HashMap<u32, u32>>, + charstrings: Vec<(usize, usize)>, + privates: Vec<Private>, + fd_select: Vec<u8>, +} + +#[derive(Debug)] +pub struct FontSet { + pub data: Vec<u8>, + gsubrs: Vec<(usize, usize)>, + pub fonts: Vec<Font>, +} + +fn u16_at(d: &[u8], i: usize) -> Option<usize> { + Some(usize::from(u16::from_be_bytes([*d.get(i)?, *d.get(i + 1)?]))) +} + +fn offset(d: &[u8], i: usize, size: usize) -> Option<usize> { + let mut v = 0usize; + for k in 0..size { + v = v.checked_mul(256)?.checked_add(usize::from(*d.get(i + k)?))?; + } + Some(v) +} + +/// An INDEX at `at`: its entries as (start, end) in `d`, and where it ends. +fn index(d: &[u8], at: usize) -> Option<(Vec<(usize, usize)>, usize)> { + let count = u16_at(d, at)?; + if count == 0 { + return Some((Vec::new(), at + 2)); + } + if count > MAX_ENTRIES { + return None; + } + let size = usize::from(*d.get(at + 2)?); + if !(1..=4).contains(&size) { + return None; + } + let offs_at = at + 3; + let data_at = offs_at + (count + 1) * size - 1; + let mut out = Vec::with_capacity(count); + let mut prev = offset(d, offs_at, size)?; + for i in 1..=count { + let next = offset(d, offs_at + i * size, size)?; + let (s, e) = (data_at.checked_add(prev)?, data_at.checked_add(next)?); + if e < s || e > d.len() { + return None; + } + out.push((s, e)); + prev = next; + } + let end = data_at.checked_add(prev)?; + Some((out, end)) +} + +#[derive(Debug, Default)] +struct Dict { + entries: Vec<(u16, Vec<f64>)>, +} + +impl Dict { + fn get(&self, op: u16) -> Option<&[f64]> { + self.entries.iter().find(|(o, _)| *o == op).map(|(_, v)| v.as_slice()) + } + + fn num(&self, op: u16) -> Option<f64> { + self.get(op)?.first().copied() + } +} + +fn dict(d: &[u8]) -> Dict { + let mut out = Dict::default(); + let mut ops: Vec<f64> = Vec::new(); + let mut i = 0; + while let Some(&b) = d.get(i) { + i += 1; + match b { + 0..=21 => { + let op = if b == 12 { + let e = d.get(i).copied().unwrap_or(0); + i += 1; + 1200 + u16::from(e) + } else { + u16::from(b) + }; + out.entries.push((op, std::mem::take(&mut ops))); + } + 28 => { + let v = i16::from_be_bytes([d.get(i).copied().unwrap_or(0), d.get(i + 1).copied().unwrap_or(0)]); + i += 2; + ops.push(f64::from(v)); + } + 29 => { + let v = i32::from_be_bytes([0, 1, 2, 3].map(|k| d.get(i + k).copied().unwrap_or(0))); + i += 4; + ops.push(f64::from(v)); + } + 30 => { + // A real: nibbles. + let mut s = String::new(); + 'real: while let Some(&n) = d.get(i) { + i += 1; + for nib in [n >> 4, n & 15] { + match nib { + 0..=9 => s.push(char::from(b'0' + nib)), + 0xa => s.push('.'), + 0xb => s.push('E'), + 0xc => s.push_str("E-"), + 0xe => s.push('-'), + 0xf => break 'real, + _ => {} + } + } + } + ops.push(s.parse().unwrap_or(0.0)); + } + 32..=246 => ops.push(f64::from(b) - 139.0), + 247..=250 => { + let w = d.get(i).copied().unwrap_or(0); + i += 1; + ops.push((f64::from(b) - 247.0) * 256.0 + f64::from(w) + 108.0); + } + 251..=254 => { + let w = d.get(i).copied().unwrap_or(0); + i += 1; + ops.push(-(f64::from(b) - 251.0) * 256.0 - f64::from(w) - 108.0); + } + _ => {} + } + if ops.len() > 64 { + break; + } + } + out +} + +fn private(d: &[u8], top: &Dict) -> Private { + let Some(v) = top.get(18) else { return Private::default() }; + let (size, off) = (v.first().copied().unwrap_or(0.0).max(0.0) as usize, v.get(1).copied().unwrap_or(0.0).max(0.0) as usize); + let Some(bytes) = off.checked_add(size).and_then(|e| d.get(off..e)) else { return Private::default() }; + let p = dict(bytes); + let subrs = p.num(19).and_then(|rel| index(d, off.checked_add(rel.max(0.0) as usize)?)).map(|(v, _)| v).unwrap_or_default(); + Private { subrs, default_width: p.num(20).unwrap_or(0.0), nominal_width: p.num(21).unwrap_or(0.0) } +} + +/// The glyph index → SID (or CID) charset. +fn charset(d: &[u8], at: usize, glyphs: usize) -> Vec<u32> { + let mut out = vec![0u32]; + // Predefined charsets (ISOAdobe and the expert ones): glyph index = SID. + if at <= 2 { + return (0..glyphs as u32).collect(); + } + let Some(&format) = d.get(at) else { return out }; + let mut i = at + 1; + while out.len() < glyphs { + match format { + 0 => match u16_at(d, i) { + Some(s) => { + out.push(s as u32); + i += 2; + } + None => break, + }, + 1 | 2 => { + let (Some(first), Some(n)) = (u16_at(d, i), if format == 1 { d.get(i + 2).map(|v| usize::from(*v)) } else { u16_at(d, i + 2) }) + else { + break; + }; + i += if format == 1 { 3 } else { 4 }; + for k in 0..=n { + if out.len() >= glyphs { + break; + } + out.push((first + k) as u32); + } + } + _ => break, + } + } + out +} + +fn fd_select(d: &[u8], at: usize, glyphs: usize) -> Vec<u8> { + let mut out = vec![0u8; glyphs]; + match d.get(at) { + Some(0) => { + for (g, slot) in out.iter_mut().enumerate() { + *slot = d.get(at + 1 + g).copied().unwrap_or(0); + } + } + Some(3) => { + let n = u16_at(d, at + 1).unwrap_or(0); + for r in 0..n { + let base = at + 3 + r * 3; + let (Some(first), Some(fd), Some(next)) = (u16_at(d, base), d.get(base + 2), u16_at(d, base + 3)) else { break }; + for g in first..next.min(glyphs) { + if let Some(slot) = out.get_mut(g) { + *slot = *fd; + } + } + } + } + _ => {} + } + out +} + +fn sid_name(sid: u32, strings: &[(usize, usize)], d: &[u8]) -> Vec<u8> { + let sid = sid as usize; + match crate::read::cff_strings::standard(sid) { + Some(n) => n.into_bytes(), + None => strings + .get(sid - crate::read::cff_strings::COUNT) + .and_then(|(s, e)| d.get(*s..*e)) + .map(<[u8]>::to_vec) + .unwrap_or_else(|| b".notdef".to_vec()), + } +} + +pub fn parse(data: Vec<u8>) -> Option<FontSet> { + let d = &data; + let hdr = usize::from(*d.get(2)?); + let (names, after_names) = index(d, hdr)?; + let (tops, after_tops) = index(d, after_names)?; + let (strings, after_strings) = index(d, after_tops)?; + let (gsubrs, _) = index(d, after_strings)?; + let mut fonts = Vec::new(); + for (k, &(ts, te)) in tops.iter().enumerate() { + let top = dict(d.get(ts..te)?); + let name = names.get(k).and_then(|(s, e)| d.get(*s..*e)).map(<[u8]>::to_vec).unwrap_or_default(); + let (charstrings, _) = index(d, top.num(17)?.max(0.0) as usize)?; + let glyphs = charstrings.len(); + let matrix = + top.get(1207).filter(|m| m.len() == 6).map(|m| [m[0], m[1], m[2], m[3], m[4], m[5]]).unwrap_or([0.001, 0.0, 0.0, 0.001, 0.0, 0.0]); + let bbox = top.get(5).filter(|b| b.len() == 4).map(|b| [b[0], b[1], b[2], b[3]]).unwrap_or([0.0, 0.0, 1000.0, 1000.0]); + let cs = charset(d, top.num(15).unwrap_or(0.0).max(0.0) as usize, glyphs); + let ros = top.get(1230).map(|v| { + let s = |i: usize| sid_name(v.get(i).copied().unwrap_or(0.0) as u32, &strings, d); + (s(0), s(1), v.get(2).copied().unwrap_or(0.0) as i64) + }); + let (privates, fds, names_out, cids) = if ros.is_some() { + let fdarray = top.num(1236).and_then(|o| index(d, o.max(0.0) as usize)).map(|(v, _)| v).unwrap_or_default(); + let privates = fdarray.iter().map(|(s, e)| d.get(*s..*e).map(|b| private(d, &dict(b))).unwrap_or_default()).collect(); + let fds = top.num(1237).map(|o| fd_select(d, o.max(0.0) as usize, glyphs)).unwrap_or_else(|| vec![0; glyphs]); + (privates, fds, Vec::new(), Some(cs)) + } else { + let names_out: Vec<Vec<u8>> = cs.iter().map(|sid| sid_name(*sid, &strings, d)).collect(); + (vec![private(d, &top)], Vec::new(), names_out, None) + }; + // Encoding (name-keyed): predefined Standard, or format 0/1 code lists. + let mut encoding = Vec::new(); + if cids.is_none() { + match top.num(16).unwrap_or(0.0) as usize { + 0 => { + let std = crate::read::encodings::standard(); + for (code, n) in std.iter().enumerate() { + if let Some(g) = names_out.iter().position(|x| x == n.as_bytes()) { + encoding.push((code as u8, g as u32)); + } + } + } + 1 => {} + at => { + let fmt = d.get(at).copied().unwrap_or(0) & 0x7f; + let n = usize::from(d.get(at + 1).copied().unwrap_or(0)); + if fmt == 0 { + for g in 0..n { + if let Some(c) = d.get(at + 2 + g) { + encoding.push((*c, g as u32 + 1)); + } + } + } else { + let mut g = 1u32; + for r in 0..n { + let (Some(first), Some(left)) = (d.get(at + 2 + r * 2), d.get(at + 3 + r * 2)) else { break }; + for k in 0..=u32::from(*left) { + encoding.push((first.wrapping_add(k as u8), g)); + g += 1; + } + } + } + } + } + } + fonts.push(Font { + name, + matrix, + bbox, + names: names_out, + encoding, + cids, + ros, + by_cid: std::cell::OnceCell::new(), + charstrings, + privates, + fd_select: fds, + }); + } + Some(FontSet { data, gsubrs, fonts }) +} + +fn bias(n: usize) -> i64 { + if n < 1240 { + 107 + } else if n < 33900 { + 1131 + } else { + 32768 + } +} + +struct Run { + path: Vec<Seg>, + x: f64, + y: f64, + open: bool, + stack: Vec<f64>, + hints: usize, + width: Option<f64>, + ops: usize, + done: bool, +} + +impl Run { + fn move_to(&mut self, dx: f64, dy: f64) { + if self.open { + self.path.push(Seg::Close); + } + self.x += dx; + self.y += dy; + self.path.push(Seg::Move(self.x, self.y)); + self.open = true; + } + + fn line(&mut self, dx: f64, dy: f64) { + self.x += dx; + self.y += dy; + self.path.push(Seg::Line(self.x, self.y)); + } + + fn curve(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) { + let (x1, y1) = (self.x + a, self.y + b); + let (x2, y2) = (x1 + c, y1 + d); + let (x3, y3) = (x2 + e, y2 + f); + self.path.push(Seg::Curve(x1, y1, x2, y2, x3, y3)); + self.x = x3; + self.y = y3; + } + + /// The first stack-clearing operator may carry the width before its arguments: there is + /// one when the count's parity differs from the operator's own (`expected_odd`). + fn take_width(&mut self, expected_odd: bool) { + if self.width.is_none() { + let present = !self.stack.is_empty() && (self.stack.len() % 2 == 1) != expected_odd; + self.width = Some(if present { self.stack.remove(0) } else { f64::NAN }); + } + } +} + +impl FontSet { + fn bytes(&self, r: (usize, usize)) -> &[u8] { + self.data.get(r.0..r.1).unwrap_or(&[]) + } + + fn exec(&self, code: &[u8], local: &[(usize, usize)], run: &mut Run, depth: usize) -> Option<()> { + if depth > MAX_DEPTH { + return None; + } + let mut i = 0; + while i < code.len() && !run.done { + run.ops += 1; + if run.ops > MAX_OPS || run.stack.len() > 96 { + return None; + } + let b = *code.get(i)?; + i += 1; + match b { + 32..=246 => run.stack.push(f64::from(b) - 139.0), + 247..=250 => { + let w = *code.get(i)?; + i += 1; + run.stack.push((f64::from(b) - 247.0) * 256.0 + f64::from(w) + 108.0); + } + 251..=254 => { + let w = *code.get(i)?; + i += 1; + run.stack.push(-(f64::from(b) - 251.0) * 256.0 - f64::from(w) - 108.0); + } + 28 => { + let v = i16::from_be_bytes([*code.get(i)?, *code.get(i + 1)?]); + i += 2; + run.stack.push(f64::from(v)); + } + 255 => { + let v = i32::from_be_bytes([*code.get(i)?, *code.get(i + 1)?, *code.get(i + 2)?, *code.get(i + 3)?]); + i += 4; + run.stack.push(f64::from(v) / 65536.0); + } + // hstem, vstem, hstemhm, vstemhm: count the hints (an odd count carries the width). + 1 | 3 | 18 | 23 => { + run.take_width(false); + run.hints += run.stack.len() / 2; + run.stack.clear(); + } + 19 | 20 => { + // hintmask, cntrmask: implicit vstems, then the mask bytes. + run.take_width(false); + run.hints += run.stack.len() / 2; + run.stack.clear(); + i += run.hints.div_ceil(8); + } + 21 => { + run.take_width(false); + let s = std::mem::take(&mut run.stack); + run.move_to(s.first().copied().unwrap_or(0.0), s.get(1).copied().unwrap_or(0.0)); + } + 22 | 4 => { + run.take_width(true); + let s = std::mem::take(&mut run.stack); + let v = s.first().copied().unwrap_or(0.0); + if b == 22 { run.move_to(v, 0.0) } else { run.move_to(0.0, v) } + } + 5 => { + let s = std::mem::take(&mut run.stack); + for &[x, y] in s.as_chunks::<2>().0 { + run.line(x, y); + } + } + 6 | 7 => { + let s = std::mem::take(&mut run.stack); + let mut horizontal = b == 6; + for v in s { + if horizontal { + run.line(v, 0.0) + } else { + run.line(0.0, v) + } + horizontal = !horizontal; + } + } + 8 => { + let s = std::mem::take(&mut run.stack); + for &[a, b2, c, d, e, f] in s.as_chunks::<6>().0 { + run.curve(a, b2, c, d, e, f); + } + } + 24 => { + // rcurveline + let s = std::mem::take(&mut run.stack); + let n = s.len().saturating_sub(2) / 6; + for &[a, b2, c, d, e, f] in s.as_chunks::<6>().0.iter().take(n) { + run.curve(a, b2, c, d, e, f); + } + if let (Some(a), Some(b2)) = (s.get(n * 6), s.get(n * 6 + 1)) { + run.line(*a, *b2); + } + } + 25 => { + // rlinecurve + let s = std::mem::take(&mut run.stack); + let lines = s.len().saturating_sub(6) / 2; + for &[x, y] in s.as_chunks::<2>().0.iter().take(lines) { + run.line(x, y); + } + if let Some(&[a, b2, c, d, e, f]) = s.get(lines * 2..lines * 2 + 6).and_then(|w| <&[f64; 6]>::try_from(w).ok()) { + run.curve(a, b2, c, d, e, f); + } + } + 26 | 27 => { + // vvcurveto, hhcurveto + let mut s = std::mem::take(&mut run.stack); + let mut first = if s.len() % 4 == 1 { Some(s.remove(0)) } else { None }; + for &[p, q, r, t] in s.as_chunks::<4>().0 { + let d1 = first.take().unwrap_or(0.0); + if b == 26 { run.curve(d1, p, q, r, 0.0, t) } else { run.curve(p, d1, q, r, t, 0.0) } + } + } + 30 | 31 => { + // vhcurveto, hvcurveto: alternating curves; the last may end off-axis. + let s = std::mem::take(&mut run.stack); + let mut horizontal = b == 31; + let mut k = 0; + while let Some(&[a, bb, c, d]) = s.get(k..k + 4).and_then(|w| <&[f64; 4]>::try_from(w).ok()) { + let extra = if s.len() - k == 5 { s.get(k + 4).copied().unwrap_or(0.0) } else { 0.0 }; + if horizontal { + run.curve(a, 0.0, bb, c, extra, d) + } else { + run.curve(0.0, a, bb, c, d, extra) + } + horizontal = !horizontal; + k += 4; + } + } + 10 | 29 => { + let n = run.stack.pop()? as i64; + let (list, bias) = if b == 10 { (local, bias(local.len())) } else { (&self.gsubrs[..], bias(self.gsubrs.len())) }; + let sub = *list.get(usize::try_from(n + bias).ok()?)?; + let sub = self.bytes(sub).to_vec(); + self.exec(&sub, local, run, depth + 1)?; + } + 11 => return Some(()), + 14 => { + run.take_width(false); + if run.open { + run.path.push(Seg::Close); + run.open = false; + } + run.done = true; + } + 12 => { + let e = *code.get(i)?; + i += 1; + let s = std::mem::take(&mut run.stack); + let a = |k: usize| s.get(k).copied().unwrap_or(0.0); + match e { + 35 => { + run.curve(a(0), a(1), a(2), a(3), a(4), a(5)); + run.curve(a(6), a(7), a(8), a(9), a(10), a(11)); + } + 34 => { + // hflex: dx1 dx2 dy2 dx3 dx4 dx5 dx6, back to the start height. + run.curve(a(0), 0.0, a(1), a(2), a(3), 0.0); + run.curve(a(4), 0.0, a(5), -a(2), a(6), 0.0); + } + 36 => { + // hflex1: dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6. + run.curve(a(0), a(1), a(2), a(3), a(4), 0.0); + run.curve(a(5), 0.0, a(6), a(7), a(8), -(a(1) + a(3) + a(7))); + } + 37 => { + // flex1: the last coordinate runs along the longer direction. + let dx = a(0) + a(2) + a(4) + a(6) + a(8); + let dy = a(1) + a(3) + a(5) + a(7) + a(9); + let (ex, ey) = if dx.abs() > dy.abs() { (a(10), -dy) } else { (-dx, a(10)) }; + run.curve(a(0), a(1), a(2), a(3), a(4), a(5)); + run.curve(a(6), a(7), a(8), a(9), ex, ey); + } + _ => {} + } + } + _ => {} + } + } + Some(()) + } + + /// Glyph `gid` of font `k` in glyph space (multiplied out by its FontMatrix later). + pub fn glyph(&self, k: usize, gid: u32) -> Option<Glyph> { + let font = self.fonts.get(k)?; + let cs = *font.charstrings.get(gid as usize)?; + let fd = usize::from(font.fd_select.get(gid as usize).copied().unwrap_or(0)); + let private = font.privates.get(fd).or_else(|| font.privates.first()).cloned().unwrap_or_default(); + let mut run = Run { path: Vec::new(), x: 0.0, y: 0.0, open: false, stack: Vec::new(), hints: 0, width: None, ops: 0, done: false }; + let code = self.bytes(cs).to_vec(); + self.exec(&code, &private.subrs, &mut run, 0)?; + if run.open { + run.path.push(Seg::Close); + } + let w = match run.width { + Some(w) if w.is_finite() => private.nominal_width + w, + _ => private.default_width, + }; + Some(Glyph { cost: run.ops + run.path.len(), path: run.path, width: (w, 0.0) }) + } + + /// The glyph index of a CID in font `k`. + pub fn gid_of_cid(&self, k: usize, cid: u32) -> Option<u32> { + let font = self.fonts.get(k)?; + let cids = font.cids.as_ref()?; + let map = font.by_cid.get_or_init(|| cids.iter().enumerate().filter_map(|(g, c)| Some((*c, u32::try_from(g).ok()?))).collect()); + map.get(&cid).copied() + } +} diff --git a/crates/ps/src/read/cff_strings.rs b/crates/ps/src/read/cff_strings.rs new file mode 100644 index 000000000..38061243b --- /dev/null +++ b/crates/ps/src/read/cff_strings.rs @@ -0,0 +1,252 @@ +//! CFF standard strings (Technical Note 5176, Appendix A): SIDs below 391 name these. + +/// SIDs 0–228: the Standard and ISO Latin glyph names. +const NAMES: [&str; 229] = [ + ".notdef", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "exclamdown", + "cent", + "sterling", + "fraction", + "yen", + "florin", + "section", + "currency", + "quotesingle", + "quotedblleft", + "guillemotleft", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "endash", + "dagger", + "daggerdbl", + "periodcentered", + "paragraph", + "bullet", + "quotesinglbase", + "quotedblbase", + "quotedblright", + "guillemotright", + "ellipsis", + "perthousand", + "questiondown", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + "ring", + "cedilla", + "hungarumlaut", + "ogonek", + "caron", + "emdash", + "AE", + "ordfeminine", + "Lslash", + "Oslash", + "OE", + "ordmasculine", + "ae", + "dotlessi", + "lslash", + "oslash", + "oe", + "germandbls", + "onesuperior", + "logicalnot", + "mu", + "trademark", + "Eth", + "onehalf", + "plusminus", + "Thorn", + "onequarter", + "divide", + "brokenbar", + "degree", + "thorn", + "threequarters", + "twosuperior", + "registered", + "minus", + "eth", + "multiply", + "threesuperior", + "copyright", + "Aacute", + "Acircumflex", + "Adieresis", + "Agrave", + "Aring", + "Atilde", + "Ccedilla", + "Eacute", + "Ecircumflex", + "Edieresis", + "Egrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Igrave", + "Ntilde", + "Oacute", + "Ocircumflex", + "Odieresis", + "Ograve", + "Otilde", + "Scaron", + "Uacute", + "Ucircumflex", + "Udieresis", + "Ugrave", + "Yacute", + "Ydieresis", + "Zcaron", + "aacute", + "acircumflex", + "adieresis", + "agrave", + "aring", + "atilde", + "ccedilla", + "eacute", + "ecircumflex", + "edieresis", + "egrave", + "iacute", + "icircumflex", + "idieresis", + "igrave", + "ntilde", + "oacute", + "ocircumflex", + "odieresis", + "ograve", + "otilde", + "scaron", + "uacute", + "ucircumflex", + "udieresis", + "ugrave", + "yacute", + "ydieresis", + "zcaron", +]; + +/// SIDs 379–390. +const TAIL: [&str; 12] = ["001.000", "001.001", "001.002", "001.003", "Black", "Bold", "Book", "Light", "Medium", "Regular", "Roman", "Semibold"]; + +/// The number of standard strings. +pub const COUNT: usize = 391; + +/// The glyph name a standard SID stands for. The expert-set names (229–378) are given as +/// `sid<n>`, which only has to be consistent within one font (they are its own glyph names). +pub fn standard(sid: usize) -> Option<String> { + if let Some(n) = NAMES.get(sid) { + return Some((*n).to_string()); + } + if let Some(n) = sid.checked_sub(379).and_then(|i| TAIL.get(i)) { + return Some((*n).to_string()); + } + (sid < COUNT).then(|| format!("sid{sid}")) +} diff --git a/crates/ps/src/read/composite.rs b/crates/ps/src/read/composite.rs new file mode 100644 index 000000000..dad0785d9 --- /dev/null +++ b/crates/ps/src/read/composite.rs @@ -0,0 +1,549 @@ +//! CFF font sets (`StartData`), CIDFonts, CMaps (`CIDInit`) and composite (Type 0) fonts. + +use std::rc::Rc; + +use crate::read::gstate::M; +use crate::read::interp::{Interp, R, err, matrix_obj}; +use crate::read::obj::{Key, Obj, PArr, PDict, PStr, name}; +use crate::read::type1::Glyph; + +/// A CMap: code space ranges, code → CID ranges (single codes are ranges of one), a parent. +#[derive(Debug, Default)] +pub struct CMap { + codespace: Vec<(Vec<u8>, Vec<u8>)>, + ranges: Vec<(Vec<u8>, Vec<u8>, u32)>, + parent: Option<usize>, + identity: bool, + /// Vertical writing (WMode 1). + pub vertical: bool, +} + +const MAX_CMAPS: usize = 10_000; +const MAX_RANGES: usize = 500_000; + +fn code_value(b: &[u8]) -> u64 { + b.iter().fold(0u64, |a, x| a << 8 | u64::from(*x)) +} + +fn in_range(code: &[u8], lo: &[u8], hi: &[u8]) -> bool { + code.len() == lo.len() && code.len() == hi.len() && code.iter().zip(lo).zip(hi).all(|((c, l), h)| c >= l && c <= h) +} + +impl Interp { + fn cmap_of(&self, d: &PDict) -> Option<usize> { + match d.get_name(b"CraftPsCMap") { + Some(Obj::Int(i)) => usize::try_from(i).ok(), + _ => None, + } + } + + /// The CMap the current dictionary is building (made on first use). + fn building(&mut self) -> R<usize> { + let d = self.current_dict()?; + if let Some(i) = self.cmap_of(&d) { + return Ok(i); + } + if self.cmaps.len() >= MAX_CMAPS { + return err("limitcheck"); + } + self.cmaps.push(CMap::default()); + let i = self.cmaps.len() - 1; + d.put_name(b"CraftPsCMap", Obj::Int(i as i64)); + Ok(i) + } + + /// CID for a code through CMap `i` (and its parents); None when unmapped. + fn cid(&self, i: usize, code: &[u8], depth: usize) -> Option<u32> { + let m = self.cmaps.get(i)?; + if m.identity { + return u32::try_from(code_value(code)).ok(); + } + for (lo, hi, start) in &m.ranges { + if in_range(code, lo, hi) { + return u32::try_from(u64::from(*start) + code_value(code).saturating_sub(code_value(lo))).ok(); + } + } + if depth < 8 { m.parent.and_then(|p| self.cid(p, code, depth + 1)) } else { None } + } + + /// How many ranges a lookup through CMap `i` may compare. + fn cmap_cost(&self, i: usize) -> u64 { + let mut n = 0u64; + let mut cur = Some(i); + for _ in 0..8 { + let Some(m) = cur.and_then(|c| self.cmaps.get(c)) else { break }; + n = n.saturating_add((m.ranges.len() + m.codespace.len()) as u64); + cur = m.parent; + } + n + } + + fn code_len(&self, i: usize, s: &[u8], depth: usize) -> Option<usize> { + let m = self.cmaps.get(i)?; + for n in 1..=4 { + let Some(code) = s.get(..n) else { break }; + if m.codespace.iter().any(|(lo, hi)| in_range(code, lo, hi)) { + return Some(n); + } + } + if depth < 8 { m.parent.and_then(|p| self.code_len(p, s, depth + 1)) } else { None } + } +} + +// ----- CIDInit procedures ----- + +pub fn begincmap(_ip: &mut Interp) -> R { + Ok(()) +} + +pub fn endcmap(ip: &mut Interp) -> R { + let i = ip.building()?; + let vertical = ip.current_dict()?.get_name(b"WMode").and_then(|o| o.num()) == Some(1.0); + if let Some(m) = ip.cmaps.get_mut(i) { + m.vertical = vertical; + } + Ok(()) +} + +pub fn usecmap(ip: &mut Interp) -> R { + let n = ip.pop()?; + let parent = find_cmap(ip, &n)?; + let i = ip.building()?; + if let Some(m) = ip.cmaps.get_mut(i) { + m.parent = Some(parent); + } + Ok(()) +} + +/// `n begin…` pushes a mark for its entries. +pub fn begin_block(ip: &mut Interp) -> R { + ip.pop_int()?; + ip.push(Obj::Mark) +} + +fn block(ip: &mut Interp) -> R<Vec<Obj>> { + let i = crate::read::ops::basic::mark_pos(ip)?; + let items = ip.o.split_off(i + 1); + ip.o.pop(); + Ok(items) +} + +fn bytes_of(o: &Obj) -> R<Vec<u8>> { + match o { + Obj::Str(s, _) => Ok(s.bytes()), + _ => err("typecheck"), + } +} + +pub fn endcodespacerange(ip: &mut Interp) -> R { + let items = block(ip)?; + let i = ip.building()?; + for p in items.chunks(2) { + if let [lo, hi] = p { + let (lo, hi) = (bytes_of(lo)?, bytes_of(hi)?); + if let Some(m) = ip.cmaps.get_mut(i) { + m.codespace.push((lo, hi)); + } + } + } + Ok(()) +} + +fn add_ranges(ip: &mut Interp, triples: bool) -> R { + let items = block(ip)?; + let i = ip.building()?; + let step = if triples { 3 } else { 2 }; + for e in items.chunks(step) { + let (lo, hi, cid) = match (triples, e) { + (true, [lo, hi, cid]) => (bytes_of(lo)?, bytes_of(hi)?, cid), + (false, [code, cid]) => (bytes_of(code)?, bytes_of(code)?, cid), + _ => continue, + }; + let Some(cid) = cid.num() else { continue }; + if let Some(m) = ip.cmaps.get_mut(i) + && m.ranges.len() < MAX_RANGES + { + m.ranges.push((lo, hi, cid.max(0.0) as u32)); + } + } + Ok(()) +} + +pub fn endcidrange(ip: &mut Interp) -> R { + add_ranges(ip, true) +} + +pub fn endcidchar(ip: &mut Interp) -> R { + add_ranges(ip, false) +} + +/// bf (Unicode) and notdef blocks: read and dropped. +pub fn end_ignored(ip: &mut Interp) -> R { + block(ip).map(|_| ()) +} + +fn identity(ip: &mut Interp, n: &[u8]) -> PDict { + let d = PDict::new(4); + d.put_name(b"CMapName", Obj::lit(n)); + let vertical = n.ends_with(b"-V"); + ip.cmaps.push(CMap { codespace: vec![(vec![0, 0], vec![0xff, 0xff])], identity: true, vertical, ..Default::default() }); + d.put_name(b"CraftPsCMap", Obj::Int(ip.cmaps.len() as i64 - 1)); + d.put_name(b"WMode", Obj::Int(i64::from(n.ends_with(b"-V")))); + d +} + +/// A CMap by name or dictionary: as an index into `ip.cmaps`. +fn find_cmap(ip: &mut Interp, o: &Obj) -> R<usize> { + let d = match o { + Obj::Dict(d) => d.clone(), + n => { + let cats = category(ip, b"CMap"); + match cats.get(&n.key()) { + Some(Obj::Dict(d)) => d, + _ => { + // Unknown CMaps read two-byte codes as CIDs, as Identity does. + let d = identity(ip, &crate::read::ops::basic::text_of(n)); + cats.put(n.clone(), Obj::Dict(d.clone())); + d + } + } + } + }; + match ip.cmap_of(&d) { + Some(i) => Ok(i), + None => { + let i = ip.cmaps.len(); + ip.cmaps.push(CMap { identity: true, codespace: vec![(vec![0, 0], vec![0xff, 0xff])], ..Default::default() }); + d.put_name(b"CraftPsCMap", Obj::Int(i as i64)); + Ok(i) + } + } +} + +fn category(ip: &mut Interp, cat: &[u8]) -> PDict { + match ip.resources.get_name(cat) { + Some(Obj::Dict(d)) => d, + _ => { + let d = PDict::new(20); + ip.resources.put_name(cat, Obj::Dict(d.clone())); + d + } + } +} + +fn add_fid(ip: &mut Interp, d: &PDict) { + if !d.known(&Key::Name(name(b"FID"))) { + d.put_name(b"FID", Obj::FontId(ip.next_fid)); + ip.next_fid += 1; + } +} + +// ----- StartData ----- + +fn nums(v: &[f64]) -> Obj { + Obj::Array(PArr::new(v.iter().map(|x| Obj::Real(*x)).collect()), false) +} + +/// `/name length StartData`: the CFF font set in the next `length` bytes of the current file; +/// its fonts become Font (name-keyed) or CIDFont (CID-keyed) resources. +pub fn startdata(ip: &mut Interp) -> R { + let len = ip.pop_usize()?; + let _set_name = ip.pop()?; + if len > 256 << 20 { + return err("limitcheck"); + } + let file = + ip.e.iter() + .rev() + .find_map(|f| match f { + crate::read::interp::Frame::File { id } => Some(*id), + _ => None, + }) + .unwrap_or(ip.main); + ip.alloc(len)?; + let mut data = Vec::with_capacity(len); + while data.len() < len { + match ip.srcs.read(file) { + Some(c) => data.push(c), + None => break, + } + } + // StartData ends the FontSetInit dictionary its program began. + let fsi = match category(ip, b"ProcSet").get_name(b"FontSetInit") { + Some(Obj::Dict(d)) => Some(d), + _ => None, + }; + if let (Some(top), Some(fsi)) = (ip.d.last(), fsi) + && top.same(&fsi) + && ip.d.len() > 3 + { + ip.d.pop(); + } + // Parsing walks the data, and a font set's glyph tables are as large again. + ip.charge_bytes(data.len())?; + ip.alloc(data.len())?; + let Some(set) = crate::read::cff::parse(data) else { + ip.warnings.push("unreadable CFF font set".into()); + return Ok(()); + }; + let set = Rc::new(set); + let si = ip.cff.len(); + ip.cff.push(set.clone()); + for (k, f) in set.fonts.iter().enumerate() { + let d = PDict::new(16); + let reference = Obj::Array(PArr::new(vec![Obj::Int(si as i64), Obj::Int(k as i64)]), false); + d.put_name(b"CraftPsCff", reference); + d.put_name(b"FontMatrix", nums(&f.matrix)); + d.put_name(b"FontBBox", nums(&f.bbox)); + d.put_name(b"PaintType", Obj::Int(0)); + if let Some((reg, ord, sup)) = &f.ros { + d.put_name(b"CIDFontName", Obj::lit(&f.name)); + d.put_name(b"CIDFontType", Obj::Int(0)); + d.put_name(b"FontType", Obj::Int(9)); + let info = PDict::new(3); + info.put_name(b"Registry", Obj::str(reg)); + info.put_name(b"Ordering", Obj::str(ord)); + info.put_name(b"Supplement", Obj::Int(*sup)); + d.put_name(b"CIDSystemInfo", Obj::Dict(info)); + add_fid(ip, &d); + category(ip, b"CIDFont").put(Obj::lit(&f.name), Obj::Dict(d)); + } else { + d.put_name(b"FontName", Obj::lit(&f.name)); + d.put_name(b"FontType", Obj::Int(2)); + let mut enc = vec![Obj::lit(b".notdef"); 256]; + for (code, gid) in &f.encoding { + if let (Some(slot), Some(n)) = (enc.get_mut(usize::from(*code)), f.names.get(*gid as usize)) { + *slot = Obj::lit(n); + } + } + d.put_name(b"Encoding", Obj::Array(PArr::new(enc), false)); + let cs = PDict::new(f.names.len()); + for (g, n) in f.names.iter().enumerate() { + cs.put_name(n, Obj::Int(g as i64)); + } + d.put_name(b"CharStrings", Obj::Dict(cs)); + d.put_name(b"Private", Obj::Dict(PDict::new(1))); + add_fid(ip, &d); + ip.fontdir.put(Obj::lit(&f.name), Obj::Dict(d.clone())); + category(ip, b"Font").put(Obj::lit(&f.name), Obj::Dict(d)); + } + } + Ok(()) +} + +/// The CFF font set and font index behind a font dictionary. +pub fn cff_of(ip: &Interp, d: &PDict) -> Option<(Rc<crate::read::cff::FontSet>, usize)> { + let Some(Obj::Array(a, _)) = d.get_name(b"CraftPsCff") else { return None }; + let si = a.get(0)?.num()? as usize; + let k = a.get(1)?.num()? as usize; + Some((ip.cff.get(si)?.clone(), k)) +} + +// ----- composite fonts ----- + +/// `name cmap [cidfonts] composefont`: a Type 0 font. +pub fn composefont(ip: &mut Interp) -> R { + let fonts = ip.pop_arr()?; + let cmap = ip.pop()?; + let n = ip.pop()?; + let font = compose(ip, &n, &cmap, fonts.items())?; + ip.push(Obj::Dict(font)) +} + +fn compose(ip: &mut Interp, n: &Obj, cmap: &Obj, descendants: Vec<Obj>) -> R<PDict> { + let i = find_cmap(ip, cmap)?; + let mut desc = Vec::new(); + for f in descendants { + desc.push(match f { + Obj::Dict(d) => Obj::Dict(d), + k => match category(ip, b"CIDFont").get(&k.key()) { + Some(d @ Obj::Dict(_)) => d, + _ => Obj::Dict(crate::read::font::find_font(ip, &k)?), + }, + }); + } + let d = PDict::new(10); + d.put_name(b"FontName", n.clone()); + d.put_name(b"FontType", Obj::Int(0)); + d.put_name(b"FMapType", Obj::Int(9)); + d.put_name(b"FontMatrix", matrix_obj(&M::ID)); + d.put_name(b"Encoding", Obj::Array(PArr::new(vec![Obj::Int(0)]), false)); + d.put_name(b"FDepVector", Obj::Array(PArr::new(desc), false)); + let cm = PDict::new(2); + cm.put_name(b"CraftPsCMap", Obj::Int(i as i64)); + d.put_name(b"CMap", Obj::Dict(cm)); + let vertical = ip.cmaps.get(i).is_some_and(|m| m.vertical); + d.put_name(b"WMode", Obj::Int(i64::from(vertical))); + add_fid(ip, &d); + ip.fontdir.put(n.clone(), Obj::Dict(d.clone())); + Ok(d) +} + +/// `findfont` of `CIDFont-CMap` (as Adobe interpreters do): the two composed. +pub fn compose_by_name(ip: &mut Interp, n: &[u8]) -> Option<PDict> { + let cats = category(ip, b"CIDFont"); + for (k, v) in cats.entries() { + let kn = crate::read::ops::basic::text_of(&k); + if n.len() > kn.len() + 1 && n.starts_with(&kn) && n.get(kn.len()) == Some(&b'-') { + let cmap = n.get(kn.len() + 1..)?; + return compose(ip, &Obj::lit(n), &Obj::lit(cmap), vec![v]).ok(); + } + } + None +} + +/// Whether a font writes vertically (its WMode, or its CMap's). +pub fn vertical(ip: &Interp, font: &PDict) -> bool { + match font.get_name(b"WMode").and_then(|o| o.num()) { + Some(w) => w == 1.0, + None => match font.get_name(b"CMap") { + Some(Obj::Dict(d)) => ip.cmap_of(&d).and_then(|i| ip.cmaps.get(i)).is_some_and(|m| m.vertical), + _ => false, + }, + } +} + +/// A CIDFont's vertical metrics for a CID in glyph space: the advance (w1) and the position +/// vector (v) from the horizontal origin to the vertical one. `Metrics2` gives them per CID; +/// otherwise the defaults: one em down, and v = (half the width, 0.88 em). +pub fn vertical_metrics(cidfont: &PDict, cid: u32, w0: f64, em: f64) -> ((f64, f64), (f64, f64)) { + if let Some(Obj::Dict(m)) = cidfont.get_name(b"Metrics2") + && let Some(Obj::Array(a, _)) = m.get(&Key::Int(i64::from(cid))) + { + let v: Vec<f64> = a.items().iter().filter_map(Obj::num).collect(); + if let [w1x, w1y, vx, vy] = v[..] { + return ((w1x, w1y), (vx, vy)); + } + } + ((0.0, -em), (w0 / 2.0, 0.88 * em)) +} + +/// What one glyph of a shown string draws with. +pub enum Key2 { + Code(u8), + Cid(u32), +} + +/// The glyphs of a string in a Type 0 font: (code, leaf font, glyph → text-space matrix, key). +pub fn decode(ip: &mut Interp, font: &PDict, s: &[u8]) -> R<Vec<(u32, PDict, M, Key2)>> { + let fm = font_matrix(font); + let desc: Vec<PDict> = match font.get_name(b"FDepVector") { + Some(Obj::Array(a, _)) => a.items().into_iter().filter_map(|o| if let Obj::Dict(d) = o { Some(d) } else { None }).collect(), + _ => Vec::new(), + }; + let Some(first) = desc.first().cloned() else { return err("invalidfont") }; + let fmap = font.get_name(b"FMapType").and_then(|o| o.num()).unwrap_or(9.0) as i64; + let mut out = Vec::new(); + if fmap == 2 { + // 8/8 mapping: a font number, then a code in it. + for p in s.chunks(2) { + if let [f, c] = p { + let leaf = desc.get(usize::from(*f)).cloned().unwrap_or_else(|| first.clone()); + let m = font_matrix(&leaf).then(&fm); + out.push((u32::from(*c), leaf, m, Key2::Code(*c))); + } + } + return Ok(out); + } + let cmap = match font.get_name(b"CMap") { + Some(Obj::Dict(d)) => ip.cmap_of(&d), + _ => None, + }; + let m = font_matrix(&first).then(&fm); + let mut i = 0; + // Each code is looked up through the CMap's ranges (and its parents'). + let per_code = cmap.map_or(1, |c| ip.cmap_cost(c)) / 16 + 1; + while i < s.len() { + ip.charge(per_code)?; + let rest = s.get(i..).unwrap_or(&[]); + let n = cmap.and_then(|c| ip.code_len(c, rest, 0)).unwrap_or(2).min(rest.len()).max(1); + let code = rest.get(..n).unwrap_or(&[]); + let cid = cmap.and_then(|c| ip.cid(c, code, 0)).unwrap_or(0); + out.push((u32::try_from(code_value(code)).unwrap_or(0), first.clone(), m, Key2::Cid(cid))); + i += n; + } + Ok(out) +} + +fn font_matrix(d: &PDict) -> M { + match d.get_name(b"FontMatrix") { + Some(Obj::Array(a, _)) => crate::read::interp::matrix_of(&a).unwrap_or(M([0.001, 0.0, 0.0, 0.001, 0.0, 0.0])), + _ => M([0.001, 0.0, 0.0, 0.001, 0.0, 0.0]), + } +} + +/// A CID's glyph in a CIDFont: CFF (CIDFontType 0) or TrueType (CIDFontType 2, through CIDMap). +pub fn cid_glyph(ip: &mut Interp, cidfont: &PDict, cid: u32) -> Option<Glyph> { + if let Some((set, k)) = cff_of(ip, cidfont) { + let gid = set.gid_of_cid(k, cid).unwrap_or(0); + return set.glyph(k, gid); + } + if cidfont.get_name(b"CIDFontType").and_then(|o| o.num()) == Some(2.0) { + let gid = match cidfont.get_name(b"CIDMap") { + Some(Obj::Int(off)) => u32::try_from(i64::from(cid) + off).ok()?, + Some(Obj::Dict(m)) => m.get(&Key::Int(i64::from(cid))).and_then(|o| o.num()).map_or(0, |v| v as u32), + Some(Obj::Str(s, _)) => gid_from(&[&s], cidfont, cid), + Some(Obj::Array(a, _)) => { + let strs: Vec<PStr> = a.items().into_iter().filter_map(|o| if let Obj::Str(s, _) = o { Some(s) } else { None }).collect(); + gid_from(&strs.iter().collect::<Vec<_>>(), cidfont, cid) + } + _ => cid, + }; + let data = crate::read::type42::sfnts(cidfont)?; + return crate::read::type42::glyph(&data, gid); + } + None +} + +/// A glyph index read from CIDMap strings (GDBytes bytes per CID, across the strings). +fn gid_from(strs: &[&PStr], cidfont: &PDict, cid: u32) -> u32 { + let gd = cidfont.get_name(b"GDBytes").and_then(|o| o.num()).unwrap_or(2.0).clamp(1.0, 4.0) as usize; + let mut at = (cid as usize).saturating_mul(gd); + for s in strs { + if at < s.len { + return (0..gd).fold(0u32, |a, k| a << 8 | u32::from(s.get(at + k).unwrap_or(0))); + } + at -= s.len; + } + 0 +} + +/// The ProcSets EPS files ask for, and the identity CMaps. +pub fn install(ip: &mut Interp) { + let procsets = category(ip, b"ProcSet"); + let fsi = PDict::new(2); + if let Some(op) = crate::read::ops::op_id(b"StartData") { + fsi.put_name(b"StartData", Obj::Op(op)); + } + procsets.put_name(b"FontSetInit", Obj::Dict(fsi)); + let cid = PDict::new(24); + for n in [ + "begincmap", + "endcmap", + "usecmap", + "begincodespacerange", + "endcodespacerange", + "begincidrange", + "endcidrange", + "begincidchar", + "endcidchar", + "beginbfchar", + "endbfchar", + "beginbfrange", + "endbfrange", + "beginnotdefrange", + "endnotdefrange", + "beginnotdefchar", + "endnotdefchar", + ] { + if let Some(op) = crate::read::ops::op_id(n.as_bytes()) { + cid.put_name(n.as_bytes(), Obj::Op(op)); + } + } + procsets.put_name(b"CIDInit", Obj::Dict(cid)); + let cmaps = category(ip, b"CMap"); + for n in [&b"Identity-H"[..], b"Identity-V"] { + let d = identity(ip, n); + cmaps.put_name(n, Obj::Dict(d)); + } +} diff --git a/crates/ps/src/read/encodings.rs b/crates/ps/src/read/encodings.rs new file mode 100644 index 000000000..7ed3ff253 --- /dev/null +++ b/crates/ps/src/read/encodings.rs @@ -0,0 +1,318 @@ +//! The two encodings every interpreter provides (PostScript Language Reference, Appendix E). + +/// Glyph names for codes 32–126, shared by both encodings except where noted. +const ASCII: [&str; 95] = [ + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", +]; + +const STANDARD_HIGH: &[(u8, &str)] = &[ + (161, "exclamdown"), + (162, "cent"), + (163, "sterling"), + (164, "fraction"), + (165, "yen"), + (166, "florin"), + (167, "section"), + (168, "currency"), + (169, "quotesingle"), + (170, "quotedblleft"), + (171, "guillemotleft"), + (172, "guilsinglleft"), + (173, "guilsinglright"), + (174, "fi"), + (175, "fl"), + (177, "endash"), + (178, "dagger"), + (179, "daggerdbl"), + (180, "periodcentered"), + (182, "paragraph"), + (183, "bullet"), + (184, "quotesinglbase"), + (185, "quotedblbase"), + (186, "quotedblright"), + (187, "guillemotright"), + (188, "ellipsis"), + (189, "perthousand"), + (191, "questiondown"), + (193, "grave"), + (194, "acute"), + (195, "circumflex"), + (196, "tilde"), + (197, "macron"), + (198, "breve"), + (199, "dotaccent"), + (200, "dieresis"), + (202, "ring"), + (203, "cedilla"), + (205, "hungarumlaut"), + (206, "ogonek"), + (207, "caron"), + (208, "emdash"), + (225, "AE"), + (227, "ordfeminine"), + (232, "Lslash"), + (233, "Oslash"), + (234, "OE"), + (235, "ordmasculine"), + (241, "ae"), + (245, "dotlessi"), + (248, "lslash"), + (249, "oslash"), + (250, "oe"), + (251, "germandbls"), +]; + +/// ISOLatin1Encoding: accents at 144–159, then ISO 8859-1 from 160. +const LATIN1_HIGH: [&str; 112] = [ + "dotlessi", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + ".notdef", + "ring", + "cedilla", + ".notdef", + "hungarumlaut", + "ogonek", + "caron", + "space", + "exclamdown", + "cent", + "sterling", + "currency", + "yen", + "brokenbar", + "section", + "dieresis", + "copyright", + "ordfeminine", + "guillemotleft", + "logicalnot", + "hyphen", + "registered", + "macron", + "degree", + "plusminus", + "twosuperior", + "threesuperior", + "acute", + "mu", + "paragraph", + "periodcentered", + "cedilla", + "onesuperior", + "ordmasculine", + "guillemotright", + "onequarter", + "onehalf", + "threequarters", + "questiondown", + "Agrave", + "Aacute", + "Acircumflex", + "Atilde", + "Adieresis", + "Aring", + "AE", + "Ccedilla", + "Egrave", + "Eacute", + "Ecircumflex", + "Edieresis", + "Igrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Eth", + "Ntilde", + "Ograve", + "Oacute", + "Ocircumflex", + "Otilde", + "Odieresis", + "multiply", + "Oslash", + "Ugrave", + "Uacute", + "Ucircumflex", + "Udieresis", + "Yacute", + "Thorn", + "germandbls", + "agrave", + "aacute", + "acircumflex", + "atilde", + "adieresis", + "aring", + "ae", + "ccedilla", + "egrave", + "eacute", + "ecircumflex", + "edieresis", + "igrave", + "iacute", + "icircumflex", + "idieresis", + "eth", + "ntilde", + "ograve", + "oacute", + "ocircumflex", + "otilde", + "odieresis", + "divide", + "oslash", + "ugrave", + "uacute", + "ucircumflex", + "udieresis", + "yacute", + "thorn", + "ydieresis", +]; + +pub fn standard() -> Vec<&'static str> { + let mut v = vec![".notdef"; 256]; + for (i, n) in ASCII.iter().enumerate() { + if let Some(slot) = v.get_mut(32 + i) { + *slot = n; + } + } + for (c, n) in STANDARD_HIGH { + if let Some(slot) = v.get_mut(usize::from(*c)) { + *slot = n; + } + } + v +} + +pub fn iso_latin1() -> Vec<&'static str> { + let mut v = vec![".notdef"; 256]; + for (i, n) in ASCII.iter().enumerate() { + if let Some(slot) = v.get_mut(32 + i) { + *slot = n; + } + } + // Latin-1 differs from Standard at the minus sign. + if let Some(slot) = v.get_mut(45) { + *slot = "minus"; + } + for (i, n) in LATIN1_HIGH.iter().enumerate() { + if let Some(slot) = v.get_mut(144 + i) { + *slot = n; + } + } + v +} + +#[cfg(test)] +mod tests { + #[test] + fn encodings_place_their_glyphs() { + let s = super::standard(); + assert_eq!((s[65], s[39], s[251], s[200]), ("A", "quoteright", "germandbls", "dieresis")); + let l = super::iso_latin1(); + assert_eq!((l[228], l[45], l[173], l[223], l[255]), ("adieresis", "minus", "hyphen", "germandbls", "ydieresis")); + } +} diff --git a/crates/ps/src/read/font.rs b/crates/ps/src/read/font.rs new file mode 100644 index 000000000..9a1af3fb6 --- /dev/null +++ b/crates/ps/src/read/font.rs @@ -0,0 +1,751 @@ +//! Fonts: dictionaries, scaling, and showing text. Type 3 fonts draw through their BuildGlyph +//! or BuildChar procedures; other font types advance by their widths (or an estimate) without +//! drawing until their glyph programs are read. + +use crate::read::gstate::M; +use crate::read::interp::{Interp, PsErr, R, err, matrix_obj}; +use crate::read::obj::{Key, Obj, PArr, PDict, PStr, name}; + +fn font_matrix(d: &PDict) -> M { + match d.get_name(b"FontMatrix") { + Some(Obj::Array(a, _)) => crate::read::interp::matrix_of(&a).unwrap_or(M([0.001, 0.0, 0.0, 0.001, 0.0, 0.0])), + _ => M([0.001, 0.0, 0.0, 0.001, 0.0, 0.0]), + } +} + +/// A stand-in for a font the file doesn't carry: a Type 1 shell with StandardEncoding. +fn substitute(ip: &mut Interp, font_name: &[u8]) -> R<PDict> { + if let Some(bytes) = ip.limits.fallback_font.and_then(|provider| provider(font_name)) + && let Some(d) = substitute_type42(ip, font_name, bytes)? + { + add_fid(ip, &d); + return Ok(d); + } + let d = PDict::new(12); + d.put_name(b"FontName", Obj::lit(font_name)); + d.put_name(b"FontType", Obj::Int(1)); + d.put_name(b"FontMatrix", matrix_obj(&M([0.001, 0.0, 0.0, 0.001, 0.0, 0.0]))); + d.put_name(b"FontBBox", Obj::Array(PArr::new(vec![Obj::Int(0), Obj::Int(-200), Obj::Int(1000), Obj::Int(900)]), false)); + d.put_name(b"PaintType", Obj::Int(0)); + if let Some(enc) = ip.systemdict.get_name(b"StandardEncoding") { + d.put_name(b"Encoding", enc); + } + d.put_name(b"CharStrings", Obj::Dict(PDict::new(1))); + d.put_name(b"Private", Obj::Dict(PDict::new(1))); + d.put_name(b"CraftPsSubstitute", Obj::Bool(true)); + add_fid(ip, &d); + Ok(d) +} + +fn substitute_type42(ip: &mut Interp, font_name: &[u8], bytes: &[u8]) -> R<Option<PDict>> { + use skrifa::MetadataProvider; + + let Ok(font) = skrifa::FontRef::new(bytes) else { return Ok(None) }; + let cmap = font.charmap(); + let charstrings = PDict::new(256); + for glyph_name in crate::read::encodings::standard() { + let Some(ch) = standard_glyph_char(glyph_name.as_bytes()) else { continue }; + let Some(gid) = cmap.map(ch) else { continue }; + charstrings.put(Obj::lit(glyph_name.as_bytes()), Obj::Int(i64::from(gid.to_u32()))); + } + ip.alloc(bytes.len().saturating_add(bytes.len() % 2))?; + let mut sfnt = bytes.to_vec(); + if sfnt.len() % 2 == 1 { + sfnt.push(0); + } + let d = PDict::new(12); + d.put_name(b"FontName", Obj::lit(font_name)); + d.put_name(b"FontType", Obj::Int(42)); + // Type 42 outlines are emitted in normalized em units by `type42::glyph`, unlike the + // 1000-unit CharStrings convention used by Type 1 fonts. + d.put_name(b"FontMatrix", matrix_obj(&M([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]))); + d.put_name(b"FontBBox", Obj::Array(PArr::new(vec![Obj::Int(0), Obj::Int(-200), Obj::Int(1000), Obj::Int(900)]), false)); + d.put_name(b"PaintType", Obj::Int(0)); + if let Some(enc) = ip.systemdict.get_name(b"StandardEncoding") { + d.put_name(b"Encoding", enc); + } + d.put_name(b"CharStrings", Obj::Dict(charstrings)); + d.put_name(b"sfnts", Obj::Array(PArr::new(vec![Obj::Str(PStr::new(sfnt), false)]), false)); + Ok(Some(d)) +} + +fn standard_glyph_char(name: &[u8]) -> Option<char> { + if name.len() == 1 && name[0].is_ascii() { + return Some(char::from(name[0])); + } + Some(match name { + b"space" => ' ', + b"exclam" => '!', + b"quotedbl" => '"', + b"numbersign" => '#', + b"dollar" => '$', + b"percent" => '%', + b"ampersand" => '&', + b"quoteright" => '’', + b"parenleft" => '(', + b"parenright" => ')', + b"asterisk" => '*', + b"plus" => '+', + b"comma" => ',', + b"hyphen" => '-', + b"period" => '.', + b"slash" => '/', + b"colon" => ':', + b"semicolon" => ';', + b"less" => '<', + b"equal" => '=', + b"greater" => '>', + b"question" => '?', + b"at" => '@', + b"bracketleft" => '[', + b"backslash" => '\\', + b"bracketright" => ']', + b"asciicircum" => '^', + b"underscore" => '_', + b"quoteleft" => '‘', + b"braceleft" => '{', + b"bar" => '|', + b"braceright" => '}', + b"asciitilde" => '~', + b"zero" => '0', + b"one" => '1', + b"two" => '2', + b"three" => '3', + b"four" => '4', + b"five" => '5', + b"six" => '6', + b"seven" => '7', + b"eight" => '8', + b"nine" => '9', + b"exclamdown" => '¡', + b"cent" => '¢', + b"sterling" => '£', + b"fraction" => '⁄', + b"yen" => '¥', + b"florin" => 'ƒ', + b"section" => '§', + b"currency" => '¤', + b"quotesingle" => '\'', + b"quotedblleft" => '“', + b"guillemotleft" => '«', + b"guilsinglleft" => '‹', + b"guilsinglright" => '›', + b"fi" => '\u{fb01}', + b"fl" => '\u{fb02}', + b"endash" => '–', + b"dagger" => '†', + b"daggerdbl" => '‡', + b"periodcentered" => '·', + b"paragraph" => '¶', + b"bullet" => '•', + b"quotesinglbase" => '‚', + b"quotedblbase" => '„', + b"quotedblright" => '”', + b"guillemotright" => '»', + b"ellipsis" => '…', + b"perthousand" => '‰', + b"questiondown" => '¿', + b"grave" => '`', + b"acute" => '´', + b"circumflex" => 'ˆ', + b"tilde" => '˜', + b"macron" => '¯', + b"breve" => '˘', + b"dotaccent" => '˙', + b"dieresis" => '¨', + b"ring" => '˚', + b"cedilla" => '¸', + b"hungarumlaut" => '˝', + b"ogonek" => '˛', + b"caron" => 'ˇ', + b"emdash" => '—', + b"AE" => 'Æ', + b"ordfeminine" => 'ª', + b"Lslash" => 'Ł', + b"Oslash" => 'Ø', + b"OE" => 'Œ', + b"ordmasculine" => 'º', + b"ae" => 'æ', + b"dotlessi" => 'ı', + b"lslash" => 'ł', + b"oslash" => 'ø', + b"oe" => 'œ', + b"germandbls" => 'ß', + _ => return None, + }) +} + +pub(crate) fn add_fid(ip: &mut Interp, d: &PDict) { + if !d.known(&Key::Name(name(b"FID"))) { + d.put_name(b"FID", Obj::FontId(ip.next_fid)); + ip.next_fid += 1; + } +} + +pub fn find_font(ip: &mut Interp, key: &Obj) -> R<PDict> { + if let Some(Obj::Dict(d)) = ip.fontdir.get(&key.key()) { + return Ok(d); + } + if let Some(Obj::Dict(fonts)) = ip.resources.get_name(b"Font") + && let Some(Obj::Dict(d)) = fonts.get(&key.key()) + { + return Ok(d); + } + // An embedded Type 1 program can leave its FontName dictionary active after eexec without + // issuing definefont. Resolve that in-scope font before substituting a stand-in. + let active = + ip.d.iter() + .rev() + .find(|font| font.get_name(b"FontName").is_some_and(|n| n.key() == key.key()) && font.get_name(b"CharStrings").is_some()) + .cloned(); + if let Some(d) = active { + add_fid(ip, &d); + return Ok(d); + } + let n = crate::read::ops::basic::text_of(key); + if let Some(d) = crate::read::composite::compose_by_name(ip, &n) { + return Ok(d); + } + let d = substitute(ip, &n)?; + ip.fontdir.put(key.clone(), Obj::Dict(d.clone())); + Ok(d) +} + +pub fn findfont(ip: &mut Interp) -> R { + let k = ip.pop()?; + let d = find_font(ip, &k)?; + ip.push(Obj::Dict(d)) +} + +pub fn definefont(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + let k = ip.pop()?; + add_fid(ip, &d); + ip.fontdir.put(k, Obj::Dict(d.clone())); + ip.push(Obj::Dict(d)) +} + +pub fn undefinefont(ip: &mut Interp) -> R { + let k = ip.pop()?; + ip.fontdir.remove(&k.key()); + Ok(()) +} + +/// A copy of a font dictionary with its FontMatrix replaced (and a new FID). +fn transformed(ip: &mut Interp, d: &PDict, m: &M) -> PDict { + let copy = PDict::new(d.len() + 2); + for (k, v) in d.entries() { + copy.put(k, v); + } + copy.put_name(b"FontMatrix", matrix_obj(&font_matrix(d).then(m))); + copy.put_name(b"FID", Obj::FontId(ip.next_fid)); + ip.next_fid += 1; + copy +} + +pub fn scalefont(ip: &mut Interp) -> R { + let s = ip.pop_num()?; + let d = ip.pop_dict()?; + let f = transformed(ip, &d, &M([s, 0.0, 0.0, s, 0.0, 0.0])); + ip.push(Obj::Dict(f)) +} + +pub fn makefont(ip: &mut Interp) -> R { + let m = ip.pop_matrix()?; + let d = ip.pop_dict()?; + let f = transformed(ip, &d, &m); + ip.push(Obj::Dict(f)) +} + +pub fn setfont(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + ip.gs.font = Some(d); + Ok(()) +} + +pub fn currentfont(ip: &mut Interp) -> R { + let f = match ip.gs.font.clone() { + Some(f) => f, + None => find_font(ip, &Obj::lit(b"Courier"))?, + }; + ip.push(Obj::Dict(f)) +} + +pub fn selectfont(ip: &mut Interp) -> R { + let m = match ip.pop()? { + Obj::Array(a, _) => crate::read::interp::matrix_of(&a)?, + o => { + let s = o.num().ok_or(PsErr::Ps("typecheck"))?; + M([s, 0.0, 0.0, s, 0.0, 0.0]) + } + }; + let k = ip.pop()?; + let d = match k { + Obj::Dict(d) => d, + k => find_font(ip, &k)?, + }; + let f = transformed(ip, &d, &m); + ip.gs.font = Some(f); + Ok(()) +} + +/// The glyph name for a character code through the font's Encoding. +fn glyph_name(font: &PDict, code: u8) -> Vec<u8> { + match font.get_name(b"Encoding") { + Some(Obj::Array(a, _)) => match a.get(usize::from(code)) { + Some(Obj::Name(n, _)) => n.to_vec(), + _ => b".notdef".to_vec(), + }, + _ => b".notdef".to_vec(), + } +} + +/// Unicode text represented by the simple font's selected glyph names. Unknown names have no +/// honest replacement text, so callers must omit ActualText rather than infer from input bytes. +fn actual_text(font: &PDict, bytes: &[u8]) -> Option<String> { + bytes.iter().map(|code| standard_glyph_char(&glyph_name(font, *code)).map(|c| c.to_string())).collect() +} + +/// A glyph's advance from the font's Metrics or CharStrings-free estimate, in glyph space. +fn estimated_width(font: &PDict, code: u8) -> (f64, f64) { + let g = glyph_name(font, code); + if let Some(Obj::Dict(m)) = font.get_name(b"Metrics") + && let Some(v) = m.get(&Key::Name(name(&g))) + { + match v { + Obj::Array(a, _) if a.len >= 2 => { + let n: Vec<f64> = a.items().iter().filter_map(Obj::num).collect(); + // The last two numbers are the width (an entry without two numbers gives none). + let w = n.len().checked_sub(2).and_then(|i| n.get(i)).copied().unwrap_or(0.0); + return (w, n.last().copied().unwrap_or(0.0)); + } + o => return (o.num().unwrap_or(0.0), 0.0), + } + } + // An average glyph: half the em, as glyph space usually has 1000 units to it. + let em = 1.0 / font_matrix(font).0[0].abs().max(1e-6); + (if code == b' ' { 0.25 } else { 0.5 } * em, 0.0) +} + +/// A Type 1 glyph of `font` (cached), None for fonts without charstrings. +fn outline(ip: &mut Interp, font: &PDict, code: u8) -> Option<std::rc::Rc<crate::read::type1::Glyph>> { + if font.get_name(b"CraftPsSubstitute").is_some() { + return None; + } + let fid = match font.get_name(b"FID") { + Some(Obj::FontId(f)) => f, + _ => 0, + }; + let g = glyph_name(font, code); + if let Some(hit) = ip.glyphs.get(&(fid, g.clone())) { + return Some(hit.clone()); + } + let glyph = if let Some((set, k)) = crate::read::composite::cff_of(ip, font) { + let gid = match font.get_name(b"CharStrings") { + Some(Obj::Dict(cs)) => cs.get(&Key::Name(name(&g))).and_then(|o| o.num()).map_or(0, |v| v as u32), + _ => 0, + }; + std::rc::Rc::new(set.glyph(k, gid)?) + } else if font.get_name(b"FontType").and_then(|o| o.num()) == Some(42.0) { + let data = match ip.sfnts.get(&fid) { + Some(d) => d.clone(), + None => { + let d = std::rc::Rc::new(crate::read::type42::sfnts(font)?); + if ip.sfnts.len() < 256 { + ip.sfnts.insert(fid, d.clone()); + } + d + } + }; + std::rc::Rc::new(crate::read::type42::glyph(&data, crate::read::type42::glyph_index(font, &g))?) + } else { + let std = crate::read::encodings::standard(); + std::rc::Rc::new(crate::read::type1::glyph(font, &g, &std)?) + }; + // Running the glyph's program was work; failing to charge it ends the run at the next step. + let _ = ip.charge(glyph.cost as u64 / 4 + 1); + let _ = ip.alloc(glyph.path.len().saturating_mul(crate::read::interp::SEG_BYTES)); + if ip.glyphs.len() < 100_000 { + ip.glyphs.insert((fid, g), glyph.clone()); + } + Some(glyph) +} + +/// A CID's glyph in a CIDFont (cached by font and CID). +fn cid_outline(ip: &mut Interp, font: &PDict, cid: u32) -> Option<std::rc::Rc<crate::read::type1::Glyph>> { + let fid = match font.get_name(b"FID") { + Some(Obj::FontId(f)) => f, + _ => 0, + }; + let key = (fid, format!("\0cid{cid}").into_bytes()); + if let Some(hit) = ip.glyphs.get(&key) { + return Some(hit.clone()); + } + let g = std::rc::Rc::new(crate::read::composite::cid_glyph(ip, font, cid)?); + let _ = ip.charge(g.cost as u64 / 4 + 1); + let _ = ip.alloc(g.path.len().saturating_mul(crate::read::interp::SEG_BYTES)); + if ip.glyphs.len() < 100_000 { + ip.glyphs.insert(key, g.clone()); + } + Some(g) +} + +/// Where a glyph at the current point lands: glyph space (through `fm`) → device space. `v` +/// moves the glyph's origin (vertical writing hangs a glyph from its vertical origin). +fn glyph_to_device(ip: &Interp, fm: &M, v: (f64, f64)) -> R<M> { + let (x, y) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let (ux, uy) = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?.apply(x, y); + Ok(M([1.0, 0.0, 0.0, 1.0, -v.0, -v.1]).then(fm).then(&M([1.0, 0.0, 0.0, 1.0, ux, uy])).then(&ip.gs.ctm)) +} + +/// Run one Type 3 glyph at the current point: its advance in glyph space. +fn type3_glyph(ip: &mut Interp, font: &PDict, code: u8) -> R<(f64, f64)> { + let (x, y) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let fm = font_matrix(font); + ip.gsave()?; + let r = (|| -> R<(f64, f64)> { + let (ux, uy) = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?.apply(x, y); + ip.gs.ctm = fm.then(&M([1.0, 0.0, 0.0, 1.0, ux, uy]).then(&ip.gs.ctm)); + ip.gs.path.clear(); + ip.gs.cur = None; + ip.gs.char_width = None; + if let Some(bg) = font.get_name(b"BuildGlyph") { + ip.push(Obj::Dict(font.clone()))?; + ip.push(Obj::lit(&glyph_name(font, code)))?; + ip.call(bg)?; + } else if let Some(bc) = font.get_name(b"BuildChar") { + ip.push(Obj::Dict(font.clone()))?; + ip.push(Obj::Int(i64::from(code)))?; + ip.call(bc)?; + } + Ok(ip.gs.char_width.unwrap_or((0.0, 0.0))) + })(); + ip.grestore(); + r +} + +/// What a glyph adds to (or, for `xshow`, replaces) its advance: given the code and its index. +type PerGlyph<'a> = dyn FnMut(&mut Interp, u32, usize) -> R<(f64, f64)> + 'a; + +/// Show (or, with `draw` false, measure) a string: the total advance in user space. +/// `per_char` gives each glyph's extra displacement (or, with `replace`, its whole advance). +fn show_glyphs(ip: &mut Interp, s: &[u8], draw: bool, replace: bool, per_char: &mut PerGlyph<'_>) -> R<(f64, f64)> { + let font = match ip.gs.font.clone() { + Some(f) => f, + None => return err("invalidfont"), + }; + let vertical = crate::read::composite::vertical(ip, &font); + // The list of glyphs is made first: at most one per byte. + ip.alloc(s.len().saturating_mul(GLYPH_JOB_BYTES))?; + let jobs: Vec<(u32, PDict, M, crate::read::composite::Key2)> = if font.get_name(b"FontType").and_then(|o| o.num()) == Some(0.0) { + crate::read::composite::decode(ip, &font, s)? + } else { + let fm = font_matrix(&font); + s.iter().map(|c| (u32::from(*c), font.clone(), fm, crate::read::composite::Key2::Code(*c))).collect() + }; + let mut total = (0.0, 0.0); + let mut text_paths: Vec<(Vec<crate::read::gstate::Seg>, crate::read::gstate::DevColor)> = Vec::new(); + let mut text_segments = 0usize; + let result = (|| -> R<(f64, f64)> { + for (i, (code, leaf, fm, key)) in jobs.into_iter().enumerate() { + let type3 = leaf.get_name(b"FontType").and_then(|o| o.num()) == Some(3.0); + let w = match key { + crate::read::composite::Key2::Code(c) if type3 => { + // Type 3 glyph procedures paint immediately. Commit any earlier staged + // outlines first so their paint order remains the same as the input string. + let pending = std::mem::take(&mut text_paths); + if !ip.gs.nulldev { + for (path, color) in pending { + ip.out.fill(&ip.gs.clip, &path, false, color).map_err(PsErr::Fatal)?; + } + } + ip.charge(GLYPH_STEPS)?; + if draw && ip.gs.cur.is_some() { + type3_glyph(ip, &leaf, c)? + } else { + let saved = ip.gs.nulldev; + ip.gs.nulldev = true; + if ip.gs.cur.is_none() { + ip.gs.cur = Some((0.0, 0.0)); + } + let w = type3_glyph(ip, &leaf, c); + ip.gs.nulldev = saved; + w? + } + } + key => { + let cid = match key { + crate::read::composite::Key2::Cid(cid) => Some(cid), + crate::read::composite::Key2::Code(_) => None, + }; + let g = match key { + crate::read::composite::Key2::Code(c) => outline(ip, &leaf, c), + crate::read::composite::Key2::Cid(cid) => cid_outline(ip, &leaf, cid), + }; + // Empty outlines (usually spaces) still advance but need little work; their + // outline cache/decoder has already charged what it actually did. + ip.charge(if g.as_ref().is_some_and(|g| g.path.is_empty()) { 1 } else { GLYPH_STEPS })?; + // Vertical writing: the glyph hangs from its vertical origin and advances down. + let em = 1.0 / font_matrix(&leaf).0[3].abs().max(1e-9); + let vmetrics = match (vertical, &g) { + (true, Some(g)) => Some(crate::read::composite::vertical_metrics(&leaf, cid.unwrap_or(0), g.width.0, em)), + (true, None) => Some(crate::read::composite::vertical_metrics(&leaf, cid.unwrap_or(0), em, em)), + _ => None, + }; + let origin = vmetrics.map_or((0.0, 0.0), |(_, v)| v); + match g { + Some(g) => { + if draw && !g.path.is_empty() && ip.gs.cur.is_some() { + ip.charge_path(g.path.len())?; + let m = glyph_to_device(ip, &fm, origin)?; + let path: Vec<crate::read::gstate::Seg> = g.path.iter().map(|s| s.map(&m)).collect(); + if ip.charpath { + if ip.gs.path.len().saturating_add(path.len()) > crate::read::gstate::MAX_PATH { + return Err(PsErr::Fatal("PostScript (path limit)".into())); + } + ip.gs.path.extend(path); + } else { + if text_segments.saturating_add(path.len()) > crate::read::gstate::MAX_PATH { + return Err(PsErr::Fatal("PostScript (path limit)".into())); + } + text_segments += path.len(); + if matches!(ip.gs.space, crate::read::gstate::Space::Pattern) { + // Pattern fills execute a cell program. Keep them on the normal + // path until their deferred representation is prepared. + crate::read::ops::gfx::fill_path(ip, &path, false)?; + } else { + let color = crate::read::ops::gfx::current_color(ip)?; + // Charge the fill work before staging it so completed glyphs + // can still be committed if a later glyph hits the budget. + ip.charge(path.len() as u64 / 4 + 1)?; + text_paths.push((path, color)); + } + } + } + match (vmetrics, leaf.get_name(b"Metrics"), key_code(code)) { + (Some((w1, _)), _, _) => w1, + (None, Some(_), Some(c)) => estimated_width(&leaf, c), + _ => g.width, + } + } + None => match vmetrics { + Some((w1, _)) => w1, + None => estimated_width(&leaf, key_code(code).unwrap_or(0)), + }, + } + } + }; + let (wx, wy) = fm.delta(w.0, w.1); + let (ex, ey) = per_char(ip, code, i)?; + let (dx, dy) = if replace { (ex, ey) } else { (wx + ex, wy + ey) }; + total = (total.0 + dx, total.1 + dy); + if draw && let Some((cx, cy)) = ip.gs.cur { + let (ddx, ddy) = ip.gs.ctm.delta(dx, dy); + ip.gs.cur = Some((cx + ddx, cy + ddy)); + } + } + Ok(total) + })(); + let path_limit = matches!(&result, Err(PsErr::Fatal(message)) if message == "PostScript (path limit)"); + if (result.is_ok() || !path_limit) && !ip.gs.nulldev { + for (path, color) in text_paths { + ip.out.fill(&ip.gs.clip, &path, false, color).map_err(PsErr::Fatal)?; + } + } + result +} + +/// What showing one glyph costs, in steps (it takes about ten times a plain operator), and the +/// memory its place in the list of glyphs takes. +const GLYPH_STEPS: u64 = 10; +const GLYPH_JOB_BYTES: usize = 96; + +fn key_code(code: u32) -> Option<u8> { + u8::try_from(code).ok() +} + +fn show_string(ip: &mut Interp, s: &[u8], draw: bool, per_char: &mut PerGlyph<'_>) -> R<(f64, f64)> { + // Whitespace-only shows advance the text position but emit no painted glyphs; avoid bloating + // the content stream with an empty semantic marked-content wrapper for them. + let text = ip.gs.font.as_ref().and_then(|font| actual_text(font, s)); + if draw + && !ip.charpath + && let Some(text) = text.filter(|text| text.chars().any(|c| !c.is_whitespace())) + { + ip.out.begin_actual_text(&text); + let result = show_glyphs(ip, s, draw, false, per_char); + ip.out.end_actual_text(); + result + } else { + show_glyphs(ip, s, draw, false, per_char) + } +} + +pub fn show(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + if ip.gs.cur.is_none() { + return err("nocurrentpoint"); + } + show_string(ip, &s, true, &mut |_, _, _| Ok((0.0, 0.0))).map(|_| ()) +} + +pub fn ashow(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let ay = ip.pop_num()?; + let ax = ip.pop_num()?; + show_string(ip, &s, true, &mut |_, _, _| Ok((ax, ay))).map(|_| ()) +} + +pub fn widthshow(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let ch = ip.pop_int()?; + let cy = ip.pop_num()?; + let cx = ip.pop_num()?; + show_string(ip, &s, true, &mut |_, c, _| Ok(if i64::from(c) == ch { (cx, cy) } else { (0.0, 0.0) })).map(|_| ()) +} + +pub fn awidthshow(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let ay = ip.pop_num()?; + let ax = ip.pop_num()?; + let ch = ip.pop_int()?; + let cy = ip.pop_num()?; + let cx = ip.pop_num()?; + show_string(ip, &s, true, &mut |_, c, _| Ok(if i64::from(c) == ch { (cx + ax, cy + ay) } else { (ax, ay) })).map(|_| ()) +} + +/// `xshow`, `yshow`, `xyshow`: explicit displacements replace the widths. +fn explicit_show(ip: &mut Interp, xs: bool, ys: bool) -> R { + let disp: Vec<f64> = match ip.pop()? { + Obj::Array(a, _) => a.items().iter().filter_map(Obj::num).collect(), + // An encoded number string is rare in EPS: the glyphs' own widths then. + Obj::Str(_, _) => Vec::new(), + _ => return err("typecheck"), + }; + let s = ip.pop_str()?.bytes(); + if ip.gs.cur.is_none() { + return err("nocurrentpoint"); + } + let step = if xs && ys { 2 } else { 1 }; + show_glyphs(ip, &s, true, true, &mut |_, _, i| { + let d = |k: usize| disp.get(i * step + k).copied().unwrap_or(0.0); + Ok(match (xs, ys) { + (true, true) => (d(0), d(1)), + (true, false) => (d(0), 0.0), + _ => (0.0, d(0)), + }) + }) + .map(|_| ()) +} + +pub fn xshow(ip: &mut Interp) -> R { + explicit_show(ip, true, false) +} + +pub fn yshow(ip: &mut Interp) -> R { + explicit_show(ip, false, true) +} + +pub fn xyshow(ip: &mut Interp) -> R { + explicit_show(ip, true, true) +} + +pub fn kshow(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let proc = ip.pop()?; + for (i, c) in s.iter().enumerate() { + show_string(ip, &[*c], true, &mut |_, _, _| Ok((0.0, 0.0)))?; + if let Some(next) = s.get(i + 1) { + ip.push(Obj::Int(i64::from(*c)))?; + ip.push(Obj::Int(i64::from(*next)))?; + ip.call(proc.clone())?; + } + } + Ok(()) +} + +pub fn cshow(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let proc = ip.pop()?; + for c in s { + let (wx, wy) = show_string(ip, &[c], false, &mut |_, _, _| Ok((0.0, 0.0)))?; + ip.push(Obj::Int(i64::from(c)))?; + ip.push(Obj::Real(wx))?; + ip.push(Obj::Real(wy))?; + ip.call(proc.clone())?; + } + Ok(()) +} + +pub fn glyphshow(ip: &mut Interp) -> R { + let _ = ip.pop()?; + // Advance by an average glyph. + let font = ip.gs.font.clone().ok_or(PsErr::Ps("invalidfont"))?; + let (wx, wy) = font_matrix(&font).delta(500.0, 0.0); + if let Some((cx, cy)) = ip.gs.cur { + let (dx, dy) = ip.gs.ctm.delta(wx, wy); + ip.gs.cur = Some((cx + dx, cy + dy)); + } + Ok(()) +} + +pub fn stringwidth(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let (wx, wy) = show_string(ip, &s, false, &mut |_, _, _| Ok((0.0, 0.0)))?; + ip.push(Obj::Real(wx))?; + ip.push(Obj::Real(wy)) +} + +pub fn charpath(ip: &mut Interp) -> R { + let _stroke = ip.pop_bool()?; + let s = ip.pop_str()?.bytes(); + let saved = ip.charpath; + ip.charpath = true; + let cur = ip.gs.cur; + let r = show_string(ip, &s, true, &mut |_, _, _| Ok((0.0, 0.0))); + ip.charpath = saved; + // The path ends at the advanced point. + if let (Some(p), Ok(_)) = (ip.gs.cur, &r) { + ip.gs.path.push(crate::read::gstate::Seg::Move(p.0, p.1)); + ip.gs.start = Some(p); + } + let _ = cur; + r.map(|_| ()) +} + +pub fn setcharwidth(ip: &mut Interp) -> R { + let wy = ip.pop_num()?; + let wx = ip.pop_num()?; + ip.gs.char_width = Some((wx, wy)); + Ok(()) +} + +pub fn setcachedevice(ip: &mut Interp) -> R { + for _ in 0..4 { + ip.pop_num()?; + } + setcharwidth(ip) +} + +/// `w0x w0y llx lly urx ury w1x w1y vx vy setcachedevice2`: the mode-0 width counts. +pub fn setcachedevice2(ip: &mut Interp) -> R { + for _ in 0..8 { + ip.pop_num()?; + } + setcharwidth(ip) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn standard_encoding_glyph_names_have_unicode_text() { + assert_eq!(standard_glyph_char(b"emdash"), Some('—')); + assert_eq!(standard_glyph_char(b"fi"), Some('\u{fb01}')); + assert_eq!(standard_glyph_char(b"sterling"), Some('£')); + assert_eq!(standard_glyph_char(b"quoteleft"), Some('‘')); + assert_eq!(standard_glyph_char(b"quoteright"), Some('’')); + assert_eq!(standard_glyph_char(b"unmapped.custom"), None); + } +} diff --git a/crates/ps/src/read/gstate.rs b/crates/ps/src/read/gstate.rs new file mode 100644 index 000000000..2b62f9180 --- /dev/null +++ b/crates/ps/src/read/gstate.rs @@ -0,0 +1,399 @@ +//! The graphics state: transformation, current path (kept in device space, as PostScript +//! defines it), colour, line parameters and clipping. + +use std::rc::Rc; + +use crate::read::obj::{Obj, PDict}; + +/// An affine matrix `[a b c d e f]`: (x, y) → (a·x + c·y + e, b·x + d·y + f). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct M(pub [f64; 6]); + +impl M { + pub const ID: M = M([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + + /// `self` first, then `o` (PostScript's `concat` is `m · CTM`). + pub fn then(&self, o: &M) -> M { + let [a, b, c, d, e, f] = self.0; + let [p, q, r, s, t, u] = o.0; + M([a * p + b * r, a * q + b * s, c * p + d * r, c * q + d * s, e * p + f * r + t, e * q + f * s + u]) + } + + pub fn apply(&self, x: f64, y: f64) -> (f64, f64) { + let [a, b, c, d, e, f] = self.0; + (a * x + c * y + e, b * x + d * y + f) + } + + pub fn delta(&self, x: f64, y: f64) -> (f64, f64) { + let [a, b, c, d, ..] = self.0; + (a * x + c * y, b * x + d * y) + } + + pub fn inv(&self) -> Option<M> { + let [a, b, c, d, e, f] = self.0; + let det = a * d - b * c; + if det == 0.0 || !det.is_finite() { + return None; + } + let m = M([d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det]); + m.0.iter().all(|v| v.is_finite()).then_some(m) + } + + pub fn finite(&self) -> bool { + self.0.iter().all(|v| v.is_finite()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Seg { + Move(f64, f64), + Line(f64, f64), + Curve(f64, f64, f64, f64, f64, f64), + Close, +} + +impl Seg { + pub fn map(&self, m: &M) -> Seg { + match *self { + Seg::Move(x, y) => { + let (x, y) = m.apply(x, y); + Seg::Move(x, y) + } + Seg::Line(x, y) => { + let (x, y) = m.apply(x, y); + Seg::Line(x, y) + } + Seg::Curve(a, b, c, d, e, f) => { + let (a, b) = m.apply(a, b); + let (c, d) = m.apply(c, d); + let (e, f) = m.apply(e, f); + Seg::Curve(a, b, c, d, e, f) + } + Seg::Close => Seg::Close, + } + } +} + +/// The most segments one path may hold. +pub const MAX_PATH: usize = 1 << 20; + +/// Maximum number of complete turns an `arc`/`arcn` adds to the path before preserving parity. +pub const MAX_ARC_TURNS: f64 = 1024.0; + +/// The sweep PostScript's `arc` or `arcn` operator selects without iterating over whole turns. +/// +/// The modulo form matters for hostile angles: repeatedly adding or subtracting 360 can take +/// effectively forever for a finite `f64` with a huge magnitude. +pub fn bounded_arc_sweep(a0: f64, a1: f64, negative: bool) -> (f64, bool) { + let sweep = if !negative && a1 < a0 { + (a1 % 360.0 - a0 % 360.0).rem_euclid(360.0) + } else if negative && a1 > a0 { + -(a0 % 360.0 - a1 % 360.0).rem_euclid(360.0) + } else { + a1 - a0 + }; + let max = MAX_ARC_TURNS * 360.0; + if !sweep.is_finite() { + return (0.0, true); + } + if sweep.abs() <= max { + return (sweep, false); + } + let sign = sweep.signum(); + let remainder = (sign * (a1 % 720.0 - a0 % 720.0)).rem_euclid(720.0); + (sign * (max - 720.0 + remainder), true) +} + +/// How many Bézier segments an arc needs, or `None` if it exceeds `max_segments`. +pub fn arc_curve_count(r: f64, a0: f64, a1: f64, max_segments: usize) -> Option<usize> { + let sweep = a1.to_radians() - a0.to_radians(); + if !sweep.is_finite() || sweep == 0.0 { + return Some(0); + } + // The established EPS reader uses a 0.1-unit curve tolerance. A quarter-circle cubic has + // about 0.00027253*r maximum radial error; subdivision error falls with the sixth power of + // the segment angle. Estimate before allocation so huge radii stop at the path bound. + let subdivisions = (r.abs() * 0.00027253 / 0.1).max(1.0).powf(1.0 / 6.0).ceil(); + let required = (sweep.abs() / std::f64::consts::FRAC_PI_2 * subdivisions).ceil().max(1.0); + (required.is_finite() && required <= max_segments as f64).then_some(required as usize) +} + +/// Bézier segments for an arc of the circle at (cx, cy) with radius r, from angle a0 to a1 +/// (degrees), in user space: the first point and the curves. +pub fn arc_curves(cx: f64, cy: f64, r: f64, a0: f64, a1: f64, max_segments: usize) -> ((f64, f64), Vec<[f64; 6]>, bool) { + let count = arc_curve_count(r, a0, a1, max_segments); + let (a0, a1) = (a0.to_radians(), a1.to_radians()); + let start = (cx + r * a0.cos(), cy + r * a0.sin()); + let Some(n) = count else { + return (start, Vec::new(), true); + }; + let sweep = a1 - a0; + if n == 0 || !sweep.is_finite() { + return (start, Vec::new(), false); + } + let step = sweep / n as f64; + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let mut out = Vec::with_capacity(n); + let mut a = a0; + for _ in 0..n { + let b = a + step; + let (ca, sa, cb, sb) = (a.cos(), a.sin(), b.cos(), b.sin()); + out.push([cx + r * (ca - k * sa), cy + r * (sa + k * ca), cx + r * (cb + k * sb), cy + r * (sb - k * cb), cx + r * cb, cy + r * sb]); + a = b; + } + (start, out, false) +} + +#[derive(Clone, Debug)] +pub enum Space { + Gray, + Rgb, + Cmyk, + /// Separation or DeviceN: the colourant names, the alternate space and its tint transform. + Tint { + names: Vec<Vec<u8>>, + alt: Box<Space>, + tint: Obj, + }, + Indexed { + base: Box<Space>, + hival: usize, + lookup: Vec<u8>, + }, + Lab, + Pattern, +} + +impl Space { + pub fn comps(&self) -> usize { + match self { + Space::Gray | Space::Indexed { .. } | Space::Pattern => 1, + Space::Rgb | Space::Lab => 3, + Space::Cmyk => 4, + Space::Tint { names, .. } => names.len().max(1), + } + } + + pub fn initial(&self) -> Vec<f64> { + match self { + Space::Cmyk => vec![0.0, 0.0, 0.0, 1.0], + Space::Tint { names, .. } => vec![1.0; names.len().max(1)], + Space::Lab => vec![0.0, 0.0, 0.0], + _ => vec![0.0; self.comps()], + } + } +} + +/// A device colour as written to the PDF. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum DevColor { + Gray(f64), + Rgb(f64, f64, f64), + Cmyk(f64, f64, f64, f64), +} + +/// A clipping path, intersected with the ones before it. +#[derive(Debug)] +pub struct Clip { + pub path: Vec<Seg>, + pub eo: bool, + pub parent: Option<Rc<Clip>>, + pub depth: usize, +} + +pub fn clip_chain(c: &Option<Rc<Clip>>) -> Vec<Rc<Clip>> { + let mut out = Vec::new(); + let mut cur = c.clone(); + while let Some(n) = cur { + cur = n.parent.clone(); + out.push(n); + } + out.reverse(); + out +} + +#[derive(Clone, Debug)] +pub struct GState { + pub ctm: M, + pub path: Vec<Seg>, + /// The current point, in device space. + pub cur: Option<(f64, f64)>, + /// Where the current subpath started (closepath returns there). + pub start: Option<(f64, f64)>, + pub space: Space, + pub color: Vec<f64>, + /// The pattern dictionary when the space is Pattern. + pub pattern: Option<PDict>, + pub line_width: f64, + pub cap: i64, + pub join: i64, + pub miter: f64, + pub dash: (Vec<f64>, f64), + pub flat: f64, + pub font: Option<PDict>, + pub clip: Option<Rc<Clip>>, + pub overprint: bool, + pub stroke_adjust: bool, + /// Clips saved by `clipsave`. + pub clip_saves: Vec<Option<Rc<Clip>>>, + /// The colour space under an uncoloured pattern (`[/Pattern /DeviceRGB]`). + pub pattern_base: Option<Box<Space>>, + /// Inside an uncoloured pattern's PaintProc: colour operators are ignored. + pub color_locked: bool, + /// Painting goes nowhere (`nulldevice`, measuring glyphs). + pub nulldev: bool, + /// Glyph widths reported by `setcharwidth`/`setcachedevice` while a glyph runs. + pub char_width: Option<(f64, f64)>, +} + +impl Default for GState { + fn default() -> Self { + GState { + ctm: M::ID, + path: Vec::new(), + cur: None, + start: None, + space: Space::Gray, + color: vec![0.0], + pattern: None, + line_width: 1.0, + cap: 0, + join: 0, + miter: 10.0, + dash: (Vec::new(), 0.0), + flat: 1.0, + font: None, + clip: None, + overprint: false, + stroke_adjust: false, + clip_saves: Vec::new(), + color_locked: false, + pattern_base: None, + nulldev: false, + char_width: None, + } + } +} + +/// The bounding box of a path's points (control points included), or None for an empty path. +pub fn bbox(path: &[Seg]) -> Option<[f64; 4]> { + let mut b: Option<[f64; 4]> = None; + let mut add = |x: f64, y: f64| { + let r = b.get_or_insert([x, y, x, y]); + r[0] = r[0].min(x); + r[1] = r[1].min(y); + r[2] = r[2].max(x); + r[3] = r[3].max(y); + }; + for s in path { + match *s { + Seg::Move(x, y) | Seg::Line(x, y) => add(x, y), + Seg::Curve(a, b2, c, d, e, f) => { + add(a, b2); + add(c, d); + add(e, f); + } + Seg::Close => {} + } + } + b +} + +/// The most dashes a stroke may break into; beyond, it is drawn solid (a tiny pattern on a +/// long path would otherwise make billions of pieces). +pub const MAX_DASHES: f64 = 100_000.0; + +/// Whether dash pattern `dash` on `path` (in the space the pattern is measured in) stays within +/// [`MAX_DASHES`]; its lengths must be finite and not all zero. +pub fn dashes_ok(path: &[Seg], dash: &[f64]) -> bool { + let period: f64 = dash.iter().sum(); + if dash.is_empty() || !period.is_finite() || period <= 0.0 || dash.iter().any(|d| !d.is_finite() || *d < 0.0) { + return false; + } + let mut len = 0.0; + let mut cur = (0.0, 0.0); + for s in path { + match *s { + Seg::Move(x, y) => cur = (x, y), + Seg::Line(x, y) => { + len += (x - cur.0).hypot(y - cur.1); + cur = (x, y); + } + Seg::Curve(a, b, c, d, e, f) => { + len += (a - cur.0).hypot(b - cur.1) + (c - a).hypot(d - b) + (e - c).hypot(f - d); + cur = (e, f); + } + Seg::Close => {} + } + } + len.is_finite() && len / period * dash.len() as f64 <= MAX_DASHES +} + +/// A path with its curves replaced by line segments (`flattenpath`). +pub fn flatten(path: &[Seg], tol: f64) -> Vec<Seg> { + let mut out = Vec::with_capacity(path.len()); + let mut cur = (0.0, 0.0); + for s in path { + match *s { + Seg::Curve(x1, y1, x2, y2, x3, y3) => { + let d = ((x1 - cur.0).hypot(y1 - cur.1) + (x2 - x1).hypot(y2 - y1) + (x3 - x2).hypot(y3 - y2)).max(0.0); + let n = ((d / tol.max(0.05)).sqrt().ceil() as usize).clamp(1, 256); + for i in 1..=n { + let t = i as f64 / n as f64; + let mt = 1.0 - t; + let x = mt * mt * mt * cur.0 + 3.0 * mt * mt * t * x1 + 3.0 * mt * t * t * x2 + t * t * t * x3; + let y = mt * mt * mt * cur.1 + 3.0 * mt * mt * t * y1 + 3.0 * mt * t * t * y2 + t * t * t * y3; + out.push(Seg::Line(x, y)); + } + cur = (x3, y3); + } + Seg::Move(x, y) | Seg::Line(x, y) => { + cur = (x, y); + out.push(*s); + } + Seg::Close => out.push(*s), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matrices_compose_like_postscript() { + let t = M([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]); + let s = M([2.0, 0.0, 0.0, 3.0, 0.0, 0.0]); + // `10 20 translate 2 3 scale`: scale applies first, then translate. + let ctm = s.then(&t); + assert_eq!(ctm.apply(1.0, 1.0), (12.0, 23.0)); + let inv = ctm.inv().unwrap(); + let (x, y) = inv.apply(12.0, 23.0); + assert!((x - 1.0).abs() < 1e-12 && (y - 1.0).abs() < 1e-12); + assert!(M([0.0; 6]).inv().is_none()); + } + + #[test] + fn a_full_circle_is_four_quarter_curves() { + let (start, curves, truncated) = arc_curves(0.0, 0.0, 10.0, 0.0, 360.0, MAX_PATH); + assert!(!truncated); + assert!((start.0 - 10.0).abs() < 1e-9); + assert_eq!(curves.len(), 4); + let last = curves.last().unwrap(); + assert!((last[4] - 10.0).abs() < 1e-9 && last[5].abs() < 1e-9); + assert!(arc_curves(0.0, 0.0, 1.0, 0.0, f64::INFINITY, MAX_PATH).1.is_empty()); + assert_eq!(arc_curves(0.0, 0.0, 1.0, 0.0, MAX_ARC_TURNS * 360.0, MAX_PATH).1.len(), 4096); + assert!(arc_curves(0.0, 0.0, 2e17, 0.0, 360.0, 100).2); + } + + #[test] + fn huge_arc_angles_are_reduced_without_unbounded_turn_loops() { + assert_eq!(bounded_arc_sweep(1e18, 0.0, false), (80.0, false)); + assert_eq!(bounded_arc_sweep(0.0, 1e18, true), (-80.0, false)); + let (sweep, skipped) = bounded_arc_sweep(0.0, 5e18, false); + assert!(skipped); + assert!(sweep.abs() <= MAX_ARC_TURNS * 360.0); + assert_eq!(bounded_arc_sweep(0.0, f64::INFINITY, false), (0.0, true)); + } +} diff --git a/crates/ps/src/read/interp.rs b/crates/ps/src/read/interp.rs new file mode 100644 index 000000000..1f4e7e140 --- /dev/null +++ b/crates/ps/src/read/interp.rs @@ -0,0 +1,747 @@ +//! The interpreter: stacks, the execution loop and error handling. +//! +//! Execution never recurses on the Rust stack for PostScript control flow: procedures, loops +//! and `stopped` are frames on an explicit execution stack. Operators that must run a procedure +//! and use its result (tint transforms, BuildChar, `pathforall`) call [`Interp::call`], a +//! nested run of the loop with a bounded depth. + +use crate::read::gstate::GState; +use crate::read::obj::{Key, Obj, PArr, PDict, PStr, name}; +use crate::read::ops::{self, OpId}; +use crate::read::pdf::Out; +use crate::read::scan; +use crate::read::source::{Source, Sources}; + +/// A PostScript error (`typecheck`, …), `stop`, `quit`, or a fatal problem that ends the run. +#[derive(Debug, Clone, PartialEq)] +pub enum PsErr { + Ps(&'static str), + Stop, + Quit, + Fatal(String), +} + +pub type R<T = ()> = Result<T, PsErr>; + +pub fn err<T>(name: &'static str) -> R<T> { + Err(PsErr::Ps(name)) +} + +#[derive(Debug, Clone)] +pub enum Frame { + Proc { + arr: PArr, + i: usize, + }, + File { + id: usize, + }, + For { + cur: f64, + inc: f64, + limit: f64, + int: bool, + proc: Obj, + }, + Repeat { + n: i64, + proc: Obj, + }, + Loop { + proc: Obj, + }, + ForallArr { + arr: PArr, + i: usize, + proc: Obj, + }, + ForallStr { + s: PStr, + i: usize, + proc: Obj, + }, + ForallDict { + items: Vec<(Obj, Obj)>, + i: usize, + proc: Obj, + }, + Stopped, + /// The bottom of a nested run ([`Interp::call`]). + Barrier, +} + +impl Frame { + pub fn is_loop(&self) -> bool { + matches!( + self, + Frame::For { .. } + | Frame::Repeat { .. } + | Frame::Loop { .. } + | Frame::ForallArr { .. } + | Frame::ForallStr { .. } + | Frame::ForallDict { .. } + ) + } +} + +/// How much work and memory one EPS may use. +pub type FallbackFont = fn(&[u8]) -> Option<&'static [u8]>; + +#[derive(Debug, Clone, Copy)] +pub struct Limits { + pub steps: u64, + pub memory: usize, + /// Let hosts that historically ignored excess operands preserve that behavior. + pub stack_overflow_noop: bool, + /// Consume image data but leave drawing to hosts that historically skipped EPS images. + pub skip_images: bool, + /// Return an empty page plus a warning when execution fails before painting anything. + pub keep_unpainted: bool, + /// Match hosts that historically coerce zero divisors to a zero integer result. + pub zero_division_zero: bool, + /// Optional host font provider for stand-in fonts absent from an EPS file. + pub fallback_font: Option<FallbackFont>, +} + +impl Default for Limits { + /// Generous for real EPS files: an Illustrator file with its procsets takes about 0.6 million + /// steps and 2 MB, one carrying a 15 MB CJK font 2 million steps and 30 MB. A program that + /// runs into the step limit ends within a few seconds. Smaller on the web. + fn default() -> Self { + if cfg!(target_arch = "wasm32") { + Limits { + steps: 20_000_000, + memory: 256 << 20, + stack_overflow_noop: false, + skip_images: false, + keep_unpainted: false, + zero_division_zero: false, + fallback_font: None, + } + } else { + Limits { + steps: 50_000_000, + memory: 1 << 30, + stack_overflow_noop: false, + skip_images: false, + keep_unpainted: false, + zero_division_zero: false, + fallback_font: None, + } + } + } +} + +/// Memory a path segment and a graphics state take. +pub const SEG_BYTES: usize = std::mem::size_of::<crate::read::gstate::Seg>(); +pub const GSTATE_BYTES: usize = 512; + +/// Content-stream bytes one written path segment takes, about. +pub const OUT_SEG_BYTES: usize = 24; + +/// Memory a file takes (charged when one is made). +pub const SOURCE_BYTES: usize = 128; + +/// Bytes read, copied or scanned per step of work charged. +pub const BYTES_PER_STEP: u64 = 16; + +// Keep the operand limit in line with the EPS reader's established 100,000-value ceiling. +const MAX_OSTACK: usize = 100_000; +const MAX_ESTACK: usize = 100_000; +const MAX_DSTACK: usize = 1_000; +const MAX_GSTACK: usize = 10_000; +const MAX_NAME_DEPTH: usize = 48; +const MAX_CALL_DEPTH: usize = 48; + +pub struct Interp { + pub o: Vec<Obj>, + pub d: Vec<PDict>, + pub e: Vec<Frame>, + pub srcs: Sources, + pub gs: GState, + pub gstack: Vec<GState>, + /// Graphics-state depths that `save` objects restore to. + pub saves: Vec<usize>, + pub gstates: Vec<GState>, + pub systemdict: PDict, + pub globaldict: PDict, + pub userdict: PDict, + pub errordict: PDict, + pub dollar_error: PDict, + pub statusdict: PDict, + pub fontdir: PDict, + /// Resource categories: name → dictionary of instances. + pub resources: PDict, + pub out: Out, + pub limits: Limits, + pub steps: u64, + pub memory: usize, + /// How many of `srcs.read` have been charged as steps, and of the segments written. + pub read_charged: u64, + pub written_charged: u64, + pub depth: usize, + /// Executable names can resolve to each other without entering a procedure frame. + pub name_depth: usize, + pub next_fid: usize, + pub main: usize, + pub warnings: Vec<String>, + /// Tiling pattern cells already written, by pattern and colour. + pub cells: std::collections::HashMap<(crate::read::obj::Key, Vec<u64>), usize>, + /// CMaps by index (CMap dictionaries refer to them). + pub cmaps: Vec<crate::read::composite::CMap>, + /// CFF font sets read by StartData. + pub cff: Vec<std::rc::Rc<crate::read::cff::FontSet>>, + /// Type 42 fonts' TrueType data by FID. + pub sfnts: std::collections::HashMap<usize, std::rc::Rc<Vec<u8>>>, + /// `charpath` is running: glyphs add to the path instead of painting. + pub charpath: bool, + /// Glyph outlines by font (FID) and glyph name. + pub glyphs: std::collections::HashMap<(usize, Vec<u8>), std::rc::Rc<crate::read::type1::Glyph>>, + /// The last names executed (for error reports). + pub recent: std::collections::VecDeque<crate::read::obj::Name>, +} + +impl Interp { + pub fn new(program: Vec<u8>, origin: (f64, f64), limits: Limits) -> Self { + let mut srcs = Sources { max_read: limits.steps.saturating_mul(BYTES_PER_STEP), ..Sources::default() }; + let main = srcs.add(Source::bytes(program)); + let systemdict = PDict::new(1000); + let globaldict = PDict::new(100); + let userdict = PDict::new(200); + let mut ip = Interp { + o: Vec::new(), + d: vec![systemdict.clone(), globaldict.clone(), userdict.clone()], + e: Vec::new(), + srcs, + gs: GState::default(), + gstack: Vec::new(), + saves: Vec::new(), + gstates: Vec::new(), + systemdict, + globaldict, + userdict, + errordict: PDict::new(40), + dollar_error: PDict::new(10), + statusdict: PDict::new(40), + fontdir: PDict::new(100), + resources: PDict::new(20), + out: Out::new(origin), + limits, + steps: 0, + memory: SOURCE_BYTES, + read_charged: 0, + written_charged: 0, + depth: 0, + name_depth: 0, + next_fid: 1, + main, + warnings: Vec::new(), + recent: std::collections::VecDeque::new(), + glyphs: std::collections::HashMap::new(), + charpath: false, + sfnts: std::collections::HashMap::new(), + cmaps: Vec::new(), + cells: std::collections::HashMap::new(), + cff: Vec::new(), + }; + ops::install(&mut ip); + ip + } + + // ----- operand stack ----- + + pub fn push(&mut self, o: Obj) -> R { + if self.o.len() >= MAX_OSTACK { + if self.limits.stack_overflow_noop { + return Ok(()); + } + return err("stackoverflow"); + } + self.o.push(o); + Ok(()) + } + + pub fn pop(&mut self) -> R<Obj> { + self.o.pop().ok_or(PsErr::Ps("stackunderflow")) + } + + pub fn top(&self, n: usize) -> R<&Obj> { + let i = self.o.len().checked_sub(n + 1).ok_or(PsErr::Ps("stackunderflow"))?; + self.o.get(i).ok_or(PsErr::Ps("stackunderflow")) + } + + pub fn need(&self, n: usize) -> R { + if self.o.len() < n { err("stackunderflow") } else { Ok(()) } + } + + /// Whether an operator can append `n` values without exceeding the operand stack limit. + pub fn has_operand_room(&self, n: usize) -> bool { + self.o.len().checked_add(n).is_some_and(|len| len <= MAX_OSTACK) + } + + pub fn pop_num(&mut self) -> R<f64> { + match self.pop()? { + o @ (Obj::Int(_) | Obj::Real(_)) => o.num().ok_or(PsErr::Ps("typecheck")), + _ => err("typecheck"), + } + } + + pub fn pop_int(&mut self) -> R<i64> { + match self.pop()? { + Obj::Int(i) => Ok(i), + Obj::Real(r) if r.is_finite() => Ok(r as i64), + _ => err("typecheck"), + } + } + + pub fn pop_usize(&mut self) -> R<usize> { + usize::try_from(self.pop_int()?).map_err(|_| PsErr::Ps("rangecheck")) + } + + pub fn pop_bool(&mut self) -> R<bool> { + match self.pop()? { + Obj::Bool(b) => Ok(b), + _ => err("typecheck"), + } + } + + pub fn pop_dict(&mut self) -> R<PDict> { + match self.pop()? { + Obj::Dict(d) => Ok(d), + _ => err("typecheck"), + } + } + + pub fn pop_arr(&mut self) -> R<PArr> { + match self.pop()? { + Obj::Array(a, _) => Ok(a), + _ => err("typecheck"), + } + } + + pub fn pop_str(&mut self) -> R<PStr> { + match self.pop()? { + Obj::Str(s, _) => Ok(s), + _ => err("typecheck"), + } + } + + /// A name, or a string read as one. + pub fn pop_name(&mut self) -> R<Vec<u8>> { + match self.pop()? { + Obj::Name(n, _) => Ok(n.to_vec()), + Obj::Str(s, _) => Ok(s.bytes()), + _ => err("typecheck"), + } + } + + pub fn pop_matrix(&mut self) -> R<crate::read::gstate::M> { + let a = self.pop_arr()?; + matrix_of(&a) + } + + /// Charge `units` steps of work (elements visited, or [`BYTES_PER_STEP`] bytes each): what an + /// operator does in proportion to its operands counts against the step limit, checked as it + /// goes rather than after. + pub fn charge(&mut self, units: u64) -> R { + self.steps = self.steps.saturating_add(units); + if self.steps > self.limits.steps { Err(PsErr::Fatal("the program runs too long".into())) } else { Ok(()) } + } + + /// Charge work for `n` bytes handled. + pub fn charge_bytes(&mut self, n: usize) -> R { + self.charge((n as u64) / BYTES_PER_STEP + 1) + } + + /// Charge memory for `n` bytes made (new objects and copies alike; the cap bounds what one + /// conversion makes in all, not only what it keeps). + pub fn alloc(&mut self, n: usize) -> R { + self.memory = self.memory.saturating_add(n); + if self.memory > self.limits.memory { Err(PsErr::Fatal("out of memory".into())) } else { Ok(()) } + } + + /// Register a retained file source against the memory bound. + pub fn add_source(&mut self, source: Source) -> R<usize> { + self.alloc(SOURCE_BYTES)?; + Ok(self.srcs.add(source)) + } + + /// Whether a file ID is still held by an operand or execution frame. + pub fn file_is_live(&self, id: usize) -> bool { + self.o.iter().any(|o| matches!(o, Obj::File(file) if *file == id)) + || self.e.iter().any(|frame| matches!(frame, Frame::File { id: file } if *file == id)) + } + + /// Consume a SubFileDecode stream whose file object is explicitly discarded with `pop`. + pub fn discard_subfile(&mut self, id: usize) -> R { + if !self.srcs.is_subfile_filter(id) { + return Ok(()); + } + let mut chunk = 0u64; + while self.srcs.read(id).is_some() { + chunk += 1; + if chunk == BYTES_PER_STEP { + self.read_charged = self.read_charged.saturating_add(chunk); + self.charge(1)?; + chunk = 0; + } + } + if self.srcs.exhausted { Err(PsErr::Fatal("the program reads too much data".into())) } else { Ok(()) } + } + + // ----- dictionaries ----- + + pub fn lookup(&self, k: &Key) -> Option<Obj> { + self.d.iter().rev().find_map(|d| d.get(k)) + } + + pub fn begin(&mut self, d: PDict) -> R { + if self.d.len() >= MAX_DSTACK { + return err("dictstackoverflow"); + } + self.d.push(d); + Ok(()) + } + + pub fn current_dict(&self) -> R<PDict> { + self.d.last().cloned().ok_or(PsErr::Ps("dictstackunderflow")) + } + + // ----- execution ----- + + pub fn push_frame(&mut self, f: Frame) -> R { + if self.e.len() >= MAX_ESTACK { + return err("execstackoverflow"); + } + self.e.push(f); + Ok(()) + } + + /// Execute an object as `exec` does: procedures run, names are looked up, strings and files + /// are scanned as programs, anything else is pushed. + pub fn exec_value(&mut self, o: Obj) -> R { + match o { + Obj::Array(a, true) => { + if a.len > 0 { + self.push_frame(Frame::Proc { arr: a, i: 0 })?; + } + Ok(()) + } + Obj::Name(n, true) => { + if self.name_depth >= MAX_NAME_DEPTH { + return Err(PsErr::Fatal("executable name resolution limit".into())); + } + self.name_depth += 1; + if self.recent.len() >= 24 { + self.recent.pop_front(); + } + self.recent.push_back(n.clone()); + let result = match self.lookup(&Key::Name(n.clone())) { + Some(v) => self.exec_found(v), + None => { + self.dollar_error.put_name(b"offending", Obj::Name(n, false)); + Err(PsErr::Ps("undefined")) + } + }; + self.name_depth -= 1; + result + } + Obj::Op(op) => self.call_op(op), + Obj::Str(s, true) => { + // A string runs as a file reading it in place. + let id = self.add_source(Source::string(&s))?; + self.push_frame(Frame::File { id }) + } + Obj::File(id) => self.push_frame(Frame::File { id }), + other => self.push(other), + } + } + + /// The value of an executable name: executed (procedures run). + fn exec_found(&mut self, v: Obj) -> R { + match v { + Obj::Array(a, true) => { + if a.len > 0 { + self.push_frame(Frame::Proc { arr: a, i: 0 })?; + } + Ok(()) + } + Obj::Op(op) => self.call_op(op), + // A name bound to another executable name: `exec_value` bounds this resolution chain. + // Files are literal unless `exec` runs them (`cvx exec`). + o @ (Obj::Name(_, true) | Obj::Str(_, true)) => self.exec_value(o), + other => self.push(other), + } + } + + pub fn call_op(&mut self, op: OpId) -> R { + let (opname, f) = ops::OPS.get(op as usize).copied().ok_or(PsErr::Ps("undefined"))?; + match f(self) { + Err(PsErr::Ps(e)) => { + self.dollar_error.put_name(b"command", Obj::lit(opname)); + Err(PsErr::Ps(e)) + } + r => r, + } + } + + /// Execute one object met in a procedure body or a program: executable names and operators + /// run, everything else (procedures included) is pushed. + fn exec_direct(&mut self, o: Obj) -> R { + match o { + Obj::Name(_, true) | Obj::Op(_) => self.exec_value(o), + other => self.push(other), + } + } + + fn step(&mut self) -> R { + // Bytes read since the last step are work too (decoding included). + let read = self.srcs.read; + let fresh = read.saturating_sub(self.read_charged); + self.read_charged = read; + self.charge(1 + fresh / BYTES_PER_STEP)?; + // So is what was written: re-emitted clips included. + let written = self.out.segments() as u64; + let fresh = written.saturating_sub(self.written_charged); + if fresh > 0 { + self.written_charged = written; + self.charge(fresh / 4)?; + self.alloc(usize::try_from(fresh).unwrap_or(usize::MAX).saturating_mul(OUT_SEG_BYTES))?; + } + if self.srcs.exhausted { + return Err(PsErr::Fatal("the program reads too much data".into())); + } + let Some(frame) = self.e.last_mut() else { return Ok(()) }; + match frame { + Frame::Proc { arr, i } => { + let Some(o) = arr.get(*i) else { + self.e.pop(); + return Ok(()); + }; + *i += 1; + if *i >= arr.len { + // The last element: drop the frame first, so tail recursion doesn't grow it. + self.e.pop(); + } + self.exec_direct(o) + } + Frame::File { id } => { + let id = *id; + let d = &self.d; + let mut resolve = |n: &[u8]| d.iter().rev().find_map(|dict| dict.get(&Key::Name(name(n)))); + let before = self.srcs.read; + let token = scan::next(&mut self.srcs, id, &mut resolve); + // What the scanner read became objects: memory. + let scanned = usize::try_from(self.srcs.read.saturating_sub(before)).unwrap_or(usize::MAX); + self.alloc(scanned)?; + match token { + Ok(Some(o)) => self.exec_direct(o), + Ok(None) => { + self.e.pop(); + Ok(()) + } + Err(msg) => { + self.e.pop(); + self.warnings.push(msg); + err("syntaxerror") + } + } + } + Frame::For { cur, inc, limit, int, proc } => { + let done = if *inc > 0.0 { *cur > *limit } else { *cur < *limit }; + if done || !cur.is_finite() { + self.e.pop(); + return Ok(()); + } + let v = if *int { Obj::Int(*cur as i64) } else { Obj::Real(*cur) }; + *cur += *inc; + let p = proc.clone(); + self.push(v)?; + self.exec_value(p) + } + Frame::Repeat { n, proc } => { + if *n <= 0 { + self.e.pop(); + return Ok(()); + } + *n -= 1; + let p = proc.clone(); + self.exec_value(p) + } + Frame::Loop { proc } => { + let p = proc.clone(); + self.exec_value(p) + } + Frame::ForallArr { arr, i, proc } => { + let Some(v) = arr.get(*i) else { + self.e.pop(); + return Ok(()); + }; + *i += 1; + let p = proc.clone(); + self.push(v)?; + self.exec_value(p) + } + Frame::ForallStr { s, i, proc } => { + let Some(v) = s.get(*i) else { + self.e.pop(); + return Ok(()); + }; + *i += 1; + let p = proc.clone(); + self.push(Obj::Int(i64::from(v)))?; + self.exec_value(p) + } + Frame::ForallDict { items, i, proc } => { + let Some((k, v)) = items.get(*i).cloned() else { + self.e.pop(); + return Ok(()); + }; + *i += 1; + let p = proc.clone(); + self.push(k)?; + self.push(v)?; + self.exec_value(p) + } + Frame::Stopped => { + self.e.pop(); + self.push(Obj::Bool(false)) + } + Frame::Barrier => Ok(()), + } + } + + /// Run until the execution stack is back to `floor` frames. + pub fn run_to(&mut self, floor: usize) -> R { + while self.e.len() > floor { + if matches!(self.e.last(), Some(Frame::Barrier)) && self.e.len() == floor + 1 { + break; + } + match self.step() { + Ok(()) => {} + Err(PsErr::Fatal(m)) => return Err(PsErr::Fatal(m)), + Err(PsErr::Quit) => return Err(PsErr::Quit), + Err(e) => { + if let PsErr::Ps(name) = &e { + self.dollar_error.put_name(b"errorname", Obj::lit(name.as_bytes())); + self.dollar_error.put_name(b"newerror", Obj::Bool(true)); + } + // Unwind to the nearest `stopped` above the floor; none: the error is ours to return. + match self.e.iter().rposition(|f| matches!(f, Frame::Stopped | Frame::Barrier)) { + Some(i) if i >= floor && matches!(self.e.get(i), Some(Frame::Stopped)) => { + self.e.truncate(i); + self.push(Obj::Bool(true))?; + } + _ => { + self.e.truncate(floor); + return Err(e); + } + } + } + } + } + Ok(()) + } + + /// Run `proc` to completion (a nested run), for operators that need its results. + pub fn call(&mut self, proc: Obj) -> R { + if self.depth >= MAX_CALL_DEPTH { + return err("limitcheck"); + } + self.depth += 1; + let floor = self.e.len(); + let r = self.push_frame(Frame::Barrier).and_then(|()| self.exec_value(proc)).and_then(|()| self.run_to(floor + 1)); + // Drop the barrier (and anything an error left above the floor). + self.e.truncate(floor); + self.depth -= 1; + r + } + + /// Run the program. + pub fn run(&mut self) -> Result<(), String> { + self.e.push(Frame::File { id: self.main }); + match self.run_to(0) { + Ok(()) | Err(PsErr::Quit) => Ok(()), + Err(PsErr::Stop) => Ok(()), + Err(PsErr::Ps(e)) => { + let cmd = self.dollar_error.get_name(b"command").map(|c| match c { + Obj::Name(n, _) => String::from_utf8_lossy(&n).into_owned(), + _ => String::new(), + }); + let offending = match self.dollar_error.get_name(b"offending") { + Some(Obj::Name(n, _)) => format!(" ({})", String::from_utf8_lossy(&n)), + _ => String::new(), + }; + let recent: Vec<String> = self.recent.iter().map(|n| String::from_utf8_lossy(n).into_owned()).collect(); + let stack: Vec<String> = self + .o + .iter() + .rev() + .take(6) + .map(|o| { + String::from_utf8_lossy(&crate::read::ops::basic::text_of(o)).chars().take(24).collect::<String>() + + ":" + + &String::from_utf8_lossy(o.type_name()) + }) + .collect(); + Err(format!( + "PostScript error {e} in {}{offending}; after {}; stack {}", + cmd.unwrap_or_default(), + recent.join(" "), + stack.join(" | ") + )) + } + Err(PsErr::Fatal(m)) => Err(m), + } + } + + // ----- graphics-state stack ----- + + pub fn gsave(&mut self) -> R { + if self.gstack.len() >= MAX_GSTACK { + return err("limitcheck"); + } + self.charge_gstate()?; + self.gstack.push(self.gs.clone()); + Ok(()) + } + + /// Copying the graphics state copies its path: work and memory in proportion. + pub fn charge_gstate(&mut self) -> R { + let n = self.gs.path.len() + self.gs.dash.0.len() + self.gs.clip_saves.len() + self.gs.color.len(); + self.charge(n as u64 / 4 + 1)?; + self.alloc(n.saturating_mul(SEG_BYTES).saturating_add(GSTATE_BYTES)) + } + + /// Charge work and memory for copying or walking `n` path segments. + pub fn charge_path(&mut self, n: usize) -> R { + self.charge(n as u64 / 4 + 1)?; + self.alloc(n.saturating_mul(SEG_BYTES)) + } + + pub fn grestore(&mut self) { + // Not below the innermost save. + let floor = self.saves.last().copied().unwrap_or(0); + if self.gstack.len() > floor + && let Some(g) = self.gstack.pop() + { + self.gs = g; + } + } +} + +/// A six-number array as a matrix. +pub fn matrix_of(a: &PArr) -> R<crate::read::gstate::M> { + if a.len != 6 { + return err("rangecheck"); + } + let mut m = [0.0; 6]; + for (i, slot) in m.iter_mut().enumerate() { + *slot = a.get(i).and_then(|o| o.num()).ok_or(PsErr::Ps("typecheck"))?; + } + Ok(crate::read::gstate::M(m)) +} + +pub fn matrix_obj(m: &crate::read::gstate::M) -> Obj { + Obj::Array(PArr::new(m.0.iter().map(|v| Obj::Real(*v)).collect()), false) +} diff --git a/crates/ps/src/read/mod.rs b/crates/ps/src/read/mod.rs new file mode 100644 index 000000000..0fcc3b363 --- /dev/null +++ b/crates/ps/src/read/mod.rs @@ -0,0 +1,118 @@ +//! Reading EPS: a PostScript interpreter that runs the program and writes what it paints as a +//! one-page PDF the size of its bounding box, in vector form with its colours kept (CMYK stays +//! CMYK), so an app can show and print it as a placed PDF. +//! +//! Written from the PostScript Language Reference (third edition), the EPS specification, the +//! Type 1 Font Format and Adobe Technical Notes 5012 (Type 42), 5176 (CFF) and 5177 (Type 2 +//! charstrings). +//! Covered: the language (Level 3 operators EPS files use), paths, painting, clipping, device and +//! Separation/DeviceN/Indexed colour, sampled images with the standard filters, smooth shadings +//! (axial, radial, function-based, triangle and patch meshes), shading and tiling patterns, and +//! text in Type 1, Type 3, Type 42 and CFF fonts (`StartData`), CIDFonts and composite fonts +//! through CMaps, written horizontally or vertically. + +mod cff; +mod cff_strings; +mod composite; +mod encodings; +mod font; +mod gstate; +mod interp; +mod obj; +mod ops; +mod pdf; +mod scan; +mod source; +mod type1; +mod type42; + +use craft_eps::{Comments, Kind, MAX_EXTENDED_HEADER, postscript_section as shared_postscript_section}; + +pub use interp::{FallbackFont, Limits}; + +/// A converted EPS. +#[derive(Debug)] +pub struct Converted { + /// A one-page PDF of the bounding box. + pub pdf: Vec<u8>, + /// The bounding box in points (x0, y0, x1, y1). + pub bbox: [f64; 4], + /// Things the program did that weren't drawn (unsupported features). + pub warnings: Vec<String>, + /// The work and memory the conversion used, as [`Limits`] counts them. + pub steps: u64, + pub memory: usize, +} + +/// The PostScript part of an EPS (inside a DOS EPS binary header, when there is one). +pub fn postscript_section(bytes: &[u8]) -> &[u8] { + shared_postscript_section(bytes).unwrap_or(&[]) +} + +/// The bounding box from the DSC comments: the high-resolution one when it is valid. +pub fn bounding_box(ps: &[u8]) -> Option<[f64; 4]> { + Comments::read_with_header_limit(ps, MAX_EXTENDED_HEADER).page_box() +} + +/// An EPS file (plain, or DOS EPS with a binary header)? +pub fn is_eps(bytes: &[u8]) -> bool { + craft_eps::sniff(bytes).is_some_and(|file| file.kind == Kind::Eps) +} + +/// How many converted EPS files are kept. +const CACHE_ENTRIES: usize = 64; + +type Cache = std::collections::HashMap<(u64, usize), Option<std::sync::Arc<Vec<u8>>>>; + +fn cache() -> &'static std::sync::Mutex<Cache> { + static CACHE: std::sync::OnceLock<std::sync::Mutex<Cache>> = std::sync::OnceLock::new(); + CACHE.get_or_init(|| std::sync::Mutex::new(Cache::new())) +} + +/// [`eps_to_pdf`] with the default limits, remembered by content: the screen, thumbnails and +/// every export convert an EPS once. None when it can't be converted (callers show its preview). +pub fn cached_pdf(eps: &[u8]) -> Option<std::sync::Arc<Vec<u8>>> { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + eps.hash(&mut h); + let key = (h.finish(), eps.len()); + if let Some(hit) = cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key) { + return hit.clone(); + } + // Convert outside the lock: other EPS files keep drawing meanwhile. + let pdf = eps_to_pdf(eps, Limits::default()).ok().map(|c| std::sync::Arc::new(c.pdf)); + let mut c = cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if c.len() >= CACHE_ENTRIES { + c.clear(); + } + c.insert(key, pdf.clone()); + pdf +} + +/// Run an EPS and write what it paints as PDF. `Err` when it isn't an EPS with a bounding box, +/// or when it fails before painting and `limits.keep_unpainted` is false. +pub fn eps_to_pdf(bytes: &[u8], limits: Limits) -> Result<Converted, String> { + let ps = postscript_section(bytes); + if !ps.starts_with(b"%!") { + return Err("not PostScript".into()); + } + let bbox = bounding_box(ps).ok_or("the EPS has no bounding box")?; + let mut ip = interp::Interp::new(ps.to_vec(), (bbox[0], bbox[1]), limits); + let result = ip.run(); + let mut warnings = std::mem::take(&mut ip.warnings); + warnings.dedup(); + if let Err(e) = result { + // What was painted before an error is kept (the rest of the page is lost, as on a + // printer); with nothing painted, the caller falls back to the preview. + if !ip.out.painted && !limits.keep_unpainted { + return Err(e); + } + warnings.push(e); + } + let size = (bbox[2] - bbox[0], bbox[3] - bbox[1]); + let (steps, memory) = (ip.steps, ip.memory); + Ok(Converted { pdf: ip.out.finish(size), bbox, warnings, steps, memory }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ps/src/read/obj.rs b/crates/ps/src/read/obj.rs new file mode 100644 index 000000000..411450123 --- /dev/null +++ b/crates/ps/src/read/obj.rs @@ -0,0 +1,301 @@ +//! PostScript objects. Composite objects (strings, arrays, dictionaries) share their storage the +//! way the language requires: `dup` copies the reference, `getinterval` a window onto the same +//! values. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +use crate::read::ops::OpId; + +/// A name: its bytes, shared. +pub type Name = Rc<[u8]>; + +pub fn name(s: &[u8]) -> Name { + Rc::from(s) +} + +#[derive(Clone, Debug)] +pub struct PStr { + pub buf: Rc<RefCell<Vec<u8>>>, + pub off: usize, + pub len: usize, +} + +impl PStr { + pub fn new(bytes: Vec<u8>) -> Self { + let len = bytes.len(); + PStr { buf: Rc::new(RefCell::new(bytes)), off: 0, len } + } + + /// The bytes in view (empty when the window no longer fits its storage). + pub fn bytes(&self) -> Vec<u8> { + let b = self.buf.borrow(); + self.off.checked_add(self.len).and_then(|end| b.get(self.off..end)).map(<[u8]>::to_vec).unwrap_or_default() + } + + pub fn get(&self, i: usize) -> Option<u8> { + if i >= self.len { + return None; + } + self.buf.borrow().get(self.off.checked_add(i)?).copied() + } + + pub fn set(&self, i: usize, v: u8) -> bool { + if i >= self.len { + return false; + } + let Some(at) = self.off.checked_add(i) else { return false }; + match self.buf.borrow_mut().get_mut(at) { + Some(slot) => { + *slot = v; + true + } + None => false, + } + } + + pub fn interval(&self, start: usize, count: usize) -> Option<PStr> { + (start.checked_add(count)? <= self.len).then(|| PStr { buf: self.buf.clone(), off: self.off + start, len: count }) + } + + /// Copy `src` into the start of this string: the written window, or None when it doesn't fit. + pub fn put_bytes(&self, at: usize, src: &[u8]) -> Option<PStr> { + if at.checked_add(src.len())? > self.len { + return None; + } + let mut b = self.buf.borrow_mut(); + let start = self.off.checked_add(at)?; + b.get_mut(start..start.checked_add(src.len())?)?.copy_from_slice(src); + Some(PStr { buf: self.buf.clone(), off: start, len: src.len() }) + } +} + +#[derive(Clone, Debug)] +pub struct PArr { + pub buf: Rc<RefCell<Vec<Obj>>>, + pub off: usize, + pub len: usize, +} + +impl PArr { + pub fn new(v: Vec<Obj>) -> Self { + let len = v.len(); + PArr { buf: Rc::new(RefCell::new(v)), off: 0, len } + } + + pub fn get(&self, i: usize) -> Option<Obj> { + if i >= self.len { + return None; + } + self.buf.borrow().get(self.off.checked_add(i)?).cloned() + } + + pub fn set(&self, i: usize, v: Obj) -> bool { + if i >= self.len { + return false; + } + let Some(at) = self.off.checked_add(i) else { return false }; + match self.buf.borrow_mut().get_mut(at) { + Some(slot) => { + *slot = v; + true + } + None => false, + } + } + + pub fn items(&self) -> Vec<Obj> { + let b = self.buf.borrow(); + self.off.checked_add(self.len).and_then(|end| b.get(self.off..end)).map(<[Obj]>::to_vec).unwrap_or_default() + } + + pub fn interval(&self, start: usize, count: usize) -> Option<PArr> { + (start.checked_add(count)? <= self.len).then(|| PArr { buf: self.buf.clone(), off: self.off + start, len: count }) + } + + pub fn same(&self, o: &PArr) -> bool { + Rc::ptr_eq(&self.buf, &o.buf) && self.off == o.off && self.len == o.len + } +} + +/// A dictionary key: names (strings become names), integers (integral reals too), booleans, and +/// anything else by identity. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Key { + Name(Name), + Int(i64), + Real(u64), + Bool(bool), + Null, + Ident(usize), +} + +#[derive(Debug, Default)] +pub struct DictInner { + pub map: HashMap<Key, (Obj, Obj)>, + pub cap: usize, +} + +#[derive(Clone, Debug)] +pub struct PDict(pub Rc<RefCell<DictInner>>); + +impl PDict { + pub fn new(cap: usize) -> Self { + PDict(Rc::new(RefCell::new(DictInner { map: HashMap::new(), cap }))) + } + + pub fn get(&self, k: &Key) -> Option<Obj> { + self.0.borrow().map.get(k).map(|(_, v)| v.clone()) + } + + pub fn get_name(&self, n: &[u8]) -> Option<Obj> { + self.get(&Key::Name(name(n))) + } + + pub fn put(&self, key: Obj, v: Obj) { + let k = key.key(); + self.0.borrow_mut().map.insert(k, (key, v)); + } + + pub fn put_name(&self, n: &[u8], v: Obj) { + self.put(Obj::Name(name(n), false), v); + } + + pub fn remove(&self, k: &Key) { + self.0.borrow_mut().map.remove(k); + } + + pub fn len(&self) -> usize { + self.0.borrow().map.len() + } + + pub fn known(&self, k: &Key) -> bool { + self.0.borrow().map.contains_key(k) + } + + pub fn entries(&self) -> Vec<(Obj, Obj)> { + self.0.borrow().map.values().cloned().collect() + } + + pub fn same(&self, o: &PDict) -> bool { + Rc::ptr_eq(&self.0, &o.0) + } + + fn ident(&self) -> usize { + Rc::as_ptr(&self.0) as *const u8 as usize + } +} + +/// An open file: an index into the interpreter's sources. +pub type FileId = usize; + +#[derive(Clone, Debug)] +pub enum Obj { + Null, + Bool(bool), + Int(i64), + Real(f64), + /// A name; `true` when executable. + Name(Name, bool), + Str(PStr, bool), + Array(PArr, bool), + Dict(PDict), + Mark, + Op(OpId), + File(FileId), + /// A `save` snapshot: the graphics-state depth it restores to. + Save(usize), + /// A font identifier (`FID`). + FontId(usize), + /// A saved graphics state (`gstate`). + GState(usize), +} + +impl Obj { + pub fn key(&self) -> Key { + match self { + Obj::Name(n, _) => Key::Name(n.clone()), + Obj::Str(s, _) => Key::Name(name(&s.bytes())), + Obj::Int(i) => Key::Int(*i), + Obj::Real(r) if r.fract() == 0.0 && r.abs() < 9.0e15 => Key::Int(*r as i64), + Obj::Real(r) => Key::Real(r.to_bits()), + Obj::Bool(b) => Key::Bool(*b), + Obj::Null => Key::Null, + Obj::Array(a, _) => Key::Ident(Rc::as_ptr(&a.buf) as *const u8 as usize ^ a.off), + Obj::Dict(d) => Key::Ident(d.ident()), + Obj::Op(o) => Key::Ident(0x4000_0000 + *o as usize), + Obj::File(f) => Key::Ident(0x5000_0000 + f), + Obj::FontId(f) => Key::Ident(0x6000_0000 + f), + Obj::Mark => Key::Ident(1), + Obj::Save(s) => Key::Ident(0x7000_0000 + s), + Obj::GState(g) => Key::Ident(0x7800_0000 + g), + } + } + + pub fn type_name(&self) -> &'static [u8] { + match self { + Obj::Null => b"nulltype", + Obj::Bool(_) => b"booleantype", + Obj::Int(_) => b"integertype", + Obj::Real(_) => b"realtype", + Obj::Name(..) => b"nametype", + Obj::Str(..) => b"stringtype", + Obj::Array(..) => b"arraytype", + Obj::Dict(_) => b"dicttype", + Obj::Mark => b"marktype", + Obj::Op(_) => b"operatortype", + Obj::File(_) => b"filetype", + Obj::Save(_) => b"savetype", + Obj::FontId(_) => b"fonttype", + Obj::GState(_) => b"gstatetype", + } + } + + pub fn is_exec(&self) -> bool { + match self { + Obj::Name(_, x) | Obj::Str(_, x) | Obj::Array(_, x) => *x, + Obj::Op(_) => true, + _ => false, + } + } + + pub fn num(&self) -> Option<f64> { + match self { + Obj::Int(i) => Some(*i as f64), + Obj::Real(r) => Some(*r), + _ => None, + } + } + + pub fn str(s: &[u8]) -> Obj { + Obj::Str(PStr::new(s.to_vec()), false) + } + + pub fn lit(n: &[u8]) -> Obj { + Obj::Name(name(n), false) + } + + pub fn proc(v: Vec<Obj>) -> Obj { + Obj::Array(PArr::new(v), true) + } + + /// Equality as `eq` sees it: numbers by value, strings by contents, names and strings + /// interchangeably, composites by identity. + pub fn ps_eq(&self, o: &Obj) -> bool { + match (self, o) { + (a, b) if a.num().is_some() && b.num().is_some() => a.num() == b.num(), + (Obj::Str(a, _), Obj::Str(b, _)) => a.bytes() == b.bytes(), + (Obj::Name(a, _), Obj::Name(b, _)) => a == b, + (Obj::Name(a, _), Obj::Str(b, _)) | (Obj::Str(b, _), Obj::Name(a, _)) => **a == *b.bytes(), + (Obj::Bool(a), Obj::Bool(b)) => a == b, + (Obj::Null, Obj::Null) | (Obj::Mark, Obj::Mark) => true, + (Obj::Array(a, _), Obj::Array(b, _)) => a.same(b), + (Obj::Dict(a), Obj::Dict(b)) => a.same(b), + (Obj::Op(a), Obj::Op(b)) => a == b, + (Obj::File(a), Obj::File(b)) | (Obj::FontId(a), Obj::FontId(b)) | (Obj::Save(a), Obj::Save(b)) => a == b, + (Obj::GState(a), Obj::GState(b)) => a == b, + _ => false, + } + } +} diff --git a/crates/ps/src/read/ops/basic.rs b/crates/ps/src/read/ops/basic.rs new file mode 100644 index 000000000..7177bd7f1 --- /dev/null +++ b/crates/ps/src/read/ops/basic.rs @@ -0,0 +1,1101 @@ +//! The language: stack, arithmetic, relations, control, types, dictionaries, strings, arrays. + +use crate::read::interp::{Frame, Interp, PsErr, R, err}; +use crate::read::obj::{Key, Obj, PArr, PDict, PStr, name}; + +// ----- stack ----- + +pub fn pop(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::File(id) if !ip.file_is_live(id) => ip.discard_subfile(id), + _ => Ok(()), + } +} + +pub fn exch(ip: &mut Interp) -> R { + ip.need(2)?; + let n = ip.o.len(); + ip.o.swap(n - 1, n - 2); + Ok(()) +} + +pub fn dup(ip: &mut Interp) -> R { + let o = ip.top(0)?.clone(); + ip.push(o) +} + +pub fn copy(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::Int(n) => { + let n = usize::try_from(n).map_err(|_| PsErr::Ps("rangecheck"))?; + ip.need(n)?; + // Check before cloning or charging so a hostile count cannot partially mutate the + // stack or allocate a large temporary; strict hosts still report stackoverflow. + if !ip.has_operand_room(n) { + return if ip.limits.stack_overflow_noop { Ok(()) } else { err("stackoverflow") }; + } + let start = ip.o.len() - n; + ip.charge((n / 8) as u64)?; + ip.alloc(n.saturating_mul(OBJ_BYTES))?; + let items: Vec<Obj> = ip.o.get(start..).map(<[Obj]>::to_vec).unwrap_or_default(); + for o in items { + ip.push(o)?; + } + Ok(()) + } + Obj::Array(dst, x) => { + let src = ip.pop_arr()?; + if src.len > dst.len { + return err("rangecheck"); + } + ip.charge(src.len as u64)?; + ip.alloc(src.len.saturating_mul(OBJ_BYTES))?; + for (i, o) in src.items().into_iter().enumerate() { + dst.set(i, o); + } + let sub = dst.interval(0, src.len).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Array(sub, x)) + } + Obj::Str(dst, x) => { + let src = ip.pop_str()?; + ip.charge_bytes(src.len)?; + ip.alloc(src.len)?; + let w = dst.put_bytes(0, &src.bytes()).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(w, x)) + } + Obj::Dict(dst) => { + let src = ip.pop_dict()?; + ip.charge(src.len() as u64)?; + ip.alloc(src.len().saturating_mul(2 * OBJ_BYTES))?; + for (k, v) in src.entries() { + dst.put(k, v); + } + ip.push(Obj::Dict(dst)) + } + _ => err("typecheck"), + } +} + +pub fn index(ip: &mut Interp) -> R { + let n = ip.pop_usize()?; + let o = ip.top(n).map_err(|_| PsErr::Ps("rangecheck"))?.clone(); + ip.push(o) +} + +pub fn roll(ip: &mut Interp) -> R { + let j = ip.pop_int()?; + let n = ip.pop_usize()?; + ip.need(n)?; + if n == 0 { + return Ok(()); + } + let start = ip.o.len() - n; + let k = usize::try_from(j.rem_euclid(n as i64)).unwrap_or(0); + if let Some(s) = ip.o.get_mut(start..) { + s.rotate_right(k); + } + Ok(()) +} + +pub fn clear(ip: &mut Interp) -> R { + ip.o.clear(); + Ok(()) +} + +pub fn count(ip: &mut Interp) -> R { + let n = ip.o.len() as i64; + ip.push(Obj::Int(n)) +} + +pub fn mark(ip: &mut Interp) -> R { + ip.push(Obj::Mark) +} + +/// Where the topmost mark is; the search is work (a deep stack takes long). +pub fn mark_pos(ip: &mut Interp) -> R<usize> { + let i = ip.o.iter().rposition(|o| matches!(o, Obj::Mark)); + ip.charge((ip.o.len() - i.map_or(0, |i| i + 1)) as u64)?; + i.ok_or(PsErr::Ps("unmatchedmark")) +} + +/// Memory one object takes, for charging copies of arrays and stacks. +pub const OBJ_BYTES: usize = 32; + +/// A string used as a dictionary key is copied into a name: work and memory. +pub fn key_cost(ip: &mut Interp, k: &Obj) -> R { + if let Obj::Str(s, _) = k { + ip.charge_bytes(s.len)?; + ip.alloc(s.len)?; + } + Ok(()) +} + +pub fn cleartomark(ip: &mut Interp) -> R { + let i = mark_pos(ip)?; + ip.o.truncate(i); + Ok(()) +} + +pub fn counttomark(ip: &mut Interp) -> R { + let i = mark_pos(ip)?; + let n = (ip.o.len() - i - 1) as i64; + ip.push(Obj::Int(n)) +} + +pub fn array_close(ip: &mut Interp) -> R { + let i = mark_pos(ip)?; + let items = ip.o.split_off(i + 1); + ip.o.pop(); + ip.alloc(items.len().saturating_mul(OBJ_BYTES))?; + ip.push(Obj::Array(PArr::new(items), false)) +} + +pub fn dict_close(ip: &mut Interp) -> R { + let i = mark_pos(ip)?; + let items = ip.o.split_off(i + 1); + ip.o.pop(); + if !items.len().is_multiple_of(2) { + return err("rangecheck"); + } + ip.alloc(items.len().saturating_mul(OBJ_BYTES))?; + for k in items.iter().step_by(2) { + key_cost(ip, k)?; + } + let d = PDict::new(items.len() / 2); + let mut it = items.into_iter(); + while let (Some(k), Some(v)) = (it.next(), it.next()) { + d.put(k, v); + } + ip.push(Obj::Dict(d)) +} + +// ----- arithmetic ----- + +fn arith(ip: &mut Interp, fi: fn(i64, i64) -> Option<i64>, fr: fn(f64, f64) -> f64) -> R { + let b = ip.pop()?; + let a = ip.pop()?; + match (&a, &b) { + (Obj::Int(x), Obj::Int(y)) => match fi(*x, *y).filter(|v| i32::try_from(*v).is_ok()) { + Some(v) => ip.push(Obj::Int(v)), + None => ip.push(Obj::Real(fr(*x as f64, *y as f64))), + }, + _ => { + let (Some(x), Some(y)) = (a.num(), b.num()) else { return err("typecheck") }; + let v = fr(x, y); + if !v.is_finite() { + return err("undefinedresult"); + } + ip.push(Obj::Real(v)) + } + } +} + +pub fn add(ip: &mut Interp) -> R { + arith(ip, i64::checked_add, |a, b| a + b) +} + +pub fn sub(ip: &mut Interp) -> R { + arith(ip, i64::checked_sub, |a, b| a - b) +} + +pub fn mul(ip: &mut Interp) -> R { + arith(ip, i64::checked_mul, |a, b| a * b) +} + +pub fn div(ip: &mut Interp) -> R { + let b = ip.pop_num()?; + let a = ip.pop_num()?; + if b == 0.0 { + return err("undefinedresult"); + } + ip.push(Obj::Real(a / b)) +} + +pub fn idiv(ip: &mut Interp) -> R { + let b = ip.pop_int()?; + let a = ip.pop_int()?; + if b == 0 { + if ip.limits.zero_division_zero { + return ip.push(Obj::Int(0)); + } + return err("undefinedresult"); + } + // The signed minimum divided by -1 overflows the host integer type. PostScript integer + // arithmetic wraps this one exceptional result to zero rather than raising an error. + let v = a.checked_div(b).unwrap_or(0); + ip.push(Obj::Int(v)) +} + +pub fn mod_(ip: &mut Interp) -> R { + let b = ip.pop_int()?; + let a = ip.pop_int()?; + if b == 0 { + if ip.limits.zero_division_zero { + return ip.push(Obj::Int(0)); + } + return err("undefinedresult"); + } + let v = a.checked_rem(b).unwrap_or(0); + ip.push(Obj::Int(v)) +} + +fn unary(ip: &mut Interp, fi: fn(i64) -> Option<i64>, fr: fn(f64) -> f64) -> R { + match ip.pop()? { + Obj::Int(i) => match fi(i) { + Some(v) => ip.push(Obj::Int(v)), + None => ip.push(Obj::Real(fr(i as f64))), + }, + Obj::Real(r) => ip.push(Obj::Real(fr(r))), + _ => err("typecheck"), + } +} + +pub fn neg(ip: &mut Interp) -> R { + unary(ip, i64::checked_neg, |r| -r) +} + +pub fn abs(ip: &mut Interp) -> R { + unary(ip, i64::checked_abs, f64::abs) +} + +pub fn ceiling(ip: &mut Interp) -> R { + unary(ip, Some, f64::ceil) +} + +pub fn floor(ip: &mut Interp) -> R { + unary(ip, Some, f64::floor) +} + +pub fn round(ip: &mut Interp) -> R { + // PostScript rounds halves up (toward +∞). + unary(ip, Some, |r| (r + 0.5).floor()) +} + +pub fn truncate(ip: &mut Interp) -> R { + unary(ip, Some, f64::trunc) +} + +fn real_fn(ip: &mut Interp, f: fn(f64) -> f64) -> R { + let a = ip.pop_num()?; + let v = f(a); + if !v.is_finite() { + return err("undefinedresult"); + } + ip.push(Obj::Real(v)) +} + +pub fn sqrt(ip: &mut Interp) -> R { + let a = ip.pop_num()?; + if a < 0.0 { + return err("rangecheck"); + } + ip.push(Obj::Real(a.sqrt())) +} + +pub fn sin(ip: &mut Interp) -> R { + real_fn(ip, |d| d.to_radians().sin()) +} + +pub fn cos(ip: &mut Interp) -> R { + real_fn(ip, |d| d.to_radians().cos()) +} + +pub fn atan(ip: &mut Interp) -> R { + let den = ip.pop_num()?; + let num = ip.pop_num()?; + if num == 0.0 && den == 0.0 { + return err("undefinedresult"); + } + let mut a = num.atan2(den).to_degrees(); + if a < 0.0 { + a += 360.0; + } + ip.push(Obj::Real(a)) +} + +pub fn exp(ip: &mut Interp) -> R { + let e = ip.pop_num()?; + let b = ip.pop_num()?; + let v = b.powf(e); + if !v.is_finite() { + return err("undefinedresult"); + } + ip.push(Obj::Real(v)) +} + +pub fn ln(ip: &mut Interp) -> R { + let a = ip.pop_num()?; + if a <= 0.0 { + return err("rangecheck"); + } + ip.push(Obj::Real(a.ln())) +} + +pub fn log(ip: &mut Interp) -> R { + let a = ip.pop_num()?; + if a <= 0.0 { + return err("rangecheck"); + } + ip.push(Obj::Real(a.log10())) +} + +pub fn rand(ip: &mut Interp) -> R { + // A fixed, repeatable sequence (no entropy in conversions). + ip.steps = ip.steps.wrapping_add(1); + let v = (ip.steps.wrapping_mul(1_103_515_245).wrapping_add(12345) >> 1) & 0x7FFF_FFFF; + ip.push(Obj::Int(v as i64)) +} + +pub fn srand(ip: &mut Interp) -> R { + ip.pop_int().map(|_| ()) +} + +pub fn rrand(ip: &mut Interp) -> R { + ip.push(Obj::Int(0)) +} + +// ----- relations, booleans, bits ----- + +/// Comparing strings compares (and copies) their bytes. +fn compare_cost(ip: &mut Interp, a: &Obj, b: &Obj) -> R { + let len = |o: &Obj| match o { + Obj::Str(s, _) => s.len, + Obj::Name(n, _) => n.len(), + _ => 0, + }; + if matches!(a, Obj::Str(..)) || matches!(b, Obj::Str(..)) { + let n = len(a).saturating_add(len(b)); + ip.charge_bytes(n)?; + ip.alloc(n)?; + } + Ok(()) +} + +pub fn eq(ip: &mut Interp) -> R { + let b = ip.pop()?; + let a = ip.pop()?; + compare_cost(ip, &a, &b)?; + ip.push(Obj::Bool(a.ps_eq(&b))) +} + +pub fn ne(ip: &mut Interp) -> R { + let b = ip.pop()?; + let a = ip.pop()?; + compare_cost(ip, &a, &b)?; + ip.push(Obj::Bool(!a.ps_eq(&b))) +} + +fn compare(ip: &mut Interp, f: fn(std::cmp::Ordering) -> bool) -> R { + let b = ip.pop()?; + let a = ip.pop()?; + compare_cost(ip, &a, &b)?; + let ord = match (&a, &b) { + (Obj::Str(x, _), Obj::Str(y, _)) => x.bytes().cmp(&y.bytes()), + _ => { + let (Some(x), Some(y)) = (a.num(), b.num()) else { return err("typecheck") }; + x.partial_cmp(&y).ok_or(PsErr::Ps("undefinedresult"))? + } + }; + ip.push(Obj::Bool(f(ord))) +} + +pub fn gt(ip: &mut Interp) -> R { + compare(ip, |o| o.is_gt()) +} + +pub fn ge(ip: &mut Interp) -> R { + compare(ip, |o| o.is_ge()) +} + +pub fn lt(ip: &mut Interp) -> R { + compare(ip, |o| o.is_lt()) +} + +pub fn le(ip: &mut Interp) -> R { + compare(ip, |o| o.is_le()) +} + +fn logic(ip: &mut Interp, fb: fn(bool, bool) -> bool, fi: fn(i64, i64) -> i64) -> R { + let b = ip.pop()?; + let a = ip.pop()?; + match (a, b) { + (Obj::Bool(x), Obj::Bool(y)) => ip.push(Obj::Bool(fb(x, y))), + (Obj::Int(x), Obj::Int(y)) => ip.push(Obj::Int(fi(x, y))), + _ => err("typecheck"), + } +} + +pub fn and(ip: &mut Interp) -> R { + logic(ip, |a, b| a & b, |a, b| a & b) +} + +pub fn or(ip: &mut Interp) -> R { + logic(ip, |a, b| a | b, |a, b| a | b) +} + +pub fn xor(ip: &mut Interp) -> R { + logic(ip, |a, b| a ^ b, |a, b| a ^ b) +} + +pub fn not(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::Bool(b) => ip.push(Obj::Bool(!b)), + Obj::Int(i) => ip.push(Obj::Int(!i)), + _ => err("typecheck"), + } +} + +pub fn bitshift(ip: &mut Interp) -> R { + let s = ip.pop_int()?; + let v = ip.pop_int()? as i32 as u32; + let r = if s >= 0 { v.checked_shl(s.min(32) as u32).unwrap_or(0) } else { v.checked_shr((-s).min(32) as u32).unwrap_or(0) }; + ip.push(Obj::Int(i64::from(r as i32))) +} + +pub fn true_(ip: &mut Interp) -> R { + ip.push(Obj::Bool(true)) +} + +pub fn false_(ip: &mut Interp) -> R { + ip.push(Obj::Bool(false)) +} + +pub fn null(ip: &mut Interp) -> R { + ip.push(Obj::Null) +} + +// ----- control ----- + +pub fn exec(ip: &mut Interp) -> R { + let o = ip.pop()?; + ip.exec_value(o) +} + +pub fn if_(ip: &mut Interp) -> R { + let p = ip.pop()?; + if ip.pop_bool()? { ip.exec_value(p) } else { Ok(()) } +} + +pub fn ifelse(ip: &mut Interp) -> R { + let pf = ip.pop()?; + let pt = ip.pop()?; + if ip.pop_bool()? { ip.exec_value(pt) } else { ip.exec_value(pf) } +} + +pub fn for_(ip: &mut Interp) -> R { + let proc = ip.pop()?; + let limit = ip.pop()?; + let inc = ip.pop()?; + let init = ip.pop()?; + let int = matches!((&init, &inc), (Obj::Int(_), Obj::Int(_))); + let (Some(cur), Some(inc), Some(limit)) = (init.num(), inc.num(), limit.num()) else { return err("typecheck") }; + if inc == 0.0 { + // Runs forever in PostScript; the step limit would end it. Treat as empty. + return Ok(()); + } + ip.push_frame(Frame::For { cur, inc, limit, int, proc }) +} + +pub fn repeat(ip: &mut Interp) -> R { + let proc = ip.pop()?; + let n = ip.pop_int()?; + if n < 0 { + return err("rangecheck"); + } + ip.push_frame(Frame::Repeat { n, proc }) +} + +pub fn loop_(ip: &mut Interp) -> R { + let proc = ip.pop()?; + ip.push_frame(Frame::Loop { proc }) +} + +pub fn exit(ip: &mut Interp) -> R { + let depth = ip.e.len() as u64; + ip.charge(depth / 16)?; + let i = ip.e.iter().rposition(|f| f.is_loop() || matches!(f, Frame::Stopped | Frame::Barrier)).ok_or(PsErr::Ps("invalidexit"))?; + if !ip.e.get(i).is_some_and(Frame::is_loop) { + return err("invalidexit"); + } + ip.e.truncate(i); + Ok(()) +} + +pub fn stop(_ip: &mut Interp) -> R { + Err(PsErr::Stop) +} + +pub fn stopped(ip: &mut Interp) -> R { + let p = ip.pop()?; + ip.push_frame(Frame::Stopped)?; + ip.exec_value(p) +} + +pub fn quit(_ip: &mut Interp) -> R { + Err(PsErr::Quit) +} + +pub fn forall(ip: &mut Interp) -> R { + let proc = ip.pop()?; + match ip.pop()? { + Obj::Array(arr, _) => ip.push_frame(Frame::ForallArr { arr, i: 0, proc }), + Obj::Str(s, _) => ip.push_frame(Frame::ForallStr { s, i: 0, proc }), + Obj::Dict(d) => { + // The entries are copied first (the procedure may change the dictionary). + ip.charge(d.len() as u64)?; + ip.alloc(d.len().saturating_mul(2 * OBJ_BYTES))?; + ip.push_frame(Frame::ForallDict { items: d.entries(), i: 0, proc }) + } + _ => err("typecheck"), + } +} + +pub fn countexecstack(ip: &mut Interp) -> R { + let n = ip.e.len() as i64; + ip.push(Obj::Int(n)) +} + +pub fn execstack(ip: &mut Interp) -> R { + let a = ip.pop_arr()?; + let n = ip.e.len().min(a.len); + let sub = a.interval(0, n).ok_or(PsErr::Ps("rangecheck"))?; + ip.charge(n as u64)?; + for i in 0..n { + sub.set(i, Obj::Null); + } + ip.push(Obj::Array(sub, false)) +} + +// ----- types and conversion ----- + +pub fn type_(ip: &mut Interp) -> R { + let o = ip.pop()?; + ip.push(Obj::Name(name(o.type_name()), true)) +} + +pub fn cvlit(ip: &mut Interp) -> R { + let o = match ip.pop()? { + Obj::Name(n, _) => Obj::Name(n, false), + Obj::Array(a, _) => Obj::Array(a, false), + Obj::Str(s, _) => Obj::Str(s, false), + o => o, + }; + ip.push(o) +} + +pub fn cvx(ip: &mut Interp) -> R { + let o = match ip.pop()? { + Obj::Name(n, _) => Obj::Name(n, true), + Obj::Array(a, _) => Obj::Array(a, true), + Obj::Str(s, _) => Obj::Str(s, true), + o => o, + }; + ip.push(o) +} + +pub fn xcheck(ip: &mut Interp) -> R { + let o = ip.pop()?; + ip.push(Obj::Bool(o.is_exec())) +} + +/// Access attributes aren't enforced: everything stays readable and writable. +pub fn noop_keep(ip: &mut Interp) -> R { + ip.top(0).map(|_| ()) +} + +pub fn check_true(ip: &mut Interp) -> R { + ip.pop()?; + ip.push(Obj::Bool(true)) +} + +pub fn cvi(ip: &mut Interp) -> R { + let v = match ip.pop()? { + Obj::Int(i) => i, + Obj::Real(r) if r.is_finite() && r.abs() < 2.2e9 => r.trunc() as i64, + Obj::Str(s, _) if s.len > 4096 => return err("limitcheck"), + Obj::Str(s, _) => match crate::read::scan::number(&s.bytes()) { + Some(o) => o.num().filter(|v| v.abs() < 2.2e9).ok_or(PsErr::Ps("rangecheck"))?.trunc() as i64, + None => return err("syntaxerror"), + }, + Obj::Real(_) => return err("rangecheck"), + _ => return err("typecheck"), + }; + ip.push(Obj::Int(v)) +} + +pub fn cvr(ip: &mut Interp) -> R { + let v = match ip.pop()? { + o @ (Obj::Int(_) | Obj::Real(_)) => o.num().unwrap_or(0.0), + Obj::Str(s, _) if s.len > 4096 => return err("limitcheck"), + Obj::Str(s, _) => crate::read::scan::number(&s.bytes()).and_then(|o| o.num()).ok_or(PsErr::Ps("syntaxerror"))?, + _ => return err("typecheck"), + }; + ip.push(Obj::Real(v)) +} + +pub fn cvn(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::Str(s, x) => { + ip.charge_bytes(s.len)?; + ip.alloc(s.len)?; + ip.push(Obj::Name(name(&s.bytes()), x)) + } + n @ Obj::Name(..) => ip.push(n), + _ => err("typecheck"), + } +} + +/// The text `cvs`/`=` print for an object. +pub fn text_of(o: &Obj) -> Vec<u8> { + match o { + Obj::Int(i) => i.to_string().into_bytes(), + Obj::Real(r) => { + if r.fract() == 0.0 && r.abs() < 1e15 { + format!("{r:.1}").into_bytes() + } else { + format!("{r}").into_bytes() + } + } + Obj::Bool(b) => { + if *b { + b"true".to_vec() + } else { + b"false".to_vec() + } + } + Obj::Name(n, _) => n.to_vec(), + Obj::Str(s, _) => s.bytes(), + Obj::Op(op) => crate::read::ops::OPS.get(*op as usize).map(|(n, _)| n.to_vec()).unwrap_or_default(), + _ => b"--nostringval--".to_vec(), + } +} + +pub fn cvs(ip: &mut Interp) -> R { + let dst = ip.pop_str()?; + let o = ip.pop()?; + ip.charge_bytes(dst.len)?; + let t = text_of(&o); + let w = dst.put_bytes(0, &t).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(w, false)) +} + +pub fn cvrs(ip: &mut Interp) -> R { + let dst = ip.pop_str()?; + let radix = ip.pop_int()?; + let n = ip.pop_num()?; + if !(2..=36).contains(&radix) { + return err("rangecheck"); + } + let t = if radix == 10 { + text_of(&Obj::Real(n)) + } else { + let mut v = (n as i64 as i32) as u32; + let mut digits = Vec::new(); + loop { + let d = (v % radix as u32) as u8; + digits.push(if d < 10 { b'0' + d } else { b'A' + d - 10 }); + v /= radix as u32; + if v == 0 { + break; + } + } + digits.reverse(); + digits + }; + let w = dst.put_bytes(0, &t).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(w, false)) +} + +// ----- dictionaries ----- + +pub fn dict(ip: &mut Interp) -> R { + let n = ip.pop_usize()?; + ip.alloc(64)?; + ip.push(Obj::Dict(PDict::new(n.min(100_000)))) +} + +pub fn maxlength(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + let n = d.0.borrow().cap.max(d.len()) as i64; + ip.push(Obj::Int(n)) +} + +pub fn begin(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + ip.begin(d) +} + +pub fn end(ip: &mut Interp) -> R { + // systemdict, globaldict and userdict stay. + if ip.d.len() <= 3 { + return err("dictstackunderflow"); + } + ip.d.pop(); + Ok(()) +} + +pub fn def(ip: &mut Interp) -> R { + let v = ip.pop()?; + let k = ip.pop()?; + key_cost(ip, &k)?; + ip.alloc(2 * OBJ_BYTES)?; + ip.current_dict()?.put(k, v); + Ok(()) +} + +pub fn load(ip: &mut Interp) -> R { + let k = ip.pop()?; + key_cost(ip, &k)?; + let Some(v) = ip.lookup(&k.key()) else { + ip.dollar_error.put_name(b"offending", k); + return err("undefined"); + }; + ip.push(v) +} + +pub fn store(ip: &mut Interp) -> R { + let v = ip.pop()?; + let k = ip.pop()?; + key_cost(ip, &k)?; + let key = k.key(); + let d = ip.d.iter().rev().find(|d| d.known(&key)).cloned().map_or_else(|| ip.current_dict(), Ok)?; + d.put(k, v); + Ok(()) +} + +pub fn get(ip: &mut Interp) -> R { + let k = ip.pop()?; + key_cost(ip, &k)?; + match ip.pop()? { + Obj::Dict(d) => { + let Some(v) = d.get(&k.key()) else { + ip.dollar_error.put_name(b"offending", k); + return err("undefined"); + }; + ip.push(v) + } + Obj::Array(a, _) => { + let i = usize::try_from(int_of(&k)?).map_err(|_| PsErr::Ps("rangecheck"))?; + let v = a.get(i).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(v) + } + Obj::Str(s, _) => { + let i = usize::try_from(int_of(&k)?).map_err(|_| PsErr::Ps("rangecheck"))?; + let v = s.get(i).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Int(i64::from(v))) + } + _ => err("typecheck"), + } +} + +fn int_of(o: &Obj) -> R<i64> { + match o { + Obj::Int(i) => Ok(*i), + _ => err("typecheck"), + } +} + +pub fn put(ip: &mut Interp) -> R { + let v = ip.pop()?; + let k = ip.pop()?; + match ip.pop()? { + Obj::Dict(d) => { + key_cost(ip, &k)?; + ip.alloc(2 * OBJ_BYTES)?; + d.put(k, v); + Ok(()) + } + Obj::Array(a, _) => { + let i = usize::try_from(int_of(&k)?).map_err(|_| PsErr::Ps("rangecheck"))?; + if a.set(i, v) { Ok(()) } else { err("rangecheck") } + } + Obj::Str(s, _) => { + let i = usize::try_from(int_of(&k)?).map_err(|_| PsErr::Ps("rangecheck"))?; + let b = u8::try_from(int_of(&v)? & 0xFF).unwrap_or(0); + if s.set(i, b) { Ok(()) } else { err("rangecheck") } + } + _ => err("typecheck"), + } +} + +pub fn known(ip: &mut Interp) -> R { + let k = ip.pop()?; + key_cost(ip, &k)?; + let d = ip.pop_dict()?; + ip.push(Obj::Bool(d.known(&k.key()))) +} + +pub fn undef(ip: &mut Interp) -> R { + let k = ip.pop()?; + key_cost(ip, &k)?; + let d = ip.pop_dict()?; + d.remove(&k.key()); + Ok(()) +} + +pub fn where_(ip: &mut Interp) -> R { + let k = ip.pop()?; + key_cost(ip, &k)?; + ip.charge(ip.d.len() as u64 / 16)?; + let k = k.key(); + match ip.d.iter().rev().find(|d| d.known(&k)).cloned() { + Some(d) => { + ip.push(Obj::Dict(d))?; + ip.push(Obj::Bool(true)) + } + None => ip.push(Obj::Bool(false)), + } +} + +pub fn currentdict(ip: &mut Interp) -> R { + let d = ip.current_dict()?; + ip.push(Obj::Dict(d)) +} + +pub fn countdictstack(ip: &mut Interp) -> R { + let n = ip.d.len() as i64; + ip.push(Obj::Int(n)) +} + +pub fn dictstack(ip: &mut Interp) -> R { + let a = ip.pop_arr()?; + let n = ip.d.len().min(a.len); + for (i, d) in ip.d.iter().take(n).enumerate() { + a.set(i, Obj::Dict(d.clone())); + } + let sub = a.interval(0, n).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Array(sub, false)) +} + +pub fn cleardictstack(ip: &mut Interp) -> R { + ip.d.truncate(3); + Ok(()) +} + +// ----- strings and arrays ----- + +pub fn array(ip: &mut Interp) -> R { + let n = ip.pop_usize()?; + ip.charge(n as u64)?; + ip.alloc(n.saturating_mul(OBJ_BYTES))?; + ip.push(Obj::Array(PArr::new(vec![Obj::Null; n]), false)) +} + +pub fn string(ip: &mut Interp) -> R { + let n = ip.pop_usize()?; + ip.charge_bytes(n)?; + ip.alloc(n)?; + ip.push(Obj::Str(PStr::new(vec![0; n]), false)) +} + +pub fn length(ip: &mut Interp) -> R { + let n = match ip.pop()? { + Obj::Array(a, _) => a.len, + Obj::Str(s, _) => s.len, + Obj::Dict(d) => d.len(), + Obj::Name(n, _) => n.len(), + _ => return err("typecheck"), + }; + ip.push(Obj::Int(n as i64)) +} + +pub fn getinterval(ip: &mut Interp) -> R { + let count = ip.pop_usize()?; + let start = ip.pop_usize()?; + match ip.pop()? { + Obj::Array(a, x) => { + let s = a.interval(start, count).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Array(s, x)) + } + Obj::Str(s, x) => { + let s = s.interval(start, count).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(s, x)) + } + _ => err("typecheck"), + } +} + +pub fn putinterval(ip: &mut Interp) -> R { + let src = ip.pop()?; + let start = ip.pop_usize()?; + match (ip.pop()?, src) { + (Obj::Array(dst, _), Obj::Array(src, _)) => { + if start.checked_add(src.len).is_none_or(|e| e > dst.len) { + return err("rangecheck"); + } + ip.charge(src.len as u64)?; + ip.alloc(src.len.saturating_mul(OBJ_BYTES))?; + for (i, o) in src.items().into_iter().enumerate() { + dst.set(start + i, o); + } + Ok(()) + } + (Obj::Str(dst, _), Obj::Str(src, _)) => { + ip.charge_bytes(src.len)?; + ip.alloc(src.len)?; + dst.put_bytes(start, &src.bytes()).map(|_| ()).ok_or(PsErr::Ps("rangecheck")) + } + _ => err("typecheck"), + } +} + +pub fn aload(ip: &mut Interp) -> R { + let o = ip.pop()?; + let Obj::Array(a, _) = &o else { return err("typecheck") }; + ip.charge(a.len as u64)?; + ip.alloc(a.len.saturating_mul(OBJ_BYTES))?; + for v in a.items() { + ip.push(v)?; + } + ip.push(o) +} + +pub fn astore(ip: &mut Interp) -> R { + let o = ip.pop()?; + let Obj::Array(a, _) = &o else { return err("typecheck") }; + ip.need(a.len)?; + ip.charge(a.len as u64)?; + let start = ip.o.len() - a.len; + let items = ip.o.split_off(start); + for (i, v) in items.into_iter().enumerate() { + a.set(i, v); + } + ip.push(o) +} + +pub fn packedarray(ip: &mut Interp) -> R { + let n = ip.pop_usize()?; + ip.need(n)?; + ip.charge(n as u64)?; + ip.alloc(n.saturating_mul(OBJ_BYTES))?; + let start = ip.o.len() - n; + let items = ip.o.split_off(start); + ip.push(Obj::Array(PArr::new(items), false)) +} + +pub fn search(ip: &mut Interp) -> R { + let seek = ip.pop_str()?.bytes(); + let s = ip.pop_str()?; + ip.charge_bytes(s.len.saturating_add(seek.len()))?; + ip.alloc(s.len.saturating_add(seek.len()))?; + let hay = s.bytes(); + let found = find(ip, &hay, &seek)?; + match found { + Some(i) => { + let post = s.interval(i + seek.len(), hay.len() - i - seek.len()).ok_or(PsErr::Ps("rangecheck"))?; + let m = s.interval(i, seek.len()).ok_or(PsErr::Ps("rangecheck"))?; + let pre = s.interval(0, i).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(post, false))?; + ip.push(Obj::Str(m, false))?; + ip.push(Obj::Str(pre, false))?; + ip.push(Obj::Bool(true)) + } + None => { + ip.push(Obj::Str(s, false))?; + ip.push(Obj::Bool(false)) + } + } +} + +/// Where `seek` first occurs in `hay`, charging the bytes compared as it goes (a naive search +/// costs |hay| × |seek| on inputs made to defeat it). +fn find(ip: &mut Interp, hay: &[u8], seek: &[u8]) -> R<Option<usize>> { + if seek.is_empty() { + return Ok(Some(0)); + } + let mut compared = 0usize; + for (i, w) in hay.windows(seek.len()).enumerate() { + let same = w.iter().zip(seek).take_while(|(a, b)| a == b).count(); + compared += same + 1; + if same == seek.len() { + ip.charge_bytes(compared)?; + return Ok(Some(i)); + } + if compared >= 1 << 16 { + ip.charge_bytes(compared)?; + compared = 0; + } + } + ip.charge_bytes(compared)?; + Ok(None) +} + +pub fn anchorsearch(ip: &mut Interp) -> R { + let seek = ip.pop_str()?.bytes(); + let s = ip.pop_str()?; + ip.charge_bytes(s.len.saturating_add(seek.len()))?; + ip.alloc(s.len.saturating_add(seek.len()))?; + if s.bytes().starts_with(&seek) { + let post = s.interval(seek.len(), s.len - seek.len()).ok_or(PsErr::Ps("rangecheck"))?; + let m = s.interval(0, seek.len()).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(post, false))?; + ip.push(Obj::Str(m, false))?; + ip.push(Obj::Bool(true)) + } else { + ip.push(Obj::Str(s, false))?; + ip.push(Obj::Bool(false)) + } +} + +/// `token` on a string: the first object and the rest. +pub fn token(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::Str(s, _) => { + let id = ip.add_source(crate::read::source::Source::string(&s))?; + let d = &ip.d; + let mut resolve = |n: &[u8]| d.iter().rev().find_map(|dict| dict.get(&Key::Name(name(n)))); + match crate::read::scan::next(&mut ip.srcs, id, &mut resolve) { + Ok(Some(o)) => { + let used = ip.srcs.position(id).unwrap_or(s.len).min(s.len); + let rest = s.interval(used, s.len - used).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(rest, false))?; + ip.push(o)?; + ip.push(Obj::Bool(true)) + } + Ok(None) => ip.push(Obj::Bool(false)), + Err(_) => err("syntaxerror"), + } + } + Obj::File(id) => { + let d = &ip.d; + let mut resolve = |n: &[u8]| d.iter().rev().find_map(|dict| dict.get(&Key::Name(name(n)))); + match crate::read::scan::next(&mut ip.srcs, id, &mut resolve) { + Ok(Some(o)) => { + ip.push(o)?; + ip.push(Obj::Bool(true)) + } + Ok(None) => ip.push(Obj::Bool(false)), + Err(_) => err("syntaxerror"), + } + } + _ => err("typecheck"), + } +} + +/// `bind`: executable names that name operators become the operators, through nested +/// procedures (each procedure once). +pub fn bind(ip: &mut Interp) -> R { + let o = ip.top(0)?.clone(); + let Obj::Array(root, _) = o else { return Ok(()) }; + let mut todo = vec![root]; + let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new(); + while let Some(a) = todo.pop() { + let id = std::rc::Rc::as_ptr(&a.buf) as *const u8 as usize; + if seen.len() > 100_000 || !seen.insert(id) { + continue; + } + ip.charge(a.len as u64)?; + for i in 0..a.len { + match a.get(i) { + Some(Obj::Name(n, true)) => { + if let Some(Obj::Op(op)) = ip.lookup(&Key::Name(n)) { + a.set(i, Obj::Op(op)); + } + } + Some(Obj::Array(sub, true)) => todo.push(sub), + _ => {} + } + } + } + Ok(()) +} diff --git a/crates/ps/src/read/ops/gfx.rs b/crates/ps/src/read/ops/gfx.rs new file mode 100644 index 000000000..489c9fe86 --- /dev/null +++ b/crates/ps/src/read/ops/gfx.rs @@ -0,0 +1,1257 @@ +//! Graphics: the graphics state, matrices, paths, painting, clipping and colour. + +use std::rc::Rc; + +use crate::read::gstate::{Clip, DevColor, GState, M, MAX_PATH, Seg, Space, arc_curve_count, arc_curves, bbox, bounded_arc_sweep, flatten}; +use crate::read::interp::{Interp, PsErr, R, SEG_BYTES, err, matrix_obj}; +use crate::read::obj::{Obj, PArr, PDict}; +use crate::read::pdf::StrokeParams; + +// ----- graphics-state stack ----- + +pub fn gsave(ip: &mut Interp) -> R { + ip.gsave() +} + +pub fn grestore(ip: &mut Interp) -> R { + ip.grestore(); + Ok(()) +} + +pub fn grestoreall(ip: &mut Interp) -> R { + let floor = ip.saves.last().copied().unwrap_or(0); + while ip.gstack.len() > floor { + ip.grestore(); + } + Ok(()) +} + +pub fn initgraphics(ip: &mut Interp) -> R { + let font = ip.gs.font.clone(); + ip.gs = GState { font, ..GState::default() }; + Ok(()) +} + +pub fn save(ip: &mut Interp) -> R { + ip.gsave()?; + ip.saves.push(ip.gstack.len()); + let n = ip.saves.len(); + ip.push(Obj::Save(n)) +} + +pub fn restore(ip: &mut Interp) -> R { + let Obj::Save(n) = ip.pop()? else { return err("typecheck") }; + if n == 0 || n > ip.saves.len() { + return err("invalidrestore"); + } + let depth = ip.saves.get(n - 1).copied().unwrap_or(0); + ip.saves.truncate(n - 1); + // Back to the state saved with it (save did a gsave, leaving `depth` states stacked). + while ip.gstack.len() >= depth.max(1) { + let Some(g) = ip.gstack.pop() else { break }; + ip.gs = g; + } + Ok(()) +} + +pub fn gstate(ip: &mut Interp) -> R { + ip.charge_gstate()?; + if ip.gstates.len() > 100_000 { + return err("limitcheck"); + } + ip.gstates.push(ip.gs.clone()); + let n = ip.gstates.len() - 1; + ip.push(Obj::GState(n)) +} + +pub fn currentgstate(ip: &mut Interp) -> R { + ip.charge_gstate()?; + let Obj::GState(n) = ip.pop()? else { return err("typecheck") }; + if let Some(slot) = ip.gstates.get_mut(n) { + *slot = ip.gs.clone(); + } + ip.push(Obj::GState(n)) +} + +pub fn setgstate(ip: &mut Interp) -> R { + ip.charge_gstate()?; + let Obj::GState(n) = ip.pop()? else { return err("typecheck") }; + if let Some(g) = ip.gstates.get(n) { + ip.gs = g.clone(); + } + Ok(()) +} + +// ----- line parameters ----- + +pub fn setlinewidth(ip: &mut Interp) -> R { + ip.gs.line_width = ip.pop_num()?.abs(); + Ok(()) +} + +pub fn currentlinewidth(ip: &mut Interp) -> R { + let w = ip.gs.line_width; + ip.push(Obj::Real(w)) +} + +pub fn setlinecap(ip: &mut Interp) -> R { + ip.gs.cap = ip.pop_int()?.clamp(0, 2); + Ok(()) +} + +pub fn currentlinecap(ip: &mut Interp) -> R { + let v = ip.gs.cap; + ip.push(Obj::Int(v)) +} + +pub fn setlinejoin(ip: &mut Interp) -> R { + ip.gs.join = ip.pop_int()?.clamp(0, 2); + Ok(()) +} + +pub fn currentlinejoin(ip: &mut Interp) -> R { + let v = ip.gs.join; + ip.push(Obj::Int(v)) +} + +pub fn setmiterlimit(ip: &mut Interp) -> R { + ip.gs.miter = ip.pop_num()?.max(1.0); + Ok(()) +} + +pub fn currentmiterlimit(ip: &mut Interp) -> R { + let v = ip.gs.miter; + ip.push(Obj::Real(v)) +} + +pub fn setdash(ip: &mut Interp) -> R { + let phase = ip.pop_num()?; + let a = ip.pop_arr()?; + let mut v = Vec::with_capacity(a.len.min(64)); + for o in a.items().iter().take(64) { + v.push(o.num().ok_or(PsErr::Ps("typecheck"))?); + } + ip.gs.dash = (v, phase); + Ok(()) +} + +pub fn currentdash(ip: &mut Interp) -> R { + let (v, phase) = ip.gs.dash.clone(); + ip.push(Obj::Array(PArr::new(v.into_iter().map(Obj::Real).collect()), false))?; + ip.push(Obj::Real(phase)) +} + +pub fn setflat(ip: &mut Interp) -> R { + ip.gs.flat = ip.pop_num()?.clamp(0.2, 100.0); + Ok(()) +} + +pub fn currentflat(ip: &mut Interp) -> R { + let v = ip.gs.flat; + ip.push(Obj::Real(v)) +} + +pub fn setstrokeadjust(ip: &mut Interp) -> R { + ip.gs.stroke_adjust = ip.pop_bool()?; + Ok(()) +} + +pub fn currentstrokeadjust(ip: &mut Interp) -> R { + let v = ip.gs.stroke_adjust; + ip.push(Obj::Bool(v)) +} + +pub fn setoverprint(ip: &mut Interp) -> R { + ip.gs.overprint = ip.pop_bool()?; + Ok(()) +} + +pub fn currentoverprint(ip: &mut Interp) -> R { + let v = ip.gs.overprint; + ip.push(Obj::Bool(v)) +} + +// ----- matrices ----- + +fn fill_matrix(a: &PArr, m: &M) -> R { + if a.len != 6 { + return err("rangecheck"); + } + for (i, v) in m.0.iter().enumerate() { + a.set(i, Obj::Real(*v)); + } + Ok(()) +} + +pub fn matrix(ip: &mut Interp) -> R { + ip.push(matrix_obj(&M::ID)) +} + +pub fn identmatrix(ip: &mut Interp) -> R { + let a = ip.pop_arr()?; + fill_matrix(&a, &M::ID)?; + ip.push(Obj::Array(a, false)) +} + +pub fn defaultmatrix(ip: &mut Interp) -> R { + identmatrix(ip) +} + +pub fn initmatrix(ip: &mut Interp) -> R { + ip.gs.ctm = M::ID; + Ok(()) +} + +pub fn currentmatrix(ip: &mut Interp) -> R { + let a = ip.pop_arr()?; + fill_matrix(&a, &ip.gs.ctm)?; + ip.push(Obj::Array(a, false)) +} + +pub fn setmatrix(ip: &mut Interp) -> R { + let m = ip.pop_matrix()?; + if !m.finite() { + return err("undefinedresult"); + } + ip.gs.ctm = m; + Ok(()) +} + +/// Operators that either change the CTM or, given a matrix operand, fill it in. +fn modify(ip: &mut Interp, args: usize, make: fn(&[f64]) -> M) -> R { + if let Ok(Obj::Array(a, _)) = ip.top(0).cloned() { + ip.pop()?; + let mut v = vec![0.0; args]; + for slot in v.iter_mut().rev() { + *slot = ip.pop_num()?; + } + fill_matrix(&a, &make(&v))?; + return ip.push(Obj::Array(a, false)); + } + let mut v = vec![0.0; args]; + for slot in v.iter_mut().rev() { + *slot = ip.pop_num()?; + } + let m = make(&v).then(&ip.gs.ctm); + if !m.finite() { + return err("undefinedresult"); + } + ip.gs.ctm = m; + Ok(()) +} + +fn arg(v: &[f64], i: usize) -> f64 { + v.get(i).copied().unwrap_or(0.0) +} + +pub fn translate(ip: &mut Interp) -> R { + modify(ip, 2, |v| M([1.0, 0.0, 0.0, 1.0, arg(v, 0), arg(v, 1)])) +} + +pub fn scale(ip: &mut Interp) -> R { + modify(ip, 2, |v| M([arg(v, 0), 0.0, 0.0, arg(v, 1), 0.0, 0.0])) +} + +pub fn rotate(ip: &mut Interp) -> R { + modify(ip, 1, |v| { + let a = arg(v, 0).to_radians(); + let (s, c) = a.sin_cos(); + M([c, s, -s, c, 0.0, 0.0]) + }) +} + +pub fn concat(ip: &mut Interp) -> R { + let m = ip.pop_matrix()?; + let r = m.then(&ip.gs.ctm); + if !r.finite() { + return err("undefinedresult"); + } + ip.gs.ctm = r; + Ok(()) +} + +pub fn concatmatrix(ip: &mut Interp) -> R { + let dst = ip.pop_arr()?; + let m2 = ip.pop_matrix()?; + let m1 = ip.pop_matrix()?; + fill_matrix(&dst, &m1.then(&m2))?; + ip.push(Obj::Array(dst, false)) +} + +pub fn invertmatrix(ip: &mut Interp) -> R { + let dst = ip.pop_arr()?; + let m = ip.pop_matrix()?; + let inv = m.inv().ok_or(PsErr::Ps("undefinedresult"))?; + fill_matrix(&dst, &inv)?; + ip.push(Obj::Array(dst, false)) +} + +fn xform(ip: &mut Interp, f: fn(&M, f64, f64) -> Option<(f64, f64)>) -> R { + let m = match ip.top(0)? { + Obj::Array(..) => ip.pop_matrix()?, + _ => ip.gs.ctm, + }; + let y = ip.pop_num()?; + let x = ip.pop_num()?; + let (x, y) = f(&m, x, y).ok_or(PsErr::Ps("undefinedresult"))?; + ip.push(Obj::Real(x))?; + ip.push(Obj::Real(y)) +} + +pub fn transform(ip: &mut Interp) -> R { + xform(ip, |m, x, y| Some(m.apply(x, y))) +} + +pub fn itransform(ip: &mut Interp) -> R { + xform(ip, |m, x, y| Some(m.inv()?.apply(x, y))) +} + +pub fn dtransform(ip: &mut Interp) -> R { + xform(ip, |m, x, y| Some(m.delta(x, y))) +} + +pub fn idtransform(ip: &mut Interp) -> R { + xform(ip, |m, x, y| Some(m.inv()?.delta(x, y))) +} + +// ----- paths ----- + +fn add_seg(ip: &mut Interp, s: Seg) -> R { + if ip.gs.path.len() >= MAX_PATH { + return Err(PsErr::Fatal("PostScript (path limit)".into())); + } + ip.gs.path.push(s); + Ok(()) +} + +pub fn newpath(ip: &mut Interp) -> R { + ip.gs.path.clear(); + ip.gs.cur = None; + ip.gs.start = None; + Ok(()) +} + +fn user_point(ip: &mut Interp) -> R<(f64, f64)> { + let y = ip.pop_num()?; + let x = ip.pop_num()?; + Ok(ip.gs.ctm.apply(x, y)) +} + +fn rel_point(ip: &mut Interp) -> R<(f64, f64)> { + let dy = ip.pop_num()?; + let dx = ip.pop_num()?; + let (cx, cy) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let (dx, dy) = ip.gs.ctm.delta(dx, dy); + Ok((cx + dx, cy + dy)) +} + +fn move_dev(ip: &mut Interp, p: (f64, f64)) -> R { + // Consecutive movetos keep only the last. + if let Some(Seg::Move(..)) = ip.gs.path.last() { + ip.gs.path.pop(); + } + add_seg(ip, Seg::Move(p.0, p.1))?; + ip.gs.cur = Some(p); + ip.gs.start = Some(p); + Ok(()) +} + +fn line_dev(ip: &mut Interp, p: (f64, f64)) -> R { + if ip.gs.cur.is_none() { + return err("nocurrentpoint"); + } + if matches!(ip.gs.path.last(), Some(Seg::Close)) + && let Some(s) = ip.gs.start + { + add_seg(ip, Seg::Move(s.0, s.1))?; + } + add_seg(ip, Seg::Line(p.0, p.1))?; + ip.gs.cur = Some(p); + Ok(()) +} + +fn curve_dev(ip: &mut Interp, a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> R { + if ip.gs.cur.is_none() { + return err("nocurrentpoint"); + } + if matches!(ip.gs.path.last(), Some(Seg::Close)) + && let Some(s) = ip.gs.start + { + add_seg(ip, Seg::Move(s.0, s.1))?; + } + add_seg(ip, Seg::Curve(a.0, a.1, b.0, b.1, c.0, c.1))?; + ip.gs.cur = Some(c); + Ok(()) +} + +pub fn moveto(ip: &mut Interp) -> R { + let p = user_point(ip)?; + move_dev(ip, p) +} + +pub fn rmoveto(ip: &mut Interp) -> R { + let p = rel_point(ip)?; + move_dev(ip, p) +} + +pub fn lineto(ip: &mut Interp) -> R { + let p = user_point(ip)?; + line_dev(ip, p) +} + +pub fn rlineto(ip: &mut Interp) -> R { + let p = rel_point(ip)?; + line_dev(ip, p) +} + +pub fn curveto(ip: &mut Interp) -> R { + let c = user_point(ip)?; + let b = user_point(ip)?; + let a = user_point(ip)?; + curve_dev(ip, a, b, c) +} + +pub fn rcurveto(ip: &mut Interp) -> R { + let mut v = [0.0; 6]; + for slot in v.iter_mut().rev() { + *slot = ip.pop_num()?; + } + let (cx, cy) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let m = ip.gs.ctm; + let d = |x: f64, y: f64| { + let (dx, dy) = m.delta(x, y); + (cx + dx, cy + dy) + }; + curve_dev(ip, d(v[0], v[1]), d(v[2], v[3]), d(v[4], v[5])) +} + +pub fn closepath(ip: &mut Interp) -> R { + // Keep a Close element for every explicit operator call, as existing EPS consumers do. + // Consecutive closes paint identically, but each one counts toward bounded path storage. + if ip.gs.cur.is_some() { + add_seg(ip, Seg::Close)?; + ip.gs.cur = ip.gs.start; + } + Ok(()) +} + +fn arc_common(ip: &mut Interp, negative: bool) -> R { + let a1 = ip.pop_num()?; + let a0 = ip.pop_num()?; + let r = ip.pop_num()?; + let cy = ip.pop_num()?; + let cx = ip.pop_num()?; + let (sweep, shortened) = bounded_arc_sweep(a0, a1, negative); + if shortened { + ip.warnings.push("arc (too many turns)".into()); + } + let start_angle = a0 % 360.0; + let available = MAX_PATH.saturating_sub(ip.gs.path.len()); + let max_curves = available.saturating_sub(1); + let connector = 1 + usize::from(ip.gs.cur.is_some() && matches!(ip.gs.path.last(), Some(Seg::Close))); + ip.alloc(connector.min(available).saturating_mul(SEG_BYTES))?; + if let Some(curves) = arc_curve_count(r, start_angle, start_angle + sweep, max_curves) { + ip.charge(curves as u64)?; + ip.alloc(curves.saturating_mul(std::mem::size_of::<[f64; 6]>()).saturating_add(curves.saturating_mul(SEG_BYTES)))?; + } + let (start, curves, truncated) = arc_curves(cx, cy, r, start_angle, start_angle + sweep, available.saturating_sub(1)); + let m = ip.gs.ctm; + let s = m.apply(start.0, start.1); + if ip.gs.cur.is_some() { + line_dev(ip, s)? + } else { + move_dev(ip, s)? + } + for c in curves { + curve_dev(ip, m.apply(c[0], c[1]), m.apply(c[2], c[3]), m.apply(c[4], c[5]))?; + } + if truncated { + return Err(PsErr::Fatal("PostScript (path limit)".into())); + } + Ok(()) +} + +pub fn arc(ip: &mut Interp) -> R { + arc_common(ip, false) +} + +pub fn arcn(ip: &mut Interp) -> R { + arc_common(ip, true) +} + +/// `arct` and `arcto`: a line toward (x1, y1), then an arc of radius r tangent to both lines. +fn arct_common(ip: &mut Interp, push_points: bool) -> R { + let r = ip.pop_num()?; + let y2 = ip.pop_num()?; + let x2 = ip.pop_num()?; + let y1 = ip.pop_num()?; + let x1 = ip.pop_num()?; + let inv = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?; + let (dx0, dy0) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let (x0, y0) = inv.apply(dx0, dy0); + let (ux, uy) = (x0 - x1, y0 - y1); + let (vx, vy) = (x2 - x1, y2 - y1); + let (lu, lv) = (ux.hypot(uy), vx.hypot(vy)); + let m = ip.gs.ctm; + if lu == 0.0 || lv == 0.0 || r == 0.0 { + line_dev(ip, m.apply(x1, y1))?; + if push_points { + for v in [x1, y1, x1, y1] { + ip.push(Obj::Real(v))?; + } + } + return Ok(()); + } + let cos = ((ux * vx + uy * vy) / (lu * lv)).clamp(-1.0, 1.0); + let theta = cos.acos(); + let t = r / (theta / 2.0).tan(); + if !t.is_finite() { + line_dev(ip, m.apply(x1, y1))?; + return Ok(()); + } + let (t1x, t1y) = (x1 + ux / lu * t, y1 + uy / lu * t); + let (t2x, t2y) = (x1 + vx / lv * t, y1 + vy / lv * t); + line_dev(ip, m.apply(t1x, t1y))?; + // One cubic for the arc between the tangent points. + let sweep = std::f64::consts::PI - theta; + let k = 4.0 / 3.0 * (sweep / 4.0).tan(); + let c1 = (t1x + (x1 - t1x) / t.max(1e-12) * k * r, t1y + (y1 - t1y) / t.max(1e-12) * k * r); + let c2 = (t2x + (x1 - t2x) / t.max(1e-12) * k * r, t2y + (y1 - t2y) / t.max(1e-12) * k * r); + curve_dev(ip, m.apply(c1.0, c1.1), m.apply(c2.0, c2.1), m.apply(t2x, t2y))?; + if push_points { + for v in [t1x, t1y, t2x, t2y] { + ip.push(Obj::Real(v))?; + } + } + Ok(()) +} + +pub fn arct(ip: &mut Interp) -> R { + arct_common(ip, false) +} + +pub fn arcto(ip: &mut Interp) -> R { + arct_common(ip, true) +} + +pub fn currentpoint(ip: &mut Interp) -> R { + let (x, y) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let (x, y) = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?.apply(x, y); + ip.push(Obj::Real(x))?; + ip.push(Obj::Real(y)) +} + +pub fn flattenpath(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len().saturating_mul(16))?; + let tol = ip.gs.flat; + let flat = flatten(&ip.gs.path, tol); + if flat.len() > MAX_PATH { + return err("limitcheck"); + } + ip.gs.path = flat; + Ok(()) +} + +pub fn reversepath(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len())?; + // Reverse each subpath. + let mut out = Vec::with_capacity(ip.gs.path.len()); + let mut sub: Vec<Seg> = Vec::new(); + let flush = |sub: &mut Vec<Seg>, out: &mut Vec<Seg>| { + let closed = matches!(sub.last(), Some(Seg::Close)); + let pts: Vec<(f64, f64, Option<[f64; 4]>)> = sub + .iter() + .filter_map(|s| match *s { + Seg::Move(x, y) | Seg::Line(x, y) => Some((x, y, None)), + Seg::Curve(a, b, c, d, e, f) => Some((e, f, Some([a, b, c, d]))), + Seg::Close => None, + }) + .collect(); + if let Some(last) = pts.last() { + out.push(Seg::Move(last.0, last.1)); + for i in (1..pts.len()).rev() { + let (Some(cur), Some(prev)) = (pts.get(i), pts.get(i - 1)) else { continue }; + match cur.2 { + Some([a, b, c, d]) => out.push(Seg::Curve(c, d, a, b, prev.0, prev.1)), + None => out.push(Seg::Line(prev.0, prev.1)), + } + } + if closed { + out.push(Seg::Close); + } + } + sub.clear(); + }; + for s in ip.gs.path.clone() { + if matches!(s, Seg::Move(..)) { + flush(&mut sub, &mut out); + } + sub.push(s); + } + flush(&mut sub, &mut out); + ip.gs.path = out; + Ok(()) +} + +/// `strokepath`: the outline of what `stroke` would paint, as the current path. The pen is +/// shaped in user space (width, caps, joins, miter limit, dashes), as for `stroke`. +pub fn strokepath(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len().saturating_mul(4))?; + use kurbo::{Cap, Join, PathEl, Point, Stroke, StrokeOpts}; + let ctm = ip.gs.ctm; + let Some(inv) = ctm.inv() else { + ip.gs.path.clear(); + return Ok(()); + }; + let p = |x: f64, y: f64| { + let (x, y) = inv.apply(x, y); + Point::new(x, y) + }; + let mut els = Vec::with_capacity(ip.gs.path.len()); + for s in &ip.gs.path { + els.push(match *s { + Seg::Move(x, y) => PathEl::MoveTo(p(x, y)), + Seg::Line(x, y) => PathEl::LineTo(p(x, y)), + Seg::Curve(a, b, c, d, e, f) => PathEl::CurveTo(p(a, b), p(c, d), p(e, f)), + Seg::Close => PathEl::ClosePath, + }); + } + let g = &ip.gs; + let cap = match g.cap { + 1 => Cap::Round, + 2 => Cap::Square, + _ => Cap::Butt, + }; + let join = match g.join { + 1 => Join::Round, + 2 => Join::Bevel, + _ => Join::Miter, + }; + let mut style = Stroke::new(g.line_width.max(1e-3)).with_caps(cap).with_join(join).with_miter_limit(g.miter.max(1.0)); + let user: Vec<Seg> = g.path.iter().map(|s| s.map(&inv)).collect(); + if !user.iter().all(|s| match *s { + Seg::Move(x, y) | Seg::Line(x, y) => x.is_finite() && y.is_finite(), + Seg::Curve(a, b, c, d, e, f) => [a, b, c, d, e, f].iter().all(|v| v.is_finite()), + Seg::Close => true, + }) { + ip.gs.path.clear(); + return Ok(()); + } + if crate::read::gstate::dashes_ok(&user, &g.dash.0) && g.dash.1.is_finite() { + style = style.with_dashes(g.dash.1, g.dash.0.clone()); + } + // Tolerance in user space, about a twentieth of a device unit. + let scale = (ctm.0[0] * ctm.0[3] - ctm.0[1] * ctm.0[2]).abs().sqrt().max(1e-9); + let out = kurbo::stroke(els, &style, &StrokeOpts::default(), (0.05 / scale).max(1e-6)); + let mut path = Vec::with_capacity(out.elements().len()); + let mut cur = (0.0, 0.0); + for el in out.elements() { + if path.len() >= MAX_PATH { + return err("limitcheck"); + } + let d = |q: Point| ctm.apply(q.x, q.y); + match *el { + PathEl::MoveTo(q) => { + cur = d(q); + path.push(Seg::Move(cur.0, cur.1)); + } + PathEl::LineTo(q) => { + cur = d(q); + path.push(Seg::Line(cur.0, cur.1)); + } + PathEl::QuadTo(c, q) => { + let (c, e) = (d(c), d(q)); + let a = (cur.0 + 2.0 / 3.0 * (c.0 - cur.0), cur.1 + 2.0 / 3.0 * (c.1 - cur.1)); + let b = (e.0 + 2.0 / 3.0 * (c.0 - e.0), e.1 + 2.0 / 3.0 * (c.1 - e.1)); + path.push(Seg::Curve(a.0, a.1, b.0, b.1, e.0, e.1)); + cur = e; + } + PathEl::CurveTo(a, b, q) => { + let (a, b, e) = (d(a), d(b), d(q)); + path.push(Seg::Curve(a.0, a.1, b.0, b.1, e.0, e.1)); + cur = e; + } + PathEl::ClosePath => path.push(Seg::Close), + } + } + ip.gs.path = path; + ip.gs.cur = Some(cur); + Ok(()) +} + +pub fn pathbbox(ip: &mut Interp) -> R { + ip.charge(ip.gs.path.len() as u64 / 4 + 1)?; + let b = bbox(&ip.gs.path).ok_or(PsErr::Ps("nocurrentpoint"))?; + let inv = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?; + let corners = [inv.apply(b[0], b[1]), inv.apply(b[2], b[1]), inv.apply(b[0], b[3]), inv.apply(b[2], b[3])]; + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for (x, y) in corners { + x0 = x0.min(x); + y0 = y0.min(y); + x1 = x1.max(x); + y1 = y1.max(y); + } + for v in [x0, y0, x1, y1] { + ip.push(Obj::Real(v))?; + } + Ok(()) +} + +pub fn pathforall(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len())?; + let close = ip.pop()?; + let curve = ip.pop()?; + let line = ip.pop()?; + let mv = ip.pop()?; + let inv = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?; + for s in ip.gs.path.clone() { + let (proc, pts) = match s { + Seg::Move(x, y) => (&mv, vec![inv.apply(x, y)]), + Seg::Line(x, y) => (&line, vec![inv.apply(x, y)]), + Seg::Curve(a, b, c, d, e, f) => (&curve, vec![inv.apply(a, b), inv.apply(c, d), inv.apply(e, f)]), + Seg::Close => (&close, vec![]), + }; + for (x, y) in pts { + ip.push(Obj::Real(x))?; + ip.push(Obj::Real(y))?; + } + ip.call(proc.clone())?; + } + Ok(()) +} + +pub fn rect_path(ip: &mut Interp) -> R<Vec<Seg>> { + let mut rects: Vec<[f64; 4]> = Vec::new(); + match ip.pop()? { + Obj::Array(a, _) => { + ip.charge_path(a.len)?; + let v: Vec<f64> = a.items().iter().filter_map(Obj::num).collect(); + for r in v.as_chunks::<4>().0 { + rects.push(*r); + } + } + Obj::Str(_, _) => return err("typecheck"), + h => { + let h = h.num().ok_or(PsErr::Ps("typecheck"))?; + let w = ip.pop_num()?; + let y = ip.pop_num()?; + let x = ip.pop_num()?; + rects.push([x, y, w, h]); + } + } + let m = ip.gs.ctm; + let mut path = Vec::with_capacity(rects.len() * 5); + for [x, y, w, h] in rects { + let p = |a: f64, b: f64| m.apply(a, b); + let (a, b, c, d) = (p(x, y), p(x + w, y), p(x + w, y + h), p(x, y + h)); + path.extend([Seg::Move(a.0, a.1), Seg::Line(b.0, b.1), Seg::Line(c.0, c.1), Seg::Line(d.0, d.1), Seg::Close]); + } + Ok(path) +} + +// ----- painting ----- + +pub fn fill_path(ip: &mut Interp, path: &[Seg], eo: bool) -> R { + ip.charge(path.len() as u64 / 4 + 1)?; + if ip.gs.nulldev { + return Ok(()); + } + if matches!(ip.gs.space, Space::Pattern) && crate::read::ops::shading::fill_pattern(ip, path, eo)? { + return Ok(()); + } + let color = current_color(ip)?; + ip.out.fill(&ip.gs.clip, path, eo, color).map_err(PsErr::Fatal) +} + +pub fn fill(ip: &mut Interp) -> R { + let path = std::mem::take(&mut ip.gs.path); + fill_path(ip, &path, false)?; + newpath(ip) +} + +pub fn eofill(ip: &mut Interp) -> R { + let path = std::mem::take(&mut ip.gs.path); + fill_path(ip, &path, true)?; + newpath(ip) +} + +pub fn stroke_path(ip: &mut Interp, path: &[Seg]) -> R { + ip.charge_path(path.len())?; + if ip.gs.nulldev { + return Ok(()); + } + let color = current_color(ip)?; + let g = &ip.gs; + let p = StrokeParams { width: g.line_width, cap: g.cap, join: g.join, miter: g.miter, dash: &g.dash }; + ip.out.stroke(&g.clip, path, &g.ctm, &p, color).map_err(PsErr::Fatal) +} + +pub fn stroke(ip: &mut Interp) -> R { + let path = std::mem::take(&mut ip.gs.path); + stroke_path(ip, &path)?; + newpath(ip) +} + +pub fn rectfill(ip: &mut Interp) -> R { + let path = rect_path(ip)?; + fill_path(ip, &path, false) +} + +pub fn rectstroke(ip: &mut Interp) -> R { + // An optional matrix operand changes the pen: applied to the CTM for this stroke. + let m = match ip.top(0)? { + Obj::Array(a, _) if a.len == 6 && ip.o.len() >= 2 && !matches!(ip.top(1), Ok(Obj::Array(..)) | Err(_)) => Some(ip.pop_matrix()?), + _ => None, + }; + let path = rect_path(ip)?; + match m { + Some(m) => { + let saved = ip.gs.ctm; + ip.gs.ctm = m.then(&saved); + let r = stroke_path(ip, &path); + ip.gs.ctm = saved; + r + } + None => stroke_path(ip, &path), + } +} + +fn clip_with(ip: &mut Interp, path: Vec<Seg>, eo: bool) -> R { + let depth = ip.gs.clip.as_ref().map_or(0, |c| c.depth + 1); + if depth > 2000 { + return err("limitcheck"); + } + ip.gs.clip = Some(Rc::new(Clip { path, eo, parent: ip.gs.clip.clone(), depth })); + Ok(()) +} + +pub fn clip(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len())?; + let path = ip.gs.path.clone(); + clip_with(ip, path, false) +} + +pub fn eoclip(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len())?; + let path = ip.gs.path.clone(); + clip_with(ip, path, true) +} + +pub fn rectclip(ip: &mut Interp) -> R { + let path = rect_path(ip)?; + clip_with(ip, path, false)?; + newpath(ip) +} + +pub fn clipsave(ip: &mut Interp) -> R { + if ip.gs.clip_saves.len() >= 1000 { + return err("limitcheck"); + } + let c = ip.gs.clip.clone(); + ip.gs.clip_saves.push(c); + Ok(()) +} + +pub fn cliprestore(ip: &mut Interp) -> R { + if let Some(c) = ip.gs.clip_saves.pop() { + ip.gs.clip = c; + } + Ok(()) +} + +pub fn initclip(ip: &mut Interp) -> R { + ip.gs.clip = None; + Ok(()) +} + +pub fn clippath(ip: &mut Interp) -> R { + let n = ip.gs.clip.as_ref().map_or(0, |c| c.path.len()); + ip.charge_path(n)?; + let path = match &ip.gs.clip { + Some(c) => c.path.clone(), + None => { + // The whole page: a generous square. + let s = 1.0e5; + vec![Seg::Move(-s, -s), Seg::Line(s, -s), Seg::Line(s, s), Seg::Line(-s, s), Seg::Close] + } + }; + ip.gs.cur = path.iter().rev().find_map(|s| match s { + Seg::Move(x, y) | Seg::Line(x, y) => Some((*x, *y)), + _ => None, + }); + ip.gs.path = path; + Ok(()) +} + +// ----- colour ----- + +/// A colour space from a name or array operand. +pub fn parse_space(ip: &mut Interp, o: &Obj, depth: usize) -> R<Space> { + if depth > 8 { + return err("limitcheck"); + } + let (family, params) = match o { + Obj::Name(n, _) => (n.to_vec(), Vec::new()), + Obj::Array(a, _) => { + let items = a.items(); + match items.first() { + Some(Obj::Name(n, _)) => (n.to_vec(), items.get(1..).map(<[Obj]>::to_vec).unwrap_or_default()), + _ => return err("typecheck"), + } + } + _ => return err("typecheck"), + }; + Ok(match family.as_slice() { + b"DeviceGray" | b"CalGray" | b"G" | b"CIEBasedA" => Space::Gray, + b"DeviceRGB" | b"CalRGB" | b"RGB" | b"CIEBasedABC" | b"CIEBasedDEF" => Space::Rgb, + b"DeviceCMYK" | b"CMYK" | b"CIEBasedDEFG" => Space::Cmyk, + b"Lab" => Space::Lab, + b"Pattern" => Space::Pattern, + b"ICCBased" => { + let n = match params.first() { + Some(Obj::Dict(d)) => d.get_name(b"N").and_then(|o| o.num()).unwrap_or(3.0) as usize, + _ => 3, + }; + match n { + 1 => Space::Gray, + 4 => Space::Cmyk, + _ => Space::Rgb, + } + } + b"Separation" | b"DeviceN" => { + let names = match params.first() { + Some(Obj::Array(a, _)) => a.items().iter().map(crate::read::ops::basic::text_of).collect(), + Some(o) => vec![crate::read::ops::basic::text_of(o)], + None => return err("rangecheck"), + }; + let alt = parse_space(ip, params.get(1).ok_or(PsErr::Ps("rangecheck"))?, depth + 1)?; + let tint = params.get(2).cloned().ok_or(PsErr::Ps("rangecheck"))?; + Space::Tint { names, alt: Box::new(alt), tint } + } + b"Indexed" | b"I" => { + let base = parse_space(ip, params.first().ok_or(PsErr::Ps("rangecheck"))?, depth + 1)?; + let hival = params.get(1).and_then(Obj::num).unwrap_or(0.0).clamp(0.0, 4095.0) as usize; + let n = base.comps(); + let lookup = match params.get(2) { + Some(Obj::Str(s, _)) => s.bytes(), + Some(p @ Obj::Array(_, true)) => { + let mut out = Vec::with_capacity((hival + 1) * n); + for i in 0..=hival { + ip.push(Obj::Int(i as i64))?; + ip.call(p.clone())?; + let mut comps = vec![0.0; n]; + for c in comps.iter_mut().rev() { + *c = ip.pop_num()?; + } + out.extend(comps.iter().map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8)); + } + out + } + _ => return err("typecheck"), + }; + Space::Indexed { base: Box::new(base), hival, lookup } + } + _ => return err("undefined"), + }) +} + +/// Evaluate a tint transform (a procedure or a Type 2 function dictionary) on `comps`. +fn eval_tint(ip: &mut Interp, tint: &Obj, comps: &[f64], out_n: usize) -> R<Vec<f64>> { + match tint { + Obj::Dict(d) => { + // Type 2 exponential: C0 + x^N (C1 − C0). + let get = |k: &[u8], dflt: f64| -> Vec<f64> { + match d.get_name(k) { + Some(Obj::Array(a, _)) => a.items().iter().filter_map(Obj::num).collect(), + _ => vec![dflt; out_n], + } + }; + let c0 = get(b"C0", 0.0); + let c1 = get(b"C1", 1.0); + let n = d.get_name(b"N").and_then(|o| o.num()).unwrap_or(1.0); + let x = comps.first().copied().unwrap_or(0.0).clamp(0.0, 1.0).powf(n); + Ok((0..out_n) + .map(|i| c0.get(i).copied().unwrap_or(0.0) + x * (c1.get(i).copied().unwrap_or(1.0) - c0.get(i).copied().unwrap_or(0.0))) + .collect()) + } + _ => { + for c in comps { + ip.push(Obj::Real(*c))?; + } + ip.call(tint.clone())?; + let mut v = vec![0.0; out_n]; + for slot in v.iter_mut().rev() { + *slot = ip.pop_num()?; + } + Ok(v) + } + } +} + +pub fn lab_to_rgb(l: f64, a: f64, b: f64) -> (f64, f64, f64) { + let fy = (l + 16.0) / 116.0; + let fx = fy + a / 500.0; + let fz = fy - b / 200.0; + let g = |t: f64| if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f64 / 29.0).powi(2) * (t - 4.0 / 29.0) }; + let (x, y, z) = (0.9505 * g(fx), g(fy), 1.089 * g(fz)); + let lin = [3.2406 * x - 1.5372 * y - 0.4986 * z, -0.9689 * x + 1.8758 * y + 0.0415 * z, 0.0557 * x - 0.2040 * y + 1.0570 * z]; + let enc = |c: f64| { + let c = c.clamp(0.0, 1.0); + if c <= 0.0031308 { 12.92 * c } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 } + }; + (enc(lin[0]), enc(lin[1]), enc(lin[2])) +} + +/// A colour in `space` as a device colour. +pub fn to_device(ip: &mut Interp, space: &Space, comps: &[f64], depth: usize) -> R<DevColor> { + if depth > 8 { + return err("limitcheck"); + } + let c = |i: usize| comps.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0); + Ok(match space { + Space::Gray => DevColor::Gray(c(0)), + Space::Rgb => DevColor::Rgb(c(0), c(1), c(2)), + Space::Cmyk => DevColor::Cmyk(c(0), c(1), c(2), c(3)), + Space::Lab => { + let (r, g, b) = + lab_to_rgb(comps.first().copied().unwrap_or(0.0), comps.get(1).copied().unwrap_or(0.0), comps.get(2).copied().unwrap_or(0.0)); + DevColor::Rgb(r, g, b) + } + Space::Tint { names, alt, tint } => { + // The colourant "None" paints nothing; "All" is registration black. + if names.len() == 1 && names.first().is_some_and(|n| n == b"All") { + return Ok(DevColor::Cmyk(c(0), c(0), c(0), c(0))); + } + let v = eval_tint(ip, &tint.clone(), comps, alt.comps())?; + to_device(ip, &alt.clone(), &v, depth + 1)? + } + Space::Indexed { base, hival, lookup } => { + let i = (comps.first().copied().unwrap_or(0.0).round().max(0.0) as usize).min(*hival); + let n = base.comps(); + let v: Vec<f64> = (0..n).map(|k| f64::from(lookup.get(i * n + k).copied().unwrap_or(0)) / 255.0).collect(); + to_device(ip, &base.clone(), &v, depth + 1)? + } + // Patterns aren't painted yet: a mid grey stands in. + Space::Pattern => DevColor::Gray(0.5), + }) +} + +pub fn current_color(ip: &mut Interp) -> R<DevColor> { + let space = ip.gs.space.clone(); + let comps = ip.gs.color.clone(); + to_device(ip, &space, &comps, 0) +} + +fn set_space(ip: &mut Interp, space: Space) { + if ip.gs.color_locked { + return; + } + ip.gs.color = space.initial(); + ip.gs.space = space; + ip.gs.pattern = None; +} + +/// Set the colour values (not inside an uncoloured pattern cell). +fn set_color(ip: &mut Interp, v: Vec<f64>) { + if !ip.gs.color_locked { + ip.gs.color = v; + } +} + +pub fn setgray(ip: &mut Interp) -> R { + let g = ip.pop_num()?; + set_space(ip, Space::Gray); + set_color(ip, vec![g]); + Ok(()) +} + +pub fn setrgbcolor(ip: &mut Interp) -> R { + let b = ip.pop_num()?; + let g = ip.pop_num()?; + let r = ip.pop_num()?; + set_space(ip, Space::Rgb); + set_color(ip, vec![r, g, b]); + Ok(()) +} + +pub fn setcmykcolor(ip: &mut Interp) -> R { + let k = ip.pop_num()?; + let y = ip.pop_num()?; + let m = ip.pop_num()?; + let c = ip.pop_num()?; + set_space(ip, Space::Cmyk); + set_color(ip, vec![c, m, y, k]); + Ok(()) +} + +pub fn sethsbcolor(ip: &mut Interp) -> R { + let v = ip.pop_num()?.clamp(0.0, 1.0); + let s = ip.pop_num()?.clamp(0.0, 1.0); + let h = ip.pop_num()?.rem_euclid(1.0) * 6.0; + let i = h.floor(); + let f = h - i; + let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); + let (r, g, b) = match i as i64 { + 0 => (v, t, p), + 1 => (q, v, p), + 2 => (p, v, t), + 3 => (p, q, v), + 4 => (t, p, v), + _ => (v, p, q), + }; + set_space(ip, Space::Rgb); + set_color(ip, vec![r, g, b]); + Ok(()) +} + +pub fn currentgray(ip: &mut Interp) -> R { + let g = match current_color(ip)? { + DevColor::Gray(g) => g, + DevColor::Rgb(r, g, b) => 0.3 * r + 0.59 * g + 0.11 * b, + DevColor::Cmyk(c, m, y, k) => 1.0 - (0.3 * c + 0.59 * m + 0.11 * y + k).min(1.0), + }; + ip.push(Obj::Real(g)) +} + +fn rgb_of(d: DevColor) -> (f64, f64, f64) { + match d { + DevColor::Gray(g) => (g, g, g), + DevColor::Rgb(r, g, b) => (r, g, b), + DevColor::Cmyk(c, m, y, k) => (1.0 - (c + k).min(1.0), 1.0 - (m + k).min(1.0), 1.0 - (y + k).min(1.0)), + } +} + +pub fn currentrgbcolor(ip: &mut Interp) -> R { + let (r, g, b) = rgb_of(current_color(ip)?); + for v in [r, g, b] { + ip.push(Obj::Real(v))?; + } + Ok(()) +} + +pub fn currenthsbcolor(ip: &mut Interp) -> R { + let (r, g, b) = rgb_of(current_color(ip)?); + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let d = max - min; + let h = if d == 0.0 { + 0.0 + } else if max == r { + ((g - b) / d).rem_euclid(6.0) / 6.0 + } else if max == g { + ((b - r) / d + 2.0) / 6.0 + } else { + ((r - g) / d + 4.0) / 6.0 + }; + let s = if max == 0.0 { 0.0 } else { d / max }; + for v in [h, s, max] { + ip.push(Obj::Real(v))?; + } + Ok(()) +} + +pub fn currentcmykcolor(ip: &mut Interp) -> R { + let (c, m, y, k) = match current_color(ip)? { + DevColor::Cmyk(c, m, y, k) => (c, m, y, k), + DevColor::Gray(g) => (0.0, 0.0, 0.0, 1.0 - g), + DevColor::Rgb(r, g, b) => { + let (c, m, y) = (1.0 - r, 1.0 - g, 1.0 - b); + let k = c.min(m).min(y); + (c - k, m - k, y - k, k) + } + }; + for v in [c, m, y, k] { + ip.push(Obj::Real(v))?; + } + Ok(()) +} + +pub fn setcolorspace(ip: &mut Interp) -> R { + let o = ip.pop()?; + let space = parse_space(ip, &o, 0)?; + let base = match (&space, &o) { + (Space::Pattern, Obj::Array(a, _)) => match a.get(1) { + Some(b) => Some(Box::new(parse_space(ip, &b, 1)?)), + None => None, + }, + _ => None, + }; + set_space(ip, space); + if !ip.gs.color_locked { + ip.gs.pattern_base = base; + } + Ok(()) +} + +pub fn currentcolorspace(ip: &mut Interp) -> R { + let n: &[u8] = match ip.gs.space { + Space::Gray => b"DeviceGray", + Space::Rgb => b"DeviceRGB", + Space::Cmyk => b"DeviceCMYK", + Space::Pattern => b"Pattern", + Space::Lab => b"Lab", + Space::Indexed { .. } => b"Indexed", + Space::Tint { .. } => b"Separation", + }; + ip.push(Obj::Array(PArr::new(vec![Obj::lit(n)]), false)) +} + +pub fn setcolor(ip: &mut Interp) -> R { + if let Space::Pattern = ip.gs.space { + // An uncoloured pattern comes after its colour: `c1 … cn pattern setcolor`. + if let Obj::Dict(d) = ip.pop()? + && !ip.gs.color_locked + { + let uncolored = d.get_name(b"PaintType").and_then(|o| o.num()) == Some(2.0); + let mut under = Vec::new(); + while uncolored && ip.top(0).is_ok_and(|o| o.num().is_some()) && under.len() < 4 { + under.push(ip.pop_num()?); + } + under.reverse(); + ip.gs.color = under; + ip.gs.pattern = Some(d); + } + return Ok(()); + } + let n = ip.gs.space.comps(); + let mut v = vec![0.0; n]; + for slot in v.iter_mut().rev() { + *slot = ip.pop_num()?; + } + set_color(ip, v); + Ok(()) +} + +pub fn currentcolor(ip: &mut Interp) -> R { + for v in ip.gs.color.clone() { + ip.push(Obj::Real(v))?; + } + Ok(()) +} + +pub fn setpattern(ip: &mut Interp) -> R { + let d: PDict = ip.pop_dict()?; + if ip.gs.color_locked { + return Ok(()); + } + // Under an uncoloured pattern, the current colour stays its colour. + let under = ip.gs.color.clone(); + set_space(ip, Space::Pattern); + if d.get_name(b"PaintType").and_then(|o| o.num()) == Some(2.0) { + ip.gs.color = under; + } + ip.gs.pattern = Some(d); + Ok(()) +} + +/// A pattern instance: a copy of the prototype with its pattern space (matrix · CTM). +pub fn makepattern(ip: &mut Interp) -> R { + let m = ip.pop_matrix()?; + let d = ip.pop_dict()?; + let inst = PDict::new(d.len() + 2); + for (k, v) in d.entries() { + inst.put(k, v); + } + inst.put_name(b"CraftPsMatrix", matrix_obj(&m.then(&ip.gs.ctm))); + ip.push(Obj::Dict(inst)) +} diff --git a/crates/ps/src/read/ops/image.rs b/crates/ps/src/read/ops/image.rs new file mode 100644 index 000000000..a58864d6d --- /dev/null +++ b/crates/ps/src/read/ops/image.rs @@ -0,0 +1,374 @@ +//! Sampled images: `image`, `colorimage`, `imagemask`. + +use crate::read::gstate::{DevColor, M, Space}; +use crate::read::interp::{Interp, PsErr, R, err, matrix_of}; +use crate::read::obj::{Obj, PDict}; +use crate::read::ops::gfx; +use crate::read::pdf::{Image, ImgSpace}; + +/// The most samples one image may hold. +const MAX_SAMPLES: usize = 400_000_000; + +/// Where samples come from: a string (reused), a file, or a procedure (called for more). +fn read_source(ip: &mut Interp, src: &Obj, need: usize) -> R<(Vec<u8>, bool)> { + let mut out = Vec::new(); + match src { + Obj::Str(s, _) => { + let b = s.bytes(); + if b.is_empty() { + return Ok((vec![0; need], false)); + } + while out.len() < need { + out.extend_from_slice(&b); + } + } + Obj::File(id) => { + if let Some(raw) = ip.srcs.dct(*id) { + return Ok((raw.to_vec(), true)); + } + while out.len() < need { + match ip.srcs.read(*id) { + Some(c) => out.push(c), + None => break, + } + } + // A filter is read to its end, as printers do: its end marker is part of the data. + if ip.srcs.is_filter(*id) { + ip.srcs.drain(*id); + } + } + p @ Obj::Array(_, true) => { + let mut empty_runs = 0; + while out.len() < need { + ip.call(p.clone())?; + let s = ip.pop_str()?; + let b = s.bytes(); + if b.is_empty() { + empty_runs += 1; + if empty_runs > 1 || out.is_empty() { + break; + } + continue; + } + out.extend_from_slice(&b); + } + } + _ => return err("typecheck"), + } + out.resize(need, 0); + Ok((out, false)) +} + +struct Params { + w: usize, + h: usize, + bpc: usize, + matrix: M, + sources: Vec<Obj>, + decode: Option<Vec<f64>>, + interpolate: bool, +} + +fn dict_params(ip: &mut Interp, d: &PDict, comps: usize) -> R<Params> { + let num = |k: &[u8]| d.get_name(k).and_then(|o| o.num()); + let w = num(b"Width").ok_or(PsErr::Ps("typecheck"))?.max(0.0) as usize; + let h = num(b"Height").ok_or(PsErr::Ps("typecheck"))?.max(0.0) as usize; + let bpc = num(b"BitsPerComponent").unwrap_or(8.0) as usize; + let matrix = match d.get_name(b"ImageMatrix") { + Some(Obj::Array(a, _)) => matrix_of(&a)?, + _ => return err("typecheck"), + }; + let multi = matches!(d.get_name(b"MultipleDataSources"), Some(Obj::Bool(true))); + let sources = match d.get_name(b"DataSource").ok_or(PsErr::Ps("typecheck"))? { + Obj::Array(a, false) if multi => a.items(), + o => vec![o], + }; + if multi && sources.len() < comps { + return err("rangecheck"); + } + let decode = match d.get_name(b"Decode") { + Some(Obj::Array(a, _)) => Some(a.items().iter().filter_map(Obj::num).collect()), + _ => None, + }; + let interpolate = matches!(d.get_name(b"Interpolate"), Some(Obj::Bool(true))); + let _ = ip; + Ok(Params { w, h, bpc, matrix, sources, decode, interpolate }) +} + +/// Read all samples, pixel-interleaved (`comps` per pixel), rows padded to bytes. +fn samples(ip: &mut Interp, p: &Params, comps: usize) -> R<(Vec<u8>, bool)> { + let total = p.w.checked_mul(p.h).and_then(|n| n.checked_mul(comps)).ok_or(PsErr::Ps("limitcheck"))?; + if total > MAX_SAMPLES || !matches!(p.bpc, 1 | 2 | 4 | 8 | 12 | 16) { + return err("limitcheck"); + } + ip.alloc(total)?; + ip.charge_bytes(total)?; + if p.sources.len() <= 1 { + let row = (p.w * comps * p.bpc).div_ceil(8); + let src = p.sources.first().cloned().ok_or(PsErr::Ps("typecheck"))?; + return read_source(ip, &src, row * p.h); + } + // One source per component, read in turn (each call or string gives the next piece of its + // component, as Photoshop's row-by-row procedures expect), then interleaved (8-bit only). + if p.bpc != 8 { + return err("limitcheck"); + } + let plane = p.w * p.h; + let mut planes: Vec<Vec<u8>> = vec![Vec::new(); comps]; + let sources: Vec<Obj> = p.sources.iter().take(comps).cloned().collect(); + let mut stalled = 0; + while planes.iter().any(|pl| pl.len() < plane) && stalled < 2 { + let mut progress = false; + for (pl, src) in planes.iter_mut().zip(&sources) { + if pl.len() >= plane { + continue; + } + let piece = match src { + p @ Obj::Array(_, true) => { + ip.call(p.clone())?; + ip.pop_str()?.bytes() + } + Obj::Str(s, _) => s.bytes(), + Obj::File(id) => { + let row = p.w.max(1); + let mut v = Vec::with_capacity(row); + while v.len() < row { + match ip.srcs.read(*id) { + Some(c) => v.push(c), + None => break, + } + } + v + } + _ => return err("typecheck"), + }; + progress |= !piece.is_empty(); + pl.extend_from_slice(&piece); + } + stalled = if progress { 0 } else { stalled + 1 }; + } + for pl in &mut planes { + pl.resize(plane, 0); + } + let mut out = Vec::with_capacity(total); + for i in 0..plane { + for pl in &planes { + out.push(pl.get(i).copied().unwrap_or(0)); + } + } + Ok((out, false)) +} + +/// The unit square → page matrix for an image of w × h samples. +fn placement(ip: &Interp, p: &Params) -> R<M> { + let inv = p.matrix.inv().ok_or(PsErr::Ps("undefinedresult"))?; + let s = M([p.w as f64, 0.0, 0.0, -(p.h as f64), 0.0, p.h as f64]); + Ok(s.then(&inv).then(&ip.gs.ctm)) +} + +/// 12- and 16-bit samples as 8-bit. +fn to_8bit(data: Vec<u8>, bpc: usize) -> Vec<u8> { + match bpc { + 16 => data.chunks(2).map(|c| c.first().copied().unwrap_or(0)).collect(), + 12 => { + let mut out = Vec::with_capacity(data.len() * 2 / 3); + for c in data.chunks(3) { + let (a, b, d) = (c.first().copied().unwrap_or(0), c.get(1).copied().unwrap_or(0), c.get(2).copied().unwrap_or(0)); + out.push(a); + out.push((b << 4) | (d >> 4)); + } + out + } + _ => data, + } +} + +fn paint(ip: &mut Interp, p: Params, space: Space) -> R { + let comps = space.comps(); + let (data, dct) = samples(ip, &p, comps)?; + if ip.limits.skip_images { + ip.warnings.push("image".into()); + return Ok(()); + } + let cm = placement(ip, &p)?; + if ip.gs.nulldev { + return Ok(()); + } + let (data, bpc) = if !dct && matches!(p.bpc, 12 | 16) { (to_8bit(data, p.bpc), 8) } else { (data, p.bpc) }; + let decode = p.decode.map(|d| d.iter().map(|v| *v as f32).collect::<Vec<_>>()); + let img_space = match &space { + Space::Gray => Some(ImgSpace::Gray), + Space::Rgb => Some(ImgSpace::Rgb), + Space::Cmyk => Some(ImgSpace::Cmyk), + Space::Indexed { base, hival, lookup } if matches!(**base, Space::Gray | Space::Rgb | Space::Cmyk) => Some(ImgSpace::Indexed { + base: Box::new(match **base { + Space::Rgb => ImgSpace::Rgb, + Space::Cmyk => ImgSpace::Cmyk, + _ => ImgSpace::Gray, + }), + hival: u8::try_from(*hival).unwrap_or(255), + lookup: lookup.clone(), + }), + _ => None, + }; + if let Some(space) = img_space { + let img = + Image { w: p.w as u32, h: p.h as u32, bpc: bpc as u8, space: Some(space), decode, data, dct, interpolate: p.interpolate, smask: None }; + return ip.out.image(&ip.gs.clip, &cm, img, None).map_err(PsErr::Fatal); + } + // Other spaces (Separation, DeviceN, Indexed over them, Lab): convert each pixel, through a + // table of the 256 values when there is one component. + if dct || bpc != 8 { + ip.warnings.push("image in an unsupported colour space skipped".into()); + return Ok(()); + } + // Converting each pixel: work and the converted copy. + ip.charge(data.len() as u64 / 4 + 1)?; + ip.alloc(p.w.saturating_mul(p.h).saturating_mul(4))?; + let mut rgb = Vec::with_capacity(p.w * p.h * 4); + if comps == 1 { + let mut table = Vec::with_capacity(256); + let dmax = match &space { + Space::Indexed { hival, .. } => *hival as f64, + _ => 1.0, + }; + for v in 0..256 { + let x = f64::from(v) / 255.0 * dmax; + table.push(gfx::to_device(ip, &space, &[x], 0)?); + } + let cmyk = table.iter().any(|c| matches!(c, DevColor::Cmyk(..))); + for s in &data { + push_color(&mut rgb, table.get(usize::from(*s)).copied().unwrap_or(DevColor::Gray(0.0)), cmyk); + } + let space = if cmyk { ImgSpace::Cmyk } else { ImgSpace::Rgb }; + let img = Image { + w: p.w as u32, + h: p.h as u32, + bpc: 8, + space: Some(space), + decode: None, + data: rgb, + dct: false, + interpolate: p.interpolate, + smask: None, + }; + return ip.out.image(&ip.gs.clip, &cm, img, None).map_err(PsErr::Fatal); + } + if p.w * p.h > 2_000_000 { + ip.warnings.push("multi-component image in a special colour space too large to convert".into()); + return Ok(()); + } + let mut cache: std::collections::HashMap<Vec<u8>, DevColor> = std::collections::HashMap::new(); + let mut colors = Vec::with_capacity(p.w * p.h); + for px in data.chunks(comps) { + let c = match cache.get(px) { + Some(c) => *c, + None => { + let v: Vec<f64> = px.iter().map(|b| f64::from(*b) / 255.0).collect(); + let c = gfx::to_device(ip, &space, &v, 0)?; + if cache.len() < 65536 { + cache.insert(px.to_vec(), c); + } + c + } + }; + colors.push(c); + } + let cmyk = colors.iter().any(|c| matches!(c, DevColor::Cmyk(..))); + for c in colors { + push_color(&mut rgb, c, cmyk); + } + let space = if cmyk { ImgSpace::Cmyk } else { ImgSpace::Rgb }; + let img = Image { + w: p.w as u32, + h: p.h as u32, + bpc: 8, + space: Some(space), + decode: None, + data: rgb, + dct: false, + interpolate: p.interpolate, + smask: None, + }; + ip.out.image(&ip.gs.clip, &cm, img, None).map_err(PsErr::Fatal) +} + +fn push_color(out: &mut Vec<u8>, c: DevColor, cmyk: bool) { + let b = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + match (c, cmyk) { + (DevColor::Cmyk(c, m, y, k), true) => out.extend([b(c), b(m), b(y), b(k)]), + (DevColor::Gray(g), true) => out.extend([0, 0, 0, b(1.0 - g)]), + (DevColor::Rgb(r, g, bl), true) => out.extend([b(1.0 - r), b(1.0 - g), b(1.0 - bl), 0]), + (DevColor::Gray(g), false) => out.extend([b(g); 3]), + (DevColor::Rgb(r, g, bl), false) => out.extend([b(r), b(g), b(bl)]), + (DevColor::Cmyk(c, m, y, k), false) => out.extend([b(1.0 - (c + k).min(1.0)), b(1.0 - (m + k).min(1.0)), b(1.0 - (y + k).min(1.0))]), + } +} + +pub fn image(ip: &mut Interp) -> R { + if let Obj::Dict(d) = ip.top(0)?.clone() { + ip.pop()?; + let space = ip.gs.space.clone(); + let p = dict_params(ip, &d, space.comps())?; + return paint(ip, p, space); + } + let src = ip.pop()?; + let matrix = ip.pop_matrix()?; + let bpc = ip.pop_usize()?; + let h = ip.pop_usize()?; + let w = ip.pop_usize()?; + paint(ip, Params { w, h, bpc, matrix, sources: vec![src], decode: None, interpolate: false }, Space::Gray) +} + +pub fn colorimage(ip: &mut Interp) -> R { + let ncomp = ip.pop_usize()?; + let multi = ip.pop_bool()?; + let space = match ncomp { + 1 => Space::Gray, + 3 => Space::Rgb, + 4 => Space::Cmyk, + _ => return err("rangecheck"), + }; + let mut sources = Vec::new(); + for _ in 0..if multi { ncomp } else { 1 } { + sources.push(ip.pop()?); + } + sources.reverse(); + let matrix = ip.pop_matrix()?; + let bpc = ip.pop_usize()?; + let h = ip.pop_usize()?; + let w = ip.pop_usize()?; + paint(ip, Params { w, h, bpc, matrix, sources, decode: None, interpolate: false }, space) +} + +pub fn imagemask(ip: &mut Interp) -> R { + let (p, polarity) = if let Obj::Dict(d) = ip.top(0)?.clone() { + ip.pop()?; + let mut p = dict_params(ip, &d, 1)?; + let inverted = p.decode.as_ref().and_then(|d| d.first()).is_some_and(|v| *v > 0.5); + p.decode = None; + (p, inverted) + } else { + let src = ip.pop()?; + let matrix = ip.pop_matrix()?; + let polarity = ip.pop_bool()?; + let h = ip.pop_usize()?; + let w = ip.pop_usize()?; + (Params { w, h, bpc: 1, matrix, sources: vec![src], decode: None, interpolate: false }, polarity) + }; + let p = Params { bpc: 1, ..p }; + let (data, _) = samples(ip, &p, 1)?; + if ip.limits.skip_images { + ip.warnings.push("image".into()); + return Ok(()); + } + let cm = placement(ip, &p)?; + if ip.gs.nulldev { + return Ok(()); + } + let color = gfx::current_color(ip)?; + // PDF stencil masks paint 0 bits; polarity true paints the 1 bits. + let decode = if polarity { Some(vec![1.0, 0.0]) } else { None }; + let img = Image { w: p.w as u32, h: p.h as u32, bpc: 1, space: None, decode, data, dct: false, interpolate: false, smask: None }; + ip.out.image(&ip.gs.clip, &cm, img, Some(color)).map_err(PsErr::Fatal) +} diff --git a/crates/ps/src/read/ops/mesh.rs b/crates/ps/src/read/ops/mesh.rs new file mode 100644 index 000000000..01a499b86 --- /dev/null +++ b/crates/ps/src/read/ops/mesh.rs @@ -0,0 +1,262 @@ +//! Mesh shadings (types 4–7): free-form and lattice triangles, Coons and tensor patches, read +//! from an array, a string or a file, their colours made device colours, and written to the PDF +//! as meshes again (each triangle and patch whole, so shared edges need no state there). + +use crate::read::gstate::{DevColor, Space}; +use crate::read::interp::{Interp, R, err}; +use crate::read::obj::{Obj, PDict}; +use crate::read::ops::gfx; +use crate::read::ops::shading::{Func, eval, pack}; +use crate::read::pdf::{ShadeKind, Shading}; + +/// A patch's control points and corner colours (the next patch may share an edge of it). +type Patch = (Vec<(f64, f64)>, Vec<DevColor>); + +/// The most vertices or patches read from one shading. +const MAX_ELEMENTS: usize = 2_000_000; + +/// The numbers of a mesh: from an array as they are, or unpacked from bits with Decode. +struct Reader { + nums: Vec<f64>, + bits: Option<(Vec<u8>, usize)>, + pos: usize, + bpc: usize, + bpcomp: usize, + bpflag: usize, + decode: Vec<f64>, +} + +impl Reader { + fn raw(&mut self, n: usize) -> Option<u64> { + let (data, bit) = self.bits.as_mut()?; + let mut v = 0u64; + for _ in 0..n { + let byte = *data.get(*bit / 8)?; + v = v << 1 | u64::from(byte >> (7 - *bit % 8) & 1); + *bit += 1; + } + Some(v) + } + + fn align(&mut self) { + if let Some((_, bit)) = self.bits.as_mut() { + *bit = bit.div_ceil(8) * 8; + } + } + + fn array_next(&mut self) -> Option<f64> { + let v = self.nums.get(self.pos).copied(); + self.pos += 1; + v + } + + fn decoded(&mut self, bits: usize, range: usize) -> Option<f64> { + if self.bits.is_none() { + return self.array_next(); + } + let v = self.raw(bits)?; + let max = ((1u128 << bits) - 1) as f64; + let (d0, d1) = (self.decode.get(2 * range).copied().unwrap_or(0.0), self.decode.get(2 * range + 1).copied().unwrap_or(1.0)); + Some(d0 + v as f64 / max * (d1 - d0)) + } + + fn flag(&mut self) -> Option<u8> { + if self.bits.is_none() { + return self.array_next().map(|v| v as u8); + } + self.raw(self.bpflag).map(|v| v as u8) + } + + fn point(&mut self) -> Option<(f64, f64)> { + let b = self.bpc; + Some((self.decoded(b, 0)?, self.decoded(b, 1)?)) + } + + fn color(&mut self, n: usize) -> Option<Vec<f64>> { + let b = self.bpcomp; + (0..n).map(|i| self.decoded(b, 2 + i)).collect() + } +} + +#[allow(clippy::cognitive_complexity, reason = "one stateful reader handles the PostScript mesh record layouts")] +pub fn build(ip: &mut Interp, d: &PDict, kind: i64, space: &Space, func: Option<&Func>) -> R<Option<Shading>> { + let num = |k: &[u8]| d.get_name(k).and_then(|o| o.num()).unwrap_or(0.0); + let ncomp = if func.is_some() { 1 } else { space.comps() }; + let decode: Vec<f64> = match d.get_name(b"Decode") { + Some(Obj::Array(a, _)) => a.items().iter().filter_map(Obj::num).collect(), + _ => Vec::new(), + }; + let mut r = Reader { + nums: Vec::new(), + bits: None, + pos: 0, + bpc: num(b"BitsPerCoordinate").clamp(1.0, 32.0) as usize, + bpcomp: num(b"BitsPerComponent").clamp(1.0, 16.0) as usize, + bpflag: num(b"BitsPerFlag").clamp(2.0, 8.0) as usize, + decode, + }; + match d.get_name(b"DataSource") { + Some(Obj::Array(a, _)) => r.nums = a.items().iter().filter_map(Obj::num).collect(), + Some(Obj::Str(s, _)) => r.bits = Some((s.bytes(), 0)), + Some(Obj::File(id)) => { + let mut v = Vec::new(); + while let Some(c) = ip.srcs.read(id) { + v.push(c); + if v.len() > 64 << 20 { + break; + } + } + r.bits = Some((v, 0)); + } + _ => return err("typecheck"), + } + let to_dev = |ip: &mut Interp, c: &[f64]| -> R<DevColor> { + let comps = match func { + Some(f) => eval(ip, f, c, 0)?, + None => c.to_vec(), + }; + gfx::to_device(ip, space, &comps, 0) + }; + let mut points: Vec<(f64, f64)> = Vec::new(); + let mut colors: Vec<DevColor> = Vec::new(); + let shade = match kind { + 4 | 5 => { + // Vertices, then triangles of them. + let mut verts: Vec<((f64, f64), DevColor)> = Vec::new(); + let mut tris: Vec<[usize; 3]> = Vec::new(); + let per_row = num(b"VerticesPerRow").max(2.0) as usize; + let mut pending: Vec<usize> = Vec::new(); + while verts.len() < MAX_ELEMENTS { + ip.charge(1)?; + let flag = if kind == 4 { + match r.flag() { + Some(f) => f, + None => break, + } + } else { + 0 + }; + let (Some(p), Some(c)) = (r.point(), r.color(ncomp)) else { break }; + if kind == 4 && r.bits.is_some() { + r.align(); + } + let c = to_dev(ip, &c)?; + verts.push((p, c)); + let n = verts.len() - 1; + if kind != 4 { + continue; + } + // Flag 0 starts a triangle of three new vertices; 1 and 2 continue from the + // last triangle's (b, c) or (a, c) edge. + match (flag, tris.last().copied()) { + (1, Some([_, b, c])) => tris.push([b, c, n]), + (2, Some([a, _, c])) => tris.push([a, c, n]), + _ => { + pending.push(n); + if pending.len() == 3 { + tris.push([pending[0], pending[1], pending[2]]); + pending.clear(); + } + } + } + } + if kind == 5 { + let rows = verts.len() / per_row; + for row in 0..rows.saturating_sub(1) { + for i in 0..per_row - 1 { + let a = row * per_row + i; + let (b, c, e) = (a + 1, a + per_row, a + per_row + 1); + tris.push([a, b, c]); + tris.push([b, e, c]); + } + } + } + for t in tris { + for i in t { + let Some((p, c)) = verts.get(i) else { return err("rangecheck") }; + points.push(*p); + colors.push(*c); + } + } + ShadeKind::Triangles + } + _ => { + // Coons (12 control points) and tensor (16) patches; flags 1–3 share an edge. + let npts = if kind == 6 { 12 } else { 16 }; + let mut prev: Option<Patch> = None; + let mut count = 0; + loop { + if count >= MAX_ELEMENTS { + break; + } + ip.charge(4)?; + let Some(flag) = r.flag() else { break }; + let (shared_pts, shared_cols) = match (flag, &prev) { + (1..=3, Some((pp, pc))) => { + // The edge of the previous patch this one starts from (per the patch order). + let (pi, ci): (&[usize], [usize; 2]) = match flag { + 1 => (&[3, 4, 5, 6], [1, 2]), + 2 => (&[6, 7, 8, 9], [2, 3]), + _ => (&[9, 10, 11, 0], [3, 0]), + }; + ( + pi.iter().filter_map(|i| pp.get(*i).copied()).collect::<Vec<_>>(), + ci.iter().filter_map(|i| pc.get(*i).copied()).collect::<Vec<_>>(), + ) + } + _ => (Vec::new(), Vec::new()), + }; + let new_pts = if shared_pts.len() == 4 { npts - 4 } else { npts }; + let new_cols = if shared_cols.len() == 2 { 2 } else { 4 }; + let mut pts = shared_pts.clone(); + if pts.len() != 4 { + pts.clear(); + } + let mut ok = true; + for _ in 0..new_pts { + match r.point() { + Some(p) => pts.push(p), + None => { + ok = false; + break; + } + } + } + let mut cols = if shared_cols.len() == 2 { shared_cols } else { Vec::new() }; + for _ in 0..new_cols { + match r.color(ncomp) { + Some(c) => cols.push(to_dev(ip, &c)?), + None => { + ok = false; + break; + } + } + } + if r.bits.is_some() { + r.align(); + } + if !ok || pts.len() != npts || cols.len() != 4 { + break; + } + points.extend(&pts); + colors.extend(&cols); + prev = Some((pts, cols)); + count += 1; + } + if kind == 6 { ShadeKind::Coons } else { ShadeKind::Tensor } + } + }; + if points.is_empty() { + return Ok(None); + } + let bbox = match d.get_name(b"BBox") { + Some(Obj::Array(a, _)) => { + let v: Vec<f64> = a.items().iter().filter_map(Obj::num).collect(); + <[f64; 4]>::try_from(v).ok() + } + _ => None, + }; + let (space, data) = pack(&colors); + let n = colors.len(); + Ok(Some(Shading { kind: shade, extend: [false, false], space, data, samples: n, bbox, points })) +} diff --git a/crates/ps/src/read/ops/misc.rs b/crates/ps/src/read/ops/misc.rs new file mode 100644 index 000000000..03f7ece9b --- /dev/null +++ b/crates/ps/src/read/ops/misc.rs @@ -0,0 +1,789 @@ +//! Files, filters, resources, forms, output, and device parameters EPS programs query or set. + +use crate::read::interp::{Interp, PsErr, R, err, matrix_of}; +use crate::read::obj::{Key, Obj, PArr, PDict, name}; +use crate::read::source::{FilterParams, Kind, Source}; + +// ----- files ----- + +pub fn currentfile(ip: &mut Interp) -> R { + let id = + ip.e.iter() + .rev() + .find_map(|f| match f { + crate::read::interp::Frame::File { id } => Some(*id), + _ => None, + }) + .unwrap_or(ip.main); + ip.push(Obj::File(id)) +} + +fn pop_file(ip: &mut Interp) -> R<usize> { + match ip.pop()? { + Obj::File(id) => Ok(id), + _ => err("typecheck"), + } +} + +pub fn read(ip: &mut Interp) -> R { + let f = pop_file(ip)?; + match ip.srcs.read(f) { + Some(c) => { + ip.push(Obj::Int(i64::from(c)))?; + ip.push(Obj::Bool(true)) + } + None => ip.push(Obj::Bool(false)), + } +} + +pub fn readstring(ip: &mut Interp) -> R { + let s = ip.pop_str()?; + let f = pop_file(ip)?; + let mut n = 0; + while n < s.len { + match ip.srcs.read(f) { + Some(c) => { + s.set(n, c); + n += 1; + } + None => break, + } + } + let full = n == s.len; + let sub = s.interval(0, n).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(sub, false))?; + ip.push(Obj::Bool(full)) +} + +pub fn readhexstring(ip: &mut Interp) -> R { + let s = ip.pop_str()?; + let f = pop_file(ip)?; + let mut n = 0; + let mut hi: Option<u8> = None; + while n < s.len { + let Some(c) = ip.srcs.read(f) else { break }; + let v = match c { + b'0'..=b'9' => c - b'0', + b'a'..=b'f' => c - b'a' + 10, + b'A'..=b'F' => c - b'A' + 10, + _ => continue, + }; + match hi.take() { + Some(h) => { + s.set(n, h << 4 | v); + n += 1; + } + None => hi = Some(v), + } + } + let full = n == s.len; + let sub = s.interval(0, n).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(sub, false))?; + ip.push(Obj::Bool(full)) +} + +pub fn readline(ip: &mut Interp) -> R { + let s = ip.pop_str()?; + let f = pop_file(ip)?; + let mut n = 0; + let mut eol = false; + while let Some(c) = ip.srcs.read(f) { + if c == b'\n' { + eol = true; + break; + } + if c == b'\r' { + if ip.srcs.peek(f) == Some(b'\n') { + ip.srcs.read(f); + } + eol = true; + break; + } + if n >= s.len { + return err("rangecheck"); + } + s.set(n, c); + n += 1; + } + let sub = s.interval(0, n).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(sub, false))?; + ip.push(Obj::Bool(eol || n > 0)) +} + +pub fn bytesavailable(ip: &mut Interp) -> R { + let f = pop_file(ip)?; + let n = ip.srcs.available(f); + ip.push(Obj::Int(n)) +} + +pub fn closefile(ip: &mut Interp) -> R { + let f = pop_file(ip)?; + let is_eexec = matches!(ip.srcs.list.get(f).map(|source| &source.kind), Some(Kind::Eexec { .. })); + ip.srcs.close(f); + if is_eexec + && let Some(font) = ip.d.iter().rev().find(|dict| dict.get_name(b"FontName").is_some()).cloned() + && let Some(name) = font.get_name(b"FontName") + { + // Some embedded programs leave `/CharStrings dict` on the operand stack instead of + // installing it with `ND` before closing eexec. Attach that completed table to its font. + if font.get_name(b"CharStrings").is_none() { + ip.charge(ip.o.len() as u64)?; + if let Some(chars) = ip.o.windows(2).rev().find_map(|pair| match pair { + [Obj::Name(key, _), Obj::Dict(chars)] if key.as_ref() == b"CharStrings" => Some(chars.clone()), + _ => None, + }) { + font.put_name(b"CharStrings", Obj::Dict(chars)); + } + } + // Embedded Type 1 programs conventionally leave their completed font dictionary in + // the current dictionary stack; closefile marks the end of eexec, so make it findable. + crate::read::font::add_fid(ip, &font); + ip.fontdir.put(name, Obj::Dict(font)); + } + Ok(()) +} + +pub fn resetfile(ip: &mut Interp) -> R { + let f = pop_file(ip)?; + ip.srcs.reset(f); + Ok(()) +} + +pub fn fileposition(ip: &mut Interp) -> R { + let f = pop_file(ip)?; + let p = ip.srcs.position(f).ok_or(PsErr::Ps("ioerror"))?; + ip.push(Obj::Int(i64::try_from(p).unwrap_or(i64::MAX))) +} + +pub fn setfileposition(ip: &mut Interp) -> R { + let p = ip.pop_usize()?; + let f = pop_file(ip)?; + if ip.srcs.set_position(f, p) { Ok(()) } else { err("ioerror") } +} + +pub fn flushfile(ip: &mut Interp) -> R { + // On an input file: read and discard to its end. + let f = pop_file(ip)?; + if f != ip.main { + while ip.srcs.read(f).is_some() {} + } + Ok(()) +} + +pub fn status(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::File(f) => { + let open = ip.srcs.available(f) >= 0; + ip.push(Obj::Bool(open)) + } + _ => ip.push(Obj::Bool(false)), + } +} + +pub fn file(ip: &mut Interp) -> R { + let _access = ip.pop()?; + let fname = ip.pop_name()?; + match fname.as_slice() { + b"%stdin" => ip.push(Obj::File(ip.main)), + // Output files swallow what is written. + b"%stdout" | b"%stderr" | b"%lineedit" | b"%statementedit" => { + let id = ip.add_source(Source::bytes(Vec::new()))?; + ip.push(Obj::File(id)) + } + // An EPS can't reach the disk. + _ => err("invalidfileaccess"), + } +} + +pub fn write_ops(ip: &mut Interp) -> R { + // `file int write`, `file string writestring`: discarded. + ip.pop()?; + ip.pop()?; + Ok(()) +} + +pub fn eexec(ip: &mut Interp) -> R { + let up = match ip.pop()? { + Obj::File(id) => id, + Obj::Str(s, _) => { + ip.alloc(s.len)?; + ip.add_source(Source::bytes(s.bytes()))? + } + _ => return err("typecheck"), + }; + let id = ip.add_source(Source::eexec(up))?; + // A number of embedded Type 1 programs omit the usual `currentdict end` before eexec; + // their encrypted prolog starts with `dup /Private ...` and expects its font dictionary. + // Supply it only when the caller has not already left an operand on the stack. + let font_prolog = ip.d.last().is_some_and(|font| { + font.get_name(b"FontName").is_some() + && font.get_name(b"FontType").and_then(|value| value.num()) == Some(1.0) + && font.get_name(b"FontMatrix").is_some() + }); + if ip.o.is_empty() + && font_prolog + && let Some(font) = ip.d.last() + { + ip.push(Obj::Dict(font.clone()))?; + } + // eexec runs with systemdict on top, which its program removes with `end` (`closefile`). + let sd = ip.systemdict.clone(); + ip.begin(sd)?; + ip.push_frame(crate::read::interp::Frame::File { id }) +} + +/// `src [params] /Name filter`, with SubFileDecode's own `count string` operands. +pub fn filter(ip: &mut Interp) -> R { + let fname = ip.pop_name()?; + let mut params = FilterParams { early_change: true, ..Default::default() }; + if fname == b"SubFileDecode" { + let eod = ip.pop()?; + params.eod_string = match eod { + Obj::Str(s, _) => s.bytes(), + _ => return err("typecheck"), + }; + params.eod_count = ip.pop_usize()?; + if let Ok(Obj::Dict(_)) = ip.top(0) { + ip.pop()?; + } + } else if let Ok(Obj::Dict(d)) = ip.top(0).cloned() { + // A dictionary operand is parameters unless it is the data source itself (never: a + // dictionary can't be a source). + ip.pop()?; + let num = |k: &[u8]| d.get_name(k).and_then(|o| o.num()); + params.early_change = num(b"EarlyChange").is_none_or(|v| v != 0.0); + params.predictor = num(b"Predictor").unwrap_or(1.0) as i64; + params.colors = num(b"Colors").unwrap_or(1.0) as i64; + params.bpc = num(b"BitsPerComponent").unwrap_or(8.0) as i64; + params.columns = num(b"Columns").unwrap_or(1.0) as i64; + } + let src = ip.pop()?; + let up = match src { + Obj::File(id) => id, + Obj::Str(s, _) => { + ip.alloc(s.len)?; + ip.add_source(Source::bytes(s.bytes()))? + } + p @ Obj::Array(_, true) => { + // A procedure source: call it until it gives an empty string. + let mut data = Vec::new(); + for _ in 0..1_000_000 { + ip.call(p.clone())?; + let s = ip.pop_str()?.bytes(); + if s.is_empty() { + break; + } + data.extend_from_slice(&s); + ip.alloc(s.len())?; + } + ip.add_source(Source::bytes(data))? + } + _ => return err("typecheck"), + }; + if fname.ends_with(b"Encode") && fname != b"NullEncode" { + // Encoding filters write; an EPS has nowhere to write to. + let id = ip.add_source(Source::bytes(Vec::new()))?; + return ip.push(Obj::File(id)); + } + // Reserve the retained source record before constructing any filter-owned buffers. The + // filter separately checks its predictor/reusable-stream storage against the remaining cap. + ip.alloc(crate::read::interp::SOURCE_BYTES)?; + let max_owned = ip.limits.memory.saturating_sub(ip.memory); + match ip.srcs.filter(up, &fname, &params, max_owned) { + Ok((source, owned_bytes)) => { + ip.alloc(owned_bytes)?; + let id = ip.srcs.add(source); + ip.push(Obj::File(id)) + } + Err(e) => { + ip.warnings.push(e); + err("ioerror") + } + } +} + +// ----- output ----- + +pub fn pop1(ip: &mut Interp) -> R { + ip.pop().map(|_| ()) +} + +pub fn noop(_ip: &mut Interp) -> R { + Ok(()) +} + +pub fn showpage(_ip: &mut Interp) -> R { + Ok(()) +} + +// ----- environment ----- + +pub fn languagelevel(ip: &mut Interp) -> R { + ip.push(Obj::Int(3)) +} + +pub fn version(ip: &mut Interp) -> R { + ip.push(Obj::str(b"3010")) +} + +pub fn product(ip: &mut Interp) -> R { + ip.push(Obj::str(b"craft-ps")) +} + +pub fn revision(ip: &mut Interp) -> R { + ip.push(Obj::Int(1)) +} + +pub fn zero(ip: &mut Interp) -> R { + ip.push(Obj::Int(0)) +} + +pub fn vmstatus(ip: &mut Interp) -> R { + let used = i64::try_from(ip.memory).unwrap_or(i64::MAX); + ip.push(Obj::Int(i64::try_from(ip.saves.len()).unwrap_or(0)))?; + ip.push(Obj::Int(used))?; + ip.push(Obj::Int(1 << 30)) +} + +pub fn push_false(ip: &mut Interp) -> R { + ip.push(Obj::Bool(false)) +} + +pub fn empty_dict(ip: &mut Interp) -> R { + ip.push(Obj::Dict(PDict::new(4))) +} + +pub fn pop_dict(ip: &mut Interp) -> R { + ip.pop_dict().map(|_| ()) +} + +/// The system and user parameters programs read (all limits generous). +pub fn currentsystemparams(ip: &mut Interp) -> R { + let d = PDict::new(24); + for k in [ + "MaxPatternCache", + "MaxFontCache", + "MaxFormCache", + "MaxScreenStorage", + "MaxDisplayList", + "MaxOutlineCache", + "MaxUPathCache", + "MaxStoredScreenCache", + "MaxSourceList", + "MaxDisplayAndSourceList", + "MaxImageBuffer", + "MaxRasterMemory", + "MaxStackSize", + "CurFontCache", + "CurFormCache", + "CurPatternCache", + "CurOutlineCache", + "CurUPathCache", + "CurScreenStorage", + "CurDisplayList", + "CurSourceList", + "CurStoredScreenCache", + "CurInputDevice", + "CurOutputDevice", + ] { + let v = if k.starts_with("Cur") { 0 } else { 8 << 20 }; + d.put_name(k.as_bytes(), Obj::Int(v)); + } + d.put_name(b"ByteOrder", Obj::Bool(false)); + d.put_name(b"RealFormat", Obj::str(b"IEEE")); + d.put_name(b"BuildTime", Obj::Int(0)); + ip.push(Obj::Dict(d)) +} + +pub fn currentuserparams(ip: &mut Interp) -> R { + let d = PDict::new(20); + for (k, v) in [ + ("MaxPatternItem", 20_000), + ("MaxFormItem", 100_000), + ("MaxFontItem", 12_500), + ("MaxUPathItem", 0), + ("MaxLocalVM", 1 << 30), + ("MaxGlobalVM", 1 << 30), + ("VMReclaim", 0), + ("VMThreshold", 1 << 20), + ("MaxDictStack", 1000), + ("MaxExecStack", 100_000), + ("MaxOpStack", 500_000), + ("MinFontCompress", 100), + ("MaxSuperScreen", 1016), + ("MaxLocalVM", 1 << 30), + ("JobTimeout", 0), + ("WaitTimeout", 0), + ] { + d.put_name(k.as_bytes(), Obj::Int(v)); + } + d.put_name(b"AccurateScreens", Obj::Bool(false)); + d.put_name(b"HalftoneMode", Obj::Int(0)); + d.put_name(b"IdiomRecognition", Obj::Bool(false)); + ip.push(Obj::Dict(d)) +} + +pub fn currentpagedevice(ip: &mut Interp) -> R { + let d = PDict::new(8); + d.put_name(b"PageSize", Obj::Array(PArr::new(vec![Obj::Int(612), Obj::Int(792)]), false)); + d.put_name(b"HWResolution", Obj::Array(PArr::new(vec![Obj::Int(72), Obj::Int(72)]), false)); + d.put_name(b"Policies", Obj::Dict(PDict::new(2))); + d.put_name(b"ProcessColorModel", Obj::lit(b"DeviceCMYK")); + d.put_name(b"Separations", Obj::Bool(false)); + ip.push(Obj::Dict(d)) +} + +pub fn currentscreen(ip: &mut Interp) -> R { + ip.push(Obj::Real(60.0))?; + ip.push(Obj::Real(45.0))?; + ip.push(Obj::proc(vec![Obj::Op(crate::read::ops::op_id(b"pop").unwrap_or(0)), Obj::Real(0.0)])) +} + +pub fn setscreen(ip: &mut Interp) -> R { + for _ in 0..3 { + ip.pop()?; + } + Ok(()) +} + +pub fn setcolorscreen(ip: &mut Interp) -> R { + for _ in 0..12 { + ip.pop()?; + } + Ok(()) +} + +pub fn currentcolorscreen(ip: &mut Interp) -> R { + for _ in 0..4 { + currentscreen(ip)?; + } + Ok(()) +} + +pub fn empty_proc(ip: &mut Interp) -> R { + ip.push(Obj::proc(Vec::new())) +} + +pub fn currentcolortransfer(ip: &mut Interp) -> R { + for _ in 0..4 { + empty_proc(ip)?; + } + Ok(()) +} + +pub fn setcolortransfer(ip: &mut Interp) -> R { + for _ in 0..4 { + ip.pop()?; + } + Ok(()) +} + +pub fn findcolorrendering(ip: &mut Interp) -> R { + let n = ip.pop()?; + ip.push(n)?; + ip.push(Obj::Bool(true)) +} + +pub fn realtime(ip: &mut Interp) -> R { + ip.push(Obj::Int(0)) +} + +pub fn internaldict(ip: &mut Interp) -> R { + ip.pop_int()?; + let d = match ip.systemdict.get_name(b"CraftPsInternal") { + Some(Obj::Dict(d)) => d, + _ => { + let d = PDict::new(10); + ip.systemdict.put_name(b"CraftPsInternal", Obj::Dict(d.clone())); + d + } + }; + ip.push(Obj::Dict(d)) +} + +pub fn setglobal(ip: &mut Interp) -> R { + ip.pop_bool().map(|_| ()) +} + +pub fn print_any(ip: &mut Interp) -> R { + ip.pop().map(|_| ()) +} + +pub fn pstack(_ip: &mut Interp) -> R { + Ok(()) +} + +pub fn nulldevice(ip: &mut Interp) -> R { + ip.gs.nulldev = true; + Ok(()) +} + +pub fn execform(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + let m = match d.get_name(b"Matrix") { + Some(Obj::Array(a, _)) => matrix_of(&a)?, + _ => crate::read::gstate::M::ID, + }; + let paint = d.get_name(b"PaintProc").ok_or(PsErr::Ps("undefined"))?; + ip.gsave()?; + ip.gs.ctm = m.then(&ip.gs.ctm); + let r = (|| { + if let Some(Obj::Array(bb, _)) = d.get_name(b"BBox") { + ip.push(Obj::Array(bb, false))?; + crate::read::ops::gfx::rectclip(ip)?; + } + ip.push(Obj::Dict(d.clone()))?; + ip.call(paint) + })(); + ip.grestore(); + r +} + +// ----- resources ----- + +fn category(ip: &mut Interp, cat: &[u8]) -> PDict { + match ip.resources.get_name(cat) { + Some(Obj::Dict(d)) => d, + _ => { + let d = PDict::new(20); + ip.resources.put_name(cat, Obj::Dict(d.clone())); + d + } + } +} + +pub fn findresource(ip: &mut Interp) -> R { + let cat = ip.pop_name()?; + let key = ip.pop()?; + if cat == b"Font" { + let f = crate::read::font::find_font(ip, &key)?; + return ip.push(Obj::Dict(f)); + } + if cat == b"Category" { + let d = category(ip, &crate::read::ops::basic::text_of(&key)); + return ip.push(Obj::Dict(d)); + } + let d = category(ip, &cat); + if let Some(v) = d.get(&key.key()) { + return ip.push(v); + } + if cat == b"Encoding" + && let Some(e) = ip.systemdict.get(&key.key()) + { + return ip.push(e); + } + if cat == b"ColorSpace" || cat == b"ColorRendering" || cat == b"Halftone" { + return ip.push(Obj::Dict(PDict::new(1))); + } + ip.dollar_error.put_name(b"command", Obj::lit(b"findresource")); + err("undefinedresource") +} + +pub fn defineresource(ip: &mut Interp) -> R { + let cat = ip.pop_name()?; + let v = ip.pop()?; + let key = ip.pop()?; + if cat == b"CIDFont" + && let Obj::Dict(d) = &v + && !d.known(&Key::Name(name(b"FID"))) + { + d.put_name(b"FID", Obj::FontId(ip.next_fid)); + ip.next_fid += 1; + } + if cat == b"Font" + && let Obj::Dict(d) = &v + { + if !d.known(&Key::Name(name(b"FID"))) { + d.put_name(b"FID", Obj::FontId(ip.next_fid)); + ip.next_fid += 1; + } + ip.fontdir.put(key.clone(), v.clone()); + } + category(ip, &cat).put(key, v.clone()); + ip.push(v) +} + +pub fn undefineresource(ip: &mut Interp) -> R { + let cat = ip.pop_name()?; + let key = ip.pop()?; + category(ip, &cat).remove(&key.key()); + Ok(()) +} + +pub fn resourcestatus(ip: &mut Interp) -> R { + let cat = ip.pop_name()?; + let key = ip.pop()?; + let known = category(ip, &cat).known(&key.key()) || (cat == b"Font" && ip.fontdir.known(&key.key())); + if known { + ip.push(Obj::Int(1))?; + ip.push(Obj::Int(0))?; + ip.push(Obj::Bool(true)) + } else { + ip.push(Obj::Bool(false)) + } +} + +pub fn resourceforall(ip: &mut Interp) -> R { + let cat = ip.pop_name()?; + let scratch = ip.pop_str()?; + let proc = ip.pop()?; + let _template = ip.pop()?; + let entries = category(ip, &cat).entries(); + ip.charge(entries.len() as u64)?; + ip.alloc(entries.len().saturating_mul(2 * crate::read::ops::basic::OBJ_BYTES))?; + for (k, _) in entries { + let t = crate::read::ops::basic::text_of(&k); + if let Some(w) = scratch.put_bytes(0, &t) { + ip.push(Obj::Str(w, false))?; + ip.call(proc.clone())?; + } + } + Ok(()) +} + +// ----- user paths and objects ----- + +pub fn ucache(_ip: &mut Interp) -> R { + Ok(()) +} + +/// Run a user path (an array of numbers and operator names) to build the current path. +fn user_path(ip: &mut Interp, o: Obj) -> R { + let items = match o { + Obj::Array(a, _) => a.items(), + _ => return err("typecheck"), + }; + crate::read::ops::gfx::newpath(ip)?; + for it in items { + match it { + Obj::Name(n, _) => { + let n: &[u8] = &n; + if matches!(n, b"ucache" | b"setbbox") { + if n == b"setbbox" { + for _ in 0..4 { + ip.pop()?; + } + } + continue; + } + let op = crate::read::ops::op_id(n).ok_or(PsErr::Ps("typecheck"))?; + ip.call_op(op)?; + } + Obj::Op(op) => { + if crate::read::ops::OPS.get(op as usize).is_some_and(|(n, _)| *n == b"setbbox") { + for _ in 0..4 { + ip.pop()?; + } + continue; + } + ip.call_op(op)?; + } + o => ip.push(o)?, + } + } + Ok(()) +} + +pub fn uappend(ip: &mut Interp) -> R { + let o = ip.pop()?; + let saved = std::mem::take(&mut ip.gs.path); + user_path(ip, o)?; + let mut p = saved; + p.append(&mut ip.gs.path); + ip.gs.path = p; + Ok(()) +} + +fn upaint(ip: &mut Interp, op: &[u8]) -> R { + let mut m = None; + if let Ok(Obj::Array(a, _)) = ip.top(0).cloned() + && a.len == 6 + && a.items().iter().all(|o| o.num().is_some()) + && ip.o.len() >= 2 + && matches!(ip.top(1), Ok(Obj::Array(..))) + { + m = Some(ip.pop_matrix()?); + } + let o = ip.pop()?; + ip.gsave()?; + let r = (|| { + user_path(ip, o)?; + if let Some(m) = m { + ip.gs.ctm = m.then(&ip.gs.ctm); + } + match op { + b"ufill" => crate::read::ops::gfx::fill(ip), + b"ueofill" => crate::read::ops::gfx::eofill(ip), + _ => crate::read::ops::gfx::stroke(ip), + } + })(); + ip.grestore(); + r +} + +pub fn ufill(ip: &mut Interp) -> R { + upaint(ip, b"ufill") +} + +pub fn ueofill(ip: &mut Interp) -> R { + upaint(ip, b"ueofill") +} + +pub fn ustroke(ip: &mut Interp) -> R { + upaint(ip, b"ustroke") +} + +pub fn setbbox(ip: &mut Interp) -> R { + for _ in 0..4 { + ip.pop_num()?; + } + Ok(()) +} + +pub fn defineuserobject(ip: &mut Interp) -> R { + let v = ip.pop()?; + let i = ip.pop_usize()?; + let arr = match ip.userdict.get_name(b"UserObjects") { + Some(Obj::Array(a, _)) if a.len > i => a, + old => { + let mut items = match old { + Some(Obj::Array(a, _)) => a.items(), + _ => Vec::new(), + }; + if i >= 100_000 { + return err("limitcheck"); + } + ip.charge((i + 1) as u64)?; + ip.alloc((i + 1).saturating_mul(crate::read::ops::basic::OBJ_BYTES))?; + items.resize(i + 1, Obj::Null); + let a = PArr::new(items); + ip.userdict.put_name(b"UserObjects", Obj::Array(a.clone(), false)); + a + } + }; + arr.set(i, v); + Ok(()) +} + +pub fn execuserobject(ip: &mut Interp) -> R { + let i = ip.pop_usize()?; + let v = match ip.userdict.get_name(b"UserObjects") { + Some(Obj::Array(a, _)) => a.get(i).ok_or(PsErr::Ps("undefined"))?, + _ => return err("undefined"), + }; + ip.exec_value(v) +} + +pub fn undefineuserobject(ip: &mut Interp) -> R { + ip.pop_usize().map(|_| ()) +} + +pub fn string_noop(ip: &mut Interp) -> R { + // `setsmoothness` and the like: one number. + ip.pop_num().map(|_| ()) +} + +pub fn gcheck(ip: &mut Interp) -> R { + ip.pop()?; + ip.push(Obj::Bool(false)) +} diff --git a/crates/ps/src/read/ops/mod.rs b/crates/ps/src/read/ops/mod.rs new file mode 100644 index 000000000..2c88d646d --- /dev/null +++ b/crates/ps/src/read/ops/mod.rs @@ -0,0 +1,228 @@ +//! The operator table: every name `systemdict` binds to an operator. + +pub mod basic; +pub mod gfx; +pub mod image; +pub mod mesh; +pub mod misc; +pub mod shading; + +use crate::read::interp::{Interp, R}; +use crate::read::obj::{Obj, PArr, PDict}; +use crate::read::{composite, font}; + +pub type OpId = u16; +pub type OpFn = fn(&mut Interp) -> R; + +macro_rules! named { + ($($n:literal => $f:expr),* $(,)?) => { &[$(($n.as_bytes(), $f as OpFn)),*] }; +} + +pub static OPS: &[(&[u8], OpFn)] = named! { + // stack + "pop" => basic::pop, "exch" => basic::exch, "dup" => basic::dup, "copy" => basic::copy, "index" => basic::index, + "roll" => basic::roll, "clear" => basic::clear, "count" => basic::count, "mark" => basic::mark, "[" => basic::mark, + "<<" => basic::mark, "]" => basic::array_close, ">>" => basic::dict_close, "cleartomark" => basic::cleartomark, + "counttomark" => basic::counttomark, + // arithmetic + "add" => basic::add, "sub" => basic::sub, "mul" => basic::mul, "div" => basic::div, "idiv" => basic::idiv, + "mod" => basic::mod_, "neg" => basic::neg, "abs" => basic::abs, "ceiling" => basic::ceiling, "floor" => basic::floor, + "round" => basic::round, "truncate" => basic::truncate, "sqrt" => basic::sqrt, "sin" => basic::sin, "cos" => basic::cos, + "atan" => basic::atan, "exp" => basic::exp, "ln" => basic::ln, "log" => basic::log, "rand" => basic::rand, + "srand" => basic::srand, "rrand" => basic::rrand, + // relations + "eq" => basic::eq, "ne" => basic::ne, "gt" => basic::gt, "ge" => basic::ge, "lt" => basic::lt, "le" => basic::le, + "and" => basic::and, "or" => basic::or, "xor" => basic::xor, "not" => basic::not, "bitshift" => basic::bitshift, + "true" => basic::true_, "false" => basic::false_, "null" => basic::null, + // control + "exec" => basic::exec, "if" => basic::if_, "ifelse" => basic::ifelse, "for" => basic::for_, "repeat" => basic::repeat, + "loop" => basic::loop_, "exit" => basic::exit, "stop" => basic::stop, "stopped" => basic::stopped, "quit" => basic::quit, + "forall" => basic::forall, "countexecstack" => basic::countexecstack, "execstack" => basic::execstack, + // types + "type" => basic::type_, "cvlit" => basic::cvlit, "cvx" => basic::cvx, "xcheck" => basic::xcheck, + "readonly" => basic::noop_keep, "executeonly" => basic::noop_keep, "noaccess" => basic::noop_keep, + "rcheck" => basic::check_true, "wcheck" => basic::check_true, "cvi" => basic::cvi, "cvr" => basic::cvr, + "cvn" => basic::cvn, "cvs" => basic::cvs, "cvrs" => basic::cvrs, "bind" => basic::bind, + // dictionaries + "dict" => basic::dict, "maxlength" => basic::maxlength, "begin" => basic::begin, "end" => basic::end, "def" => basic::def, + // Conventional Type 1 font-prolog aliases. + "ND" => basic::def, "NP" => basic::put, + "load" => basic::load, "store" => basic::store, "get" => basic::get, "put" => basic::put, "known" => basic::known, + "undef" => basic::undef, "where" => basic::where_, "currentdict" => basic::currentdict, + "countdictstack" => basic::countdictstack, "dictstack" => basic::dictstack, "cleardictstack" => basic::cleardictstack, + // strings and arrays + "array" => basic::array, "string" => basic::string, "length" => basic::length, "getinterval" => basic::getinterval, + "putinterval" => basic::putinterval, "aload" => basic::aload, "astore" => basic::astore, + "packedarray" => basic::packedarray, "search" => basic::search, "anchorsearch" => basic::anchorsearch, + "token" => basic::token, + // graphics state + "gsave" => gfx::gsave, "grestore" => gfx::grestore, "grestoreall" => gfx::grestoreall, "initgraphics" => gfx::initgraphics, + "save" => gfx::save, "restore" => gfx::restore, "gstate" => gfx::gstate, "currentgstate" => gfx::currentgstate, + "setgstate" => gfx::setgstate, "setlinewidth" => gfx::setlinewidth, "currentlinewidth" => gfx::currentlinewidth, + "setlinecap" => gfx::setlinecap, "currentlinecap" => gfx::currentlinecap, "setlinejoin" => gfx::setlinejoin, + "currentlinejoin" => gfx::currentlinejoin, "setmiterlimit" => gfx::setmiterlimit, + "currentmiterlimit" => gfx::currentmiterlimit, "setdash" => gfx::setdash, "currentdash" => gfx::currentdash, + "setflat" => gfx::setflat, "currentflat" => gfx::currentflat, "setstrokeadjust" => gfx::setstrokeadjust, + "currentstrokeadjust" => gfx::currentstrokeadjust, "setoverprint" => gfx::setoverprint, + "currentoverprint" => gfx::currentoverprint, + // matrices + "matrix" => gfx::matrix, "initmatrix" => gfx::initmatrix, "identmatrix" => gfx::identmatrix, + "defaultmatrix" => gfx::defaultmatrix, "currentmatrix" => gfx::currentmatrix, "setmatrix" => gfx::setmatrix, + "translate" => gfx::translate, "scale" => gfx::scale, "rotate" => gfx::rotate, "concat" => gfx::concat, + "concatmatrix" => gfx::concatmatrix, "invertmatrix" => gfx::invertmatrix, "transform" => gfx::transform, + "itransform" => gfx::itransform, "dtransform" => gfx::dtransform, "idtransform" => gfx::idtransform, + // paths + "newpath" => gfx::newpath, "moveto" => gfx::moveto, "rmoveto" => gfx::rmoveto, "lineto" => gfx::lineto, + "rlineto" => gfx::rlineto, "curveto" => gfx::curveto, "rcurveto" => gfx::rcurveto, "closepath" => gfx::closepath, + "arc" => gfx::arc, "arcn" => gfx::arcn, "arct" => gfx::arct, "arcto" => gfx::arcto, "currentpoint" => gfx::currentpoint, + "flattenpath" => gfx::flattenpath, "reversepath" => gfx::reversepath, "strokepath" => gfx::strokepath, + "pathbbox" => gfx::pathbbox, "pathforall" => gfx::pathforall, "clippath" => gfx::clippath, "initclip" => gfx::initclip, + "clipsave" => gfx::clipsave, "cliprestore" => gfx::cliprestore, "clip" => gfx::clip, "eoclip" => gfx::eoclip, "rectclip" => gfx::rectclip, + // painting + "fill" => gfx::fill, "eofill" => gfx::eofill, "stroke" => gfx::stroke, "rectfill" => gfx::rectfill, + "rectstroke" => gfx::rectstroke, "shfill" => shading::shfill, "erasepage" => misc::noop, + "image" => image::image, "colorimage" => image::colorimage, "imagemask" => image::imagemask, + // colour + "setgray" => gfx::setgray, "currentgray" => gfx::currentgray, "setrgbcolor" => gfx::setrgbcolor, + "currentrgbcolor" => gfx::currentrgbcolor, "sethsbcolor" => gfx::sethsbcolor, "currenthsbcolor" => gfx::currenthsbcolor, + "setcmykcolor" => gfx::setcmykcolor, "currentcmykcolor" => gfx::currentcmykcolor, "setcolorspace" => gfx::setcolorspace, + "currentcolorspace" => gfx::currentcolorspace, "setcolor" => gfx::setcolor, "currentcolor" => gfx::currentcolor, + "setpattern" => gfx::setpattern, "makepattern" => gfx::makepattern, + // fonts + "findfont" => font::findfont, "definefont" => font::definefont, "undefinefont" => font::undefinefont, + "scalefont" => font::scalefont, "makefont" => font::makefont, "setfont" => font::setfont, + "currentfont" => font::currentfont, "rootfont" => font::currentfont, "selectfont" => font::selectfont, + "show" => font::show, "ashow" => font::ashow, "widthshow" => font::widthshow, "awidthshow" => font::awidthshow, + "xshow" => font::xshow, "yshow" => font::yshow, "xyshow" => font::xyshow, "kshow" => font::kshow, "cshow" => font::cshow, + "glyphshow" => font::glyphshow, "stringwidth" => font::stringwidth, "charpath" => font::charpath, + "setcharwidth" => font::setcharwidth, "setcachedevice" => font::setcachedevice, + "setcachedevice2" => font::setcachedevice2, "setcachelimit" => misc::pop1, "cachestatus" => misc::noop, + // files + "currentfile" => misc::currentfile, "read" => misc::read, "readstring" => misc::readstring, + "readhexstring" => misc::readhexstring, "readline" => misc::readline, "bytesavailable" => misc::bytesavailable, + "closefile" => misc::closefile, "resetfile" => misc::resetfile, "fileposition" => misc::fileposition, + "setfileposition" => misc::setfileposition, "flushfile" => misc::flushfile, "status" => misc::status, + "file" => misc::file, "write" => misc::write_ops, "writestring" => misc::write_ops, "writehexstring" => misc::write_ops, + "eexec" => misc::eexec, "filter" => misc::filter, "flush" => misc::noop, + "print" => misc::print_any, "=" => misc::print_any, "==" => misc::print_any, "stack" => misc::pstack, + "pstack" => misc::pstack, + // resources and forms + "findresource" => misc::findresource, "defineresource" => misc::defineresource, + "undefineresource" => misc::undefineresource, "resourcestatus" => misc::resourcestatus, + "resourceforall" => misc::resourceforall, "execform" => misc::execform, + // user paths and objects + "ucache" => misc::ucache, "setbbox" => misc::setbbox, "uappend" => misc::uappend, "ufill" => misc::ufill, + "ueofill" => misc::ueofill, "ustroke" => misc::ustroke, "defineuserobject" => misc::defineuserobject, + "execuserobject" => misc::execuserobject, "undefineuserobject" => misc::undefineuserobject, + // environment and device + "showpage" => misc::showpage, "copypage" => misc::noop, "nulldevice" => misc::nulldevice, + "languagelevel" => misc::languagelevel, "version" => misc::version, "product" => misc::product, + "revision" => misc::revision, "serialnumber" => misc::zero, "realtime" => misc::realtime, "usertime" => misc::realtime, + "vmstatus" => misc::vmstatus, "vmreclaim" => misc::pop1, "setvmthreshold" => misc::pop1, + "setglobal" => misc::setglobal, "currentglobal" => misc::push_false, "setpacking" => misc::setglobal, + "currentpacking" => misc::push_false, "gcheck" => misc::gcheck, "setshared" => misc::setglobal, + "currentshared" => misc::push_false, "setpagedevice" => misc::pop_dict, "currentpagedevice" => misc::currentpagedevice, + "setuserparams" => misc::pop_dict, "currentuserparams" => misc::currentuserparams, "setsystemparams" => misc::pop_dict, + "currentsystemparams" => misc::currentsystemparams, "setdevparams" => misc::write_ops, "currentdevparams" => misc::empty_dict, + "setscreen" => misc::setscreen, "currentscreen" => misc::currentscreen, "setcolorscreen" => misc::setcolorscreen, + "currentcolorscreen" => misc::currentcolorscreen, "sethalftone" => misc::pop_dict, "currenthalftone" => misc::empty_dict, + "settransfer" => misc::pop1, "currenttransfer" => misc::empty_proc, "setcolortransfer" => misc::setcolortransfer, + "currentcolortransfer" => misc::currentcolortransfer, "setblackgeneration" => misc::pop1, + "currentblackgeneration" => misc::empty_proc, "setundercolorremoval" => misc::pop1, + "currentundercolorremoval" => misc::empty_proc, "setcolorrendering" => misc::pop_dict, + "currentcolorrendering" => misc::empty_dict, "findcolorrendering" => misc::findcolorrendering, + "setsmoothness" => misc::string_noop, "currentsmoothness" => misc::zero, "internaldict" => misc::internaldict, + "setucacheparams" => misc::noop, "ucachestatus" => misc::noop, "setobjectformat" => misc::pop1, + "currentobjectformat" => misc::zero, "sethalftonephase" => misc::setbbox, "echo" => misc::pop1, + "prompt" => misc::noop, "executive" => misc::noop, "start" => misc::noop, + // CFF font sets, CMaps and composite fonts + "StartData" => composite::startdata, "composefont" => composite::composefont, + "begincmap" => composite::begincmap, "endcmap" => composite::endcmap, "usecmap" => composite::usecmap, + "begincodespacerange" => composite::begin_block, "endcodespacerange" => composite::endcodespacerange, + "begincidrange" => composite::begin_block, "endcidrange" => composite::endcidrange, + "begincidchar" => composite::begin_block, "endcidchar" => composite::endcidchar, + "beginbfchar" => composite::begin_block, "endbfchar" => composite::end_ignored, + "beginbfrange" => composite::begin_block, "endbfrange" => composite::end_ignored, + "beginnotdefrange" => composite::begin_block, "endnotdefrange" => composite::end_ignored, + "beginnotdefchar" => composite::begin_block, "endnotdefchar" => composite::end_ignored, +}; + +pub fn op_id(n: &[u8]) -> Option<OpId> { + OPS.iter().position(|(name, _)| *name == n).and_then(|i| OpId::try_from(i).ok()) +} + +fn encoding(names: Vec<&'static str>) -> Obj { + Obj::Array(PArr::new(names.into_iter().map(|n| Obj::lit(n.as_bytes())).collect()), false) +} + +/// Fill systemdict and the standard dictionaries. +pub fn install(ip: &mut Interp) { + for (i, (n, _)) in OPS.iter().enumerate() { + if let Ok(id) = OpId::try_from(i) { + ip.systemdict.put_name(n, Obj::Op(id)); + } + } + // Environment queries are plain values: executing the name pushes them, and programs that + // `get` them from systemdict (`systemdict /languagelevel get 2 ge`) find a number. + ip.systemdict.put_name(b"languagelevel", Obj::Int(3)); + for (n, d) in [ + (&b"systemdict"[..], ip.systemdict.clone()), + (b"userdict", ip.userdict.clone()), + (b"globaldict", ip.globaldict.clone()), + (b"errordict", ip.errordict.clone()), + (b"$error", ip.dollar_error.clone()), + (b"statusdict", ip.statusdict.clone()), + (b"FontDirectory", ip.fontdir.clone()), + (b"GlobalFontDirectory", ip.fontdir.clone()), + (b"SharedFontDirectory", ip.fontdir.clone()), + ] { + ip.systemdict.put_name(n, Obj::Dict(d)); + } + ip.systemdict.put_name(b"version", Obj::str(b"3010")); + ip.systemdict.put_name(b"product", Obj::str(b"craft-ps")); + ip.systemdict.put_name(b"revision", Obj::Int(1)); + ip.systemdict.put_name(b"serialnumber", Obj::Int(0)); + ip.systemdict.put_name(b"StandardEncoding", encoding(crate::read::encodings::standard())); + ip.systemdict.put_name(b"ISOLatin1Encoding", encoding(crate::read::encodings::iso_latin1())); + // Errors are handled by `stopped`; the handlers exist for programs that look at them. + for e in [ + "dictfull", + "dictstackoverflow", + "dictstackunderflow", + "execstackoverflow", + "handleerror", + "interrupt", + "invalidaccess", + "invalidexit", + "invalidfileaccess", + "invalidfont", + "invalidrestore", + "ioerror", + "limitcheck", + "nocurrentpoint", + "rangecheck", + "stackoverflow", + "stackunderflow", + "syntaxerror", + "timeout", + "typecheck", + "undefined", + "undefinedfilename", + "undefinedresult", + "unmatchedmark", + "unregistered", + "VMerror", + "configurationerror", + "undefinedresource", + ] { + let stop = op_id(b"stop").map(Obj::Op).unwrap_or(Obj::Null); + ip.errordict.put_name(e.as_bytes(), Obj::proc(vec![stop])); + } + ip.dollar_error.put_name(b"newerror", Obj::Bool(false)); + ip.statusdict.put_name(b"product", Obj::str(b"craft-ps")); + ip.statusdict.put_name(b"processcolors", Obj::proc(vec![Obj::Int(4)])); + ip.userdict.put_name(b"#copies", Obj::Int(1)); + let cats = PDict::new(4); + ip.resources.put_name(b"Category", Obj::Dict(cats)); + composite::install(ip); +} diff --git a/crates/ps/src/read/ops/shading.rs b/crates/ps/src/read/ops/shading.rs new file mode 100644 index 000000000..599a06921 --- /dev/null +++ b/crates/ps/src/read/ops/shading.rs @@ -0,0 +1,389 @@ +//! Smooth shading: `shfill` and shading patterns. Functions (types 0, 2 and 3, or procedures) +//! are evaluated here in the shading's colour space and sampled into device colours, which the +//! PDF carries as a sampled function. + +use crate::read::gstate::{DevColor, M, Seg}; +use crate::read::interp::{Interp, PsErr, R, err, matrix_of}; +use crate::read::obj::{Obj, PDict}; +use crate::read::ops::gfx; +use crate::read::pdf::{OutSpace, ShadeKind, Shading}; + +/// Samples along an axial or radial shading, and per side of a function-based one. +const SAMPLES: usize = 256; +const GRID: usize = 48; +/// The most inputs a sampled function may take. +const MAX_INPUTS: usize = 4; +/// The most samples a sampled function may hold. +const MAX_SAMPLES: usize = 1 << 22; + +pub enum Func { + Exp { + c0: Vec<f64>, + c1: Vec<f64>, + n: f64, + domain: [f64; 2], + }, + Stitch { + fns: Vec<Func>, + bounds: Vec<f64>, + encode: Vec<f64>, + domain: [f64; 2], + }, + Sampled { + size: Vec<usize>, + domain: Vec<f64>, + encode: Vec<f64>, + decode: Vec<f64>, + samples: Vec<f64>, + outs: usize, + }, + Proc(Obj), + /// One function per output. + Each(Vec<Func>), +} + +fn nums(o: Option<Obj>) -> Option<Vec<f64>> { + match o? { + Obj::Array(a, _) => Some(a.items().iter().filter_map(Obj::num).collect()), + _ => None, + } +} + +fn pair(v: &[f64], dflt: [f64; 2]) -> [f64; 2] { + [v.first().copied().unwrap_or(dflt[0]), v.get(1).copied().unwrap_or(dflt[1])] +} + +fn parse_fn(ip: &mut Interp, o: &Obj, depth: usize) -> R<Func> { + if depth > 8 { + return err("limitcheck"); + } + let d = match o { + Obj::Dict(d) => d.clone(), + Obj::Array(a, false) => return a.items().iter().map(|f| parse_fn(ip, f, depth + 1)).collect::<R<Vec<_>>>().map(Func::Each), + p @ Obj::Array(_, true) => return Ok(Func::Proc(p.clone())), + _ => return err("typecheck"), + }; + let domain = nums(d.get_name(b"Domain")).unwrap_or_else(|| vec![0.0, 1.0]); + match d.get_name(b"FunctionType").and_then(|o| o.num()).unwrap_or(-1.0) as i64 { + 2 => Ok(Func::Exp { + c0: nums(d.get_name(b"C0")).unwrap_or_else(|| vec![0.0]), + c1: nums(d.get_name(b"C1")).unwrap_or_else(|| vec![1.0]), + n: d.get_name(b"N").and_then(|o| o.num()).unwrap_or(1.0), + domain: pair(&domain, [0.0, 1.0]), + }), + 3 => { + let fns = match d.get_name(b"Functions") { + Some(Obj::Array(a, _)) => a.items().iter().map(|f| parse_fn(ip, f, depth + 1)).collect::<R<Vec<_>>>()?, + _ => return err("typecheck"), + }; + Ok(Func::Stitch { + fns, + bounds: nums(d.get_name(b"Bounds")).unwrap_or_default(), + encode: nums(d.get_name(b"Encode")).unwrap_or_default(), + domain: pair(&domain, [0.0, 1.0]), + }) + } + 0 => { + let size: Vec<usize> = nums(d.get_name(b"Size")).unwrap_or_default().iter().map(|v| v.max(1.0) as usize).collect(); + let range = nums(d.get_name(b"Range")).unwrap_or_default(); + let outs = range.len() / 2; + let bps = d.get_name(b"BitsPerSample").and_then(|o| o.num()).unwrap_or(8.0) as usize; + let count = size.iter().try_fold(outs.max(1), |a, s| a.checked_mul(*s)).filter(|n| *n <= MAX_SAMPLES).ok_or(PsErr::Ps("limitcheck"))?; + // At most four inputs: interpolation visits 2^inputs corners per value. + if size.is_empty() || size.len() > MAX_INPUTS || outs == 0 || !matches!(bps, 1 | 2 | 4 | 8 | 12 | 16 | 24 | 32) { + return err("rangecheck"); + } + ip.charge(count as u64)?; + ip.alloc(count.saturating_mul(8))?; + let bytes_needed = (count * bps).div_ceil(8); + let data = match d.get_name(b"DataSource") { + Some(Obj::Str(s, _)) => s.bytes(), + Some(Obj::File(id)) => { + let mut v = Vec::with_capacity(bytes_needed); + while v.len() < bytes_needed { + match ip.srcs.read(id) { + Some(c) => v.push(c), + None => break, + } + } + v + } + _ => return err("typecheck"), + }; + let max = ((1u64 << bps) - 1) as f64; + let mut samples = Vec::with_capacity(count); + let mut bit = 0usize; + for _ in 0..count { + let mut v = 0u64; + for _ in 0..bps { + let byte = data.get(bit / 8).copied().unwrap_or(0); + v = v << 1 | u64::from(byte >> (7 - bit % 8) & 1); + bit += 1; + } + samples.push(v as f64 / max); + } + let encode = nums(d.get_name(b"Encode")).unwrap_or_else(|| size.iter().flat_map(|s| [0.0, (*s as f64 - 1.0).max(0.0)]).collect()); + let decode = nums(d.get_name(b"Decode")).unwrap_or(range); + Ok(Func::Sampled { size, domain, encode, decode, samples, outs }) + } + _ => err("rangecheck"), + } +} + +pub fn eval(ip: &mut Interp, f: &Func, x: &[f64], depth: usize) -> R<Vec<f64>> { + if depth > 16 { + return err("limitcheck"); + } + Ok(match f { + Func::Exp { c0, c1, n, domain } => { + let t = x.first().copied().unwrap_or(0.0).clamp(domain[0].min(domain[1]), domain[0].max(domain[1])); + let k = t.powf(*n); + let len = c0.len().max(c1.len()); + (0..len) + .map(|i| c0.get(i).copied().unwrap_or(0.0) + k * (c1.get(i).copied().unwrap_or(1.0) - c0.get(i).copied().unwrap_or(0.0))) + .collect() + } + Func::Stitch { fns, bounds, encode, domain } => { + let t = x.first().copied().unwrap_or(0.0).clamp(domain[0], domain[1]); + let i = bounds.iter().take_while(|b| t >= **b).count().min(fns.len().saturating_sub(1)); + let lo = if i == 0 { domain[0] } else { bounds.get(i - 1).copied().unwrap_or(domain[0]) }; + let hi = bounds.get(i).copied().unwrap_or(domain[1]); + let (e0, e1) = (encode.get(2 * i).copied().unwrap_or(0.0), encode.get(2 * i + 1).copied().unwrap_or(1.0)); + let u = if hi > lo { e0 + (t - lo) / (hi - lo) * (e1 - e0) } else { e0 }; + match fns.get(i) { + Some(sub) => eval(ip, sub, &[u], depth + 1)?, + None => vec![0.0], + } + } + Func::Sampled { size, domain, encode, decode, samples, outs } => { + // Multilinear interpolation between the samples around the point. + let m = size.len(); + let mut base = 0usize; + let mut stride = *outs; + let mut corners: Vec<(usize, f64)> = vec![(0, 1.0)]; + for k in 0..m { + let (d0, d1) = (domain.get(2 * k).copied().unwrap_or(0.0), domain.get(2 * k + 1).copied().unwrap_or(1.0)); + let s = size.get(k).copied().unwrap_or(1); + let xk = x.get(k).copied().unwrap_or(0.0).clamp(d0.min(d1), d0.max(d1)); + let (e0, e1) = (encode.get(2 * k).copied().unwrap_or(0.0), encode.get(2 * k + 1).copied().unwrap_or((s - 1) as f64)); + let e = if d1 != d0 { e0 + (xk - d0) / (d1 - d0) * (e1 - e0) } else { e0 }; + let e = e.clamp(0.0, (s - 1) as f64); + let i0 = e.floor() as usize; + let i1 = (i0 + 1).min(s - 1); + let frac = e - i0 as f64; + base += i0 * stride; + let step = (i1 - i0) * stride; + corners = corners.into_iter().flat_map(|(off, w)| [(off, w * (1.0 - frac)), (off + step, w * frac)]).collect(); + stride *= s; + } + (0..*outs) + .map(|j| { + let v: f64 = corners.iter().map(|(off, w)| samples.get(base + off + j).copied().unwrap_or(0.0) * w).sum(); + let (d0, d1) = (decode.get(2 * j).copied().unwrap_or(0.0), decode.get(2 * j + 1).copied().unwrap_or(1.0)); + d0 + v * (d1 - d0) + }) + .collect() + } + Func::Proc(p) => { + for v in x { + ip.push(Obj::Real(*v))?; + } + let before = ip.o.len() - x.len(); + ip.call(p.clone())?; + let n = ip.o.len().saturating_sub(before); + let mut out = vec![0.0; n]; + for slot in out.iter_mut().rev() { + *slot = ip.pop_num()?; + } + out + } + Func::Each(fns) => { + let mut out = Vec::with_capacity(fns.len()); + for f in fns { + out.push(eval(ip, f, x, depth + 1)?.first().copied().unwrap_or(0.0)); + } + out + } + }) +} + +/// Device colours as bytes in one output space (CMYK when every colour is CMYK). +pub fn pack(colors: &[DevColor]) -> (OutSpace, Vec<u8>) { + let b = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let all_cmyk = colors.iter().all(|c| matches!(c, DevColor::Cmyk(..))); + let all_gray = colors.iter().all(|c| matches!(c, DevColor::Gray(..))); + let mut out = Vec::new(); + for c in colors { + match (*c, all_cmyk, all_gray) { + (DevColor::Cmyk(c, m, y, k), true, _) => out.extend([b(c), b(m), b(y), b(k)]), + (DevColor::Gray(g), _, true) => out.push(b(g)), + (DevColor::Gray(g), _, _) => out.extend([b(g); 3]), + (DevColor::Rgb(r, g, bl), _, _) => out.extend([b(r), b(g), b(bl)]), + (DevColor::Cmyk(c, m, y, k), _, _) => out.extend([b(1.0 - (c + k).min(1.0)), b(1.0 - (m + k).min(1.0)), b(1.0 - (y + k).min(1.0))]), + } + } + let space = if all_cmyk { + OutSpace::Cmyk + } else if all_gray { + OutSpace::Gray + } else { + OutSpace::Rgb + }; + (space, out) +} + +/// A shading dictionary as the PDF will draw it, or None for kinds not drawn (with a warning). +pub fn build(ip: &mut Interp, d: &PDict) -> R<Option<Shading>> { + let kind = d.get_name(b"ShadingType").and_then(|o| o.num()).unwrap_or(0.0) as i64; + let space_obj = d.get_name(b"ColorSpace").ok_or(PsErr::Ps("undefined"))?; + let space = gfx::parse_space(ip, &space_obj, 0)?; + let func = match d.get_name(b"Function") { + Some(f) => Some(parse_fn(ip, &f, 0)?), + None => None, + }; + let bbox = nums(d.get_name(b"BBox")).filter(|b| b.len() == 4).map(|b| [b[0], b[1], b[2], b[3]]); + let extend = match d.get_name(b"Extend") { + Some(Obj::Array(a, _)) => [matches!(a.get(0), Some(Obj::Bool(true))), matches!(a.get(1), Some(Obj::Bool(true)))], + _ => [false, false], + }; + let color_at = |ip: &mut Interp, x: &[f64]| -> R<DevColor> { + let comps = match &func { + Some(f) => eval(ip, f, x, 0)?, + None => x.to_vec(), + }; + gfx::to_device(ip, &space, &comps, 0) + }; + let shade = match kind { + 2 | 3 => { + let coords = nums(d.get_name(b"Coords")).unwrap_or_default(); + let domain = pair(&nums(d.get_name(b"Domain")).unwrap_or_default(), [0.0, 1.0]); + let mut colors = Vec::with_capacity(SAMPLES); + for i in 0..SAMPLES { + let t = domain[0] + (domain[1] - domain[0]) * i as f64 / (SAMPLES - 1) as f64; + colors.push(color_at(ip, &[t])?); + } + let k = if kind == 2 { + let [a, b, c, e] = <[f64; 4]>::try_from(coords).map_err(|_| PsErr::Ps("rangecheck"))?; + ShadeKind::Axial([a, b, c, e]) + } else { + let [a, b, c, e, f, g] = <[f64; 6]>::try_from(coords).map_err(|_| PsErr::Ps("rangecheck"))?; + ShadeKind::Radial([a, b, c, e, f, g]) + }; + let (space, data) = pack(&colors); + Shading { kind: k, extend, space, data, samples: SAMPLES, bbox, points: Vec::new() } + } + 1 => { + let dom = nums(d.get_name(b"Domain")).unwrap_or_else(|| vec![0.0, 1.0, 0.0, 1.0]); + let [x0, x1, y0, y1] = <[f64; 4]>::try_from(dom).map_err(|_| PsErr::Ps("rangecheck"))?; + let matrix = match d.get_name(b"Matrix") { + Some(Obj::Array(a, _)) => matrix_of(&a)?, + _ => M::ID, + }; + let mut colors = Vec::with_capacity(GRID * GRID); + for j in 0..GRID { + for i in 0..GRID { + let x = x0 + (x1 - x0) * i as f64 / (GRID - 1) as f64; + let y = y0 + (y1 - y0) * j as f64 / (GRID - 1) as f64; + colors.push(color_at(ip, &[x, y])?); + } + } + let (space, data) = pack(&colors); + Shading { kind: ShadeKind::Function { domain: [x0, x1, y0, y1], matrix }, extend, space, data, samples: GRID, bbox, points: Vec::new() } + } + 4..=7 => match crate::read::ops::mesh::build(ip, d, kind, &space, func.as_ref())? { + Some(s) => s, + None => return Ok(None), + }, + _ => { + ip.warnings.push(format!("shading type {kind} not drawn")); + return Ok(None); + } + }; + Ok(Some(shade)) +} + +pub fn shfill(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + if ip.gs.nulldev { + return Ok(()); + } + let Some(s) = build(ip, &d)? else { return Ok(()) }; + let ctm = ip.gs.ctm; + ip.out.shade(&ip.gs.clip, None, false, &ctm, s).map_err(PsErr::Fatal) +} + +/// Fill `path` with the current shading pattern; false when the pattern isn't a shading. +pub fn fill_pattern(ip: &mut Interp, path: &[Seg], eo: bool) -> R<bool> { + let Some(p) = ip.gs.pattern.clone() else { return Ok(false) }; + if p.get_name(b"PatternType").and_then(|o| o.num()) == Some(1.0) { + return tiling(ip, &p, path, eo).map(|()| true); + } + if p.get_name(b"PatternType").and_then(|o| o.num()) != Some(2.0) { + return Ok(false); + } + let Some(Obj::Dict(sh)) = p.get_name(b"Shading") else { return Ok(false) }; + let m = match p.get_name(b"CraftPsMatrix") { + Some(Obj::Array(a, _)) => matrix_of(&a)?, + _ => M::ID, + }; + let Some(s) = build(ip, &sh)? else { return Ok(true) }; + ip.out.shade(&ip.gs.clip, Some(path), eo, &m, s).map_err(PsErr::Fatal)?; + Ok(true) +} + +/// Fill with a tiling pattern: its cell painted once (per colour, for an uncoloured one) into a +/// PDF tiling pattern, cached on the pattern. +fn tiling(ip: &mut Interp, p: &PDict, path: &[Seg], eo: bool) -> R { + let uncolored = p.get_name(b"PaintType").and_then(|o| o.num()) == Some(2.0); + let color = if uncolored { Some(ip.gs.color.clone()) } else { None }; + let key = (crate::read::obj::Obj::Dict(p.clone()).key(), color.clone().unwrap_or_default().iter().map(|v| v.to_bits()).collect::<Vec<_>>()); + let n = match ip.cells.get(&key) { + Some(n) => *n, + None => { + let n = cell(ip, p, color)?; + if ip.cells.len() < 10_000 { + ip.cells.insert(key, n); + } + n + } + }; + ip.out.fill_tiling(&ip.gs.clip, path, eo, n).map_err(PsErr::Fatal) +} + +fn cell(ip: &mut Interp, p: &PDict, color: Option<Vec<f64>>) -> R<usize> { + let bbox = nums(p.get_name(b"BBox")).filter(|b| b.len() == 4).map(|b| [b[0], b[1], b[2], b[3]]).ok_or(PsErr::Ps("rangecheck"))?; + let num = |k: &[u8]| p.get_name(k).and_then(|o| o.num()); + let step = (num(b"XStep").unwrap_or(bbox[2] - bbox[0]), num(b"YStep").unwrap_or(bbox[3] - bbox[1])); + if step.0 == 0.0 || step.1 == 0.0 || !step.0.is_finite() || !step.1.is_finite() { + return err("rangecheck"); + } + let m = match p.get_name(b"CraftPsMatrix") { + Some(Obj::Array(a, _)) => matrix_of(&a)?, + _ => M::ID, + }; + let paint = p.get_name(b"PaintProc").ok_or(PsErr::Ps("undefined"))?; + let under = ip.gs.pattern_base.as_deref().cloned(); + let cap = ip.out.begin_cell(); + ip.gsave()?; + // The cell is drawn in pattern space, unclipped, from a fresh path. + ip.gs.ctm = M::ID; + ip.gs.clip = None; + ip.gs.path.clear(); + ip.gs.cur = None; + ip.gs.nulldev = false; + if let Some(c) = color { + // An uncoloured cell paints in the colour given with the pattern. + ip.gs.space = under.unwrap_or(match c.len() { + 3 => crate::read::gstate::Space::Rgb, + 4 => crate::read::gstate::Space::Cmyk, + _ => crate::read::gstate::Space::Gray, + }); + ip.gs.color = c; + ip.gs.pattern = None; + ip.gs.color_locked = true; + } + let r = ip.push(Obj::Dict(p.clone())).and_then(|()| ip.call(paint)); + ip.grestore(); + let n = ip.out.end_cell(cap, bbox, step, m).map_err(PsErr::Fatal)?; + r.map(|()| n) +} diff --git a/crates/ps/src/read/pdf.rs b/crates/ps/src/read/pdf.rs new file mode 100644 index 000000000..0faabe09a --- /dev/null +++ b/crates/ps/src/read/pdf.rs @@ -0,0 +1,629 @@ +//! What the program paints, written as a one-page PDF. +//! +//! Paths arrive in device space (the EPS's default user space). Clipping is applied lazily: +//! before each painting operation the clips in force are matched against those the content +//! stream has applied, popping (`Q`) and pushing (`q … W n`) the difference, so the PostScript +//! program's own gsave/grestore pattern doesn't matter. + +use std::rc::Rc; + +use pdf_writer::types::{LineCapStyle, LineJoinStyle}; +use pdf_writer::{Content, Filter, Finish, Name, Pdf, Rect, Ref}; + +use crate::read::gstate::{Clip, DevColor, M, Seg, clip_chain}; + +/// The most path segments and images written. +const MAX_SEGMENTS: usize = 20_000_000; +const MAX_IMAGES: usize = 100_000; + +#[derive(Clone, Debug, PartialEq)] +pub enum ImgSpace { + Gray, + Rgb, + Cmyk, + Indexed { base: Box<ImgSpace>, hival: u8, lookup: Vec<u8> }, +} + +#[derive(Debug)] +pub struct Image { + pub w: u32, + pub h: u32, + pub bpc: u8, + /// None for a stencil mask (`imagemask`). + pub space: Option<ImgSpace>, + pub decode: Option<Vec<f32>>, + pub data: Vec<u8>, + /// `data` is a JPEG (DCTDecode passed through). + pub dct: bool, + pub interpolate: bool, + /// An 8-bit soft mask (w, h, alpha). + pub smask: Option<(u32, u32, Vec<u8>)>, +} + +/// The device space a shading's colours were sampled in. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum OutSpace { + Gray, + Rgb, + Cmyk, +} + +impl OutSpace { + fn comps(self) -> usize { + match self { + OutSpace::Gray => 1, + OutSpace::Rgb => 3, + OutSpace::Cmyk => 4, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ShadeKind { + Axial([f64; 4]), + Radial([f64; 6]), + /// A function of (x, y) over its domain, mapped by `matrix`. + Function { + domain: [f64; 4], + matrix: M, + }, + /// Vertices in threes; `Coons` and `Tensor` patches of 12 and 16 points. + Triangles, + Coons, + Tensor, +} + +/// A smooth shading with its colours sampled: along the axis (`samples` of them), over a +/// `samples` × `samples` grid, or one per vertex or patch corner. +#[derive(Clone, Debug)] +pub struct Shading { + pub kind: ShadeKind, + pub extend: [bool; 2], + pub space: OutSpace, + pub data: Vec<u8>, + pub samples: usize, + pub bbox: Option<[f64; 4]>, + pub points: Vec<(f64, f64)>, +} + +/// A tiling pattern cell: its content (in pattern space), cell box, steps and pattern matrix. +pub struct Tiling { + content: Vec<u8>, + bbox: [f64; 4], + step: (f64, f64), + matrix: M, +} + +/// What a pattern cell's content replaces while it is captured. +pub struct Capture { + c: Content, + applied: Vec<Rc<Clip>>, + state: PaintState, + saved: Vec<PaintState>, +} + +#[derive(Clone, Debug, Default, PartialEq)] +struct PaintState { + fill: Option<DevColor>, + stroke: Option<DevColor>, +} + +pub struct StrokeParams<'a> { + pub width: f64, + pub cap: i64, + pub join: i64, + pub miter: f64, + pub dash: &'a (Vec<f64>, f64), +} + +pub struct Out { + c: Content, + images: Vec<Image>, + shadings: Vec<Shading>, + tilings: Vec<Tiling>, + origin: (f64, f64), + applied: Vec<Rc<Clip>>, + state: PaintState, + saved: Vec<PaintState>, + segments: usize, + /// Anything painted at all. + pub painted: bool, +} + +fn f(v: f64) -> f32 { + if v.is_finite() { v.clamp(-3.0e7, 3.0e7) as f32 } else { 0.0 } +} + +impl Out { + pub fn new(origin: (f64, f64)) -> Self { + let mut c = Content::new(); + c.transform([1.0, 0.0, 0.0, 1.0, f(-origin.0), f(-origin.1)]); + Out { + c, + images: Vec::new(), + shadings: Vec::new(), + tilings: Vec::new(), + origin, + applied: Vec::new(), + state: PaintState::default(), + saved: Vec::new(), + segments: 0, + painted: false, + } + } + + /// Preserve the semantic text for consumers that group outlined glyphs. + pub fn begin_actual_text(&mut self, text: &str) { + self.c.begin_marked_content_with_properties(Name(b"Span")).properties().actual_text(pdf_writer::TextStr(text)); + } + + pub fn end_actual_text(&mut self) { + self.c.end_marked_content(); + } + + fn sync_clip(&mut self, clip: &Option<Rc<Clip>>) -> Result<(), String> { + let target = clip_chain(clip); + let common = self.applied.iter().zip(&target).take_while(|(a, b)| Rc::ptr_eq(a, b)).count(); + while self.applied.len() > common { + self.applied.pop(); + self.c.restore_state(); + self.state = self.saved.pop().unwrap_or_default(); + } + for node in target.into_iter().skip(common) { + self.c.save_state(); + self.saved.push(self.state.clone()); + self.path(&node.path)?; + if node.eo { + self.c.clip_even_odd(); + } else { + self.c.clip_nonzero(); + } + self.c.end_path(); + self.applied.push(node); + } + Ok(()) + } + + fn path(&mut self, path: &[Seg]) -> Result<(), String> { + self.segments = self.segments.saturating_add(path.len()); + if self.segments > MAX_SEGMENTS { + return Err("too many path segments".into()); + } + for s in path { + match *s { + Seg::Move(x, y) => { + self.c.move_to(f(x), f(y)); + } + Seg::Line(x, y) => { + self.c.line_to(f(x), f(y)); + } + Seg::Curve(a, b, c, d, e, g) => { + self.c.cubic_to(f(a), f(b), f(c), f(d), f(e), f(g)); + } + Seg::Close => { + self.c.close_path(); + } + } + } + Ok(()) + } + + fn set_fill(&mut self, color: DevColor) { + if self.state.fill == Some(color) { + return; + } + match color { + DevColor::Gray(g) => self.c.set_fill_gray(f(g)), + DevColor::Rgb(r, g, b) => self.c.set_fill_rgb(f(r), f(g), f(b)), + DevColor::Cmyk(c, m, y, k) => self.c.set_fill_cmyk(f(c), f(m), f(y), f(k)), + }; + self.state.fill = Some(color); + } + + fn set_stroke(&mut self, color: DevColor) { + if self.state.stroke == Some(color) { + return; + } + match color { + DevColor::Gray(g) => self.c.set_stroke_gray(f(g)), + DevColor::Rgb(r, g, b) => self.c.set_stroke_rgb(f(r), f(g), f(b)), + DevColor::Cmyk(c, m, y, k) => self.c.set_stroke_cmyk(f(c), f(m), f(y), f(k)), + }; + self.state.stroke = Some(color); + } + + pub fn fill(&mut self, clip: &Option<Rc<Clip>>, path: &[Seg], eo: bool, color: DevColor) -> Result<(), String> { + if !path.iter().any(|s| !matches!(s, Seg::Move(..))) { + return Ok(()); + } + self.sync_clip(clip)?; + self.set_fill(color); + self.path(path)?; + if eo { + self.c.fill_even_odd(); + } else { + self.c.fill_nonzero(); + } + self.painted = true; + Ok(()) + } + + /// Stroke a device-space path drawn under `ctm` (the pen is shaped in user space). + pub fn stroke(&mut self, clip: &Option<Rc<Clip>>, path: &[Seg], ctm: &M, p: &StrokeParams, color: DevColor) -> Result<(), String> { + if !path.iter().any(|s| !matches!(s, Seg::Move(..))) { + return Ok(()); + } + let Some(inv) = ctm.inv() else { return Ok(()) }; + self.sync_clip(clip)?; + self.set_stroke(color); + self.c.save_state(); + self.c.transform(ctm.0.map(f)); + let user: Vec<Seg> = path.iter().map(|s| s.map(&inv)).collect(); + self.c.set_line_width(f(p.width.max(0.0))); + self.c.set_line_cap(match p.cap { + 1 => LineCapStyle::RoundCap, + 2 => LineCapStyle::ProjectingSquareCap, + _ => LineCapStyle::ButtCap, + }); + self.c.set_line_join(match p.join { + 1 => LineJoinStyle::RoundJoin, + 2 => LineJoinStyle::BevelJoin, + _ => LineJoinStyle::MiterJoin, + }); + self.c.set_miter_limit(f(p.miter.max(1.0))); + if crate::read::gstate::dashes_ok(&user, &p.dash.0) { + self.c.set_dash_pattern(p.dash.0.iter().map(|d| f(*d)), f(p.dash.1)); + } + self.path(&user)?; + self.c.stroke(); + self.c.restore_state(); + self.painted = true; + Ok(()) + } + + /// Paint an image: `cm` maps the unit square onto the page; stencil masks use `fill`. + pub fn image(&mut self, clip: &Option<Rc<Clip>>, cm: &M, img: Image, fill: Option<DevColor>) -> Result<(), String> { + if self.images.len() >= MAX_IMAGES { + return Err("too many images".into()); + } + if !cm.finite() || img.w == 0 || img.h == 0 { + return Ok(()); + } + self.sync_clip(clip)?; + if let Some(color) = fill { + self.set_fill(color); + } + let n = self.images.len(); + self.images.push(img); + self.c.save_state(); + self.c.transform(cm.0.map(f)); + let name = format!("Im{n}"); + self.c.x_object(Name(name.as_bytes())); + self.c.restore_state(); + self.painted = true; + Ok(()) + } + + /// Start a pattern cell: painting goes to its own content until [`Out::end_cell`]. + pub fn begin_cell(&mut self) -> Capture { + Capture { + c: std::mem::replace(&mut self.c, Content::new()), + applied: std::mem::take(&mut self.applied), + state: std::mem::take(&mut self.state), + saved: std::mem::take(&mut self.saved), + } + } + + /// Finish a pattern cell: its pattern number. + pub fn end_cell(&mut self, cap: Capture, bbox: [f64; 4], step: (f64, f64), matrix: M) -> Result<usize, String> { + let mut cell = std::mem::replace(&mut self.c, cap.c); + for _ in 0..self.applied.len() { + cell.restore_state(); + } + self.applied = cap.applied; + self.state = cap.state; + self.saved = cap.saved; + if self.tilings.len() >= MAX_IMAGES { + return Err("too many patterns".into()); + } + // Pattern space maps to the page's default space, which the content moved to the origin. + let matrix = matrix.then(&M([1.0, 0.0, 0.0, 1.0, -self.origin.0, -self.origin.1])); + self.tilings.push(Tiling { content: cell.finish().into_vec(), bbox, step, matrix }); + Ok(self.tilings.len() - 1) + } + + /// Fill a device-space path with tiling pattern `n`. + pub fn fill_tiling(&mut self, clip: &Option<Rc<Clip>>, path: &[Seg], eo: bool, n: usize) -> Result<(), String> { + if !path.iter().any(|s| !matches!(s, Seg::Move(..))) { + return Ok(()); + } + self.sync_clip(clip)?; + self.c.set_fill_color_space(pdf_writer::types::ColorSpaceOperand::Pattern); + let name = format!("P{n}"); + self.c.set_fill_pattern(None, Name(name.as_bytes())); + self.state.fill = None; + self.path(path)?; + if eo { + self.c.fill_even_odd(); + } else { + self.c.fill_nonzero(); + } + self.painted = true; + Ok(()) + } + + /// Paint a shading in shading space `m` (inside `path` too, for a shading pattern fill). + pub fn shade(&mut self, clip: &Option<Rc<Clip>>, path: Option<&[Seg]>, eo: bool, m: &M, s: Shading) -> Result<(), String> { + if self.shadings.len() >= MAX_IMAGES { + return Err("too many shadings".into()); + } + if !m.finite() || m.inv().is_none() { + return Ok(()); + } + self.sync_clip(clip)?; + self.c.save_state(); + if let Some(p) = path { + self.path(p)?; + if eo { + self.c.clip_even_odd(); + } else { + self.c.clip_nonzero(); + } + self.c.end_path(); + } + self.c.transform(m.0.map(f)); + if let Some([x0, y0, x1, y1]) = s.bbox { + self.c.rect(f(x0), f(y0), f(x1 - x0), f(y1 - y0)); + self.c.clip_nonzero(); + self.c.end_path(); + } + let name = format!("Sh{}", self.shadings.len()); + self.shadings.push(s); + self.c.shading(Name(name.as_bytes())); + self.c.restore_state(); + self.painted = true; + Ok(()) + } + + /// The PDF: one page of `size`, its content, images and shadings. + /// Path segments written so far (clips included). + pub fn segments(&self) -> usize { + self.segments + } + + pub fn finish(self, size: (f64, f64)) -> Vec<u8> { + let mut pdf = Pdf::new(); + // ActualText marked content is defined in PDF 1.5; the rest of this output uses basic + // page content, without transparency groups. + pdf.set_version(1, 5); + let (catalog, pages, page, content) = (Ref::new(1), Ref::new(2), Ref::new(3), Ref::new(4)); + let mut next = 5; + let mut alloc = || { + let r = Ref::new(next); + next += 1; + r + }; + let image_refs: Vec<(Ref, Option<Ref>)> = self.images.iter().map(|i| (alloc(), i.smask.as_ref().map(|_| alloc()))).collect(); + let shading_refs: Vec<(Ref, Ref)> = self.shadings.iter().map(|_| (alloc(), alloc())).collect(); + let tiling_refs: Vec<Ref> = self.tilings.iter().map(|_| alloc()).collect(); + // Every resource is listed for the page and for each pattern cell (names are global). + let resources = |res: &mut pdf_writer::writers::Resources<'_>| { + let mut xo = res.x_objects(); + for (i, (r, _)) in image_refs.iter().enumerate() { + let name = format!("Im{i}"); + xo.pair(Name(name.as_bytes()), *r); + } + xo.finish(); + let mut sh = res.shadings(); + for (i, (r, _)) in shading_refs.iter().enumerate() { + let name = format!("Sh{i}"); + sh.pair(Name(name.as_bytes()), *r); + } + sh.finish(); + let mut pa = res.patterns(); + for (i, r) in tiling_refs.iter().enumerate() { + let name = format!("P{i}"); + pa.pair(Name(name.as_bytes()), *r); + } + pa.finish(); + }; + pdf.catalog(catalog).pages(pages); + pdf.pages(pages).kids([page]).count(1); + { + let mut p = pdf.page(page); + p.parent(pages); + p.media_box(Rect::new(0.0, 0.0, f(size.0.max(1.0)), f(size.1.max(1.0)))); + p.contents(content); + let mut res = p.resources(); + resources(&mut res); + res.finish(); + p.finish(); + } + let mut c = self.c; + for _ in 0..self.applied.len() { + c.restore_state(); + } + let raw = c.finish().into_vec(); + let z = miniz_oxide::deflate::compress_to_vec_zlib(&raw, 6); + pdf.stream(content, &z).filter(Filter::FlateDecode); + for (img, (r, smask)) in self.images.iter().zip(&image_refs) { + let packed; + let (data, filter) = if img.dct { + (&img.data[..], Filter::DctDecode) + } else { + packed = miniz_oxide::deflate::compress_to_vec_zlib(&img.data, 6); + (&packed[..], Filter::FlateDecode) + }; + let mut x = pdf.image_xobject(*r, data); + x.filter(filter); + x.width(i32::try_from(img.w).unwrap_or(i32::MAX)); + x.height(i32::try_from(img.h).unwrap_or(i32::MAX)); + match &img.space { + None => { + x.image_mask(true); + } + Some(space) => { + x.bits_per_component(i32::from(img.bpc)); + match space { + ImgSpace::Gray => x.color_space().device_gray(), + ImgSpace::Rgb => x.color_space().device_rgb(), + ImgSpace::Cmyk => x.color_space().device_cmyk(), + ImgSpace::Indexed { base, hival, lookup } => { + let base = match **base { + ImgSpace::Rgb => Name(b"DeviceRGB"), + ImgSpace::Cmyk => Name(b"DeviceCMYK"), + _ => Name(b"DeviceGray"), + }; + x.color_space().indexed(base, i32::from(*hival), lookup); + } + } + } + } + if img.space.is_none() { + x.bits_per_component(1); + } + if let Some(d) = &img.decode { + x.decode(d.iter().copied()); + } + if img.interpolate { + x.interpolate(true); + } + if let Some(m) = smask { + x.s_mask(*m); + } + x.finish(); + if let (Some(m), Some((w, h, alpha))) = (smask, &img.smask) { + let z = miniz_oxide::deflate::compress_to_vec_zlib(alpha, 6); + let mut s = pdf.image_xobject(*m, &z); + s.filter(Filter::FlateDecode); + s.width(i32::try_from(*w).unwrap_or(i32::MAX)); + s.height(i32::try_from(*h).unwrap_or(i32::MAX)); + s.color_space().device_gray(); + s.bits_per_component(8); + s.finish(); + } + } + for (s, (r, fr)) in self.shadings.iter().zip(&shading_refs) { + write_shading(&mut pdf, s, *r, *fr); + } + for (t, r) in self.tilings.iter().zip(&tiling_refs) { + let z = miniz_oxide::deflate::compress_to_vec_zlib(&t.content, 6); + let mut p = pdf.tiling_pattern(*r, &z); + p.filter(Filter::FlateDecode); + p.paint_type(pdf_writer::types::PaintType::Colored); + p.tiling_type(pdf_writer::types::TilingType::ConstantSpacing); + let [x0, y0, x1, y1] = t.bbox; + p.bbox(Rect::new(f(x0), f(y0), f(x1), f(y1))); + p.x_step(f(t.step.0)); + p.y_step(f(t.step.1)); + p.matrix(t.matrix.0.map(f)); + let mut res = p.resources(); + resources(&mut res); + res.finish(); + p.finish(); + } + pdf.finish() + } +} + +fn set_space(cs: pdf_writer::writers::ColorSpace<'_>, s: OutSpace) { + match s { + OutSpace::Gray => cs.device_gray(), + OutSpace::Rgb => cs.device_rgb(), + OutSpace::Cmyk => cs.device_cmyk(), + } +} + +fn write_shading(pdf: &mut Pdf, s: &Shading, r: Ref, fr: Ref) { + use pdf_writer::types::FunctionShadingType; + use pdf_writer::writers::StreamShadingType; + let n = s.space.comps(); + let range: Vec<f32> = (0..n).flat_map(|_| [0.0, 1.0]).collect(); + let samples = i32::try_from(s.samples.max(2)).unwrap_or(2); + match &s.kind { + ShadeKind::Axial(_) | ShadeKind::Radial(_) | ShadeKind::Function { .. } => { + { + let mut func = pdf.sampled_function(fr, &s.data); + if let ShadeKind::Function { domain, .. } = &s.kind { + func.domain(domain.map(f)); + func.size([samples, samples]); + } else { + func.domain([0.0, 1.0]); + func.size([samples]); + } + func.range(range.iter().copied()); + func.bits_per_sample(8); + } + let mut sh = pdf.function_shading(r); + match &s.kind { + ShadeKind::Axial(c) => { + sh.shading_type(FunctionShadingType::Axial); + sh.coords(c.map(f)); + sh.extend(s.extend); + } + ShadeKind::Radial(c) => { + sh.shading_type(FunctionShadingType::Radial); + sh.coords(c.map(f)); + sh.extend(s.extend); + } + ShadeKind::Function { domain, matrix } => { + sh.shading_type(FunctionShadingType::Function); + sh.domain(domain.map(f)); + sh.matrix(matrix.0.map(f)); + } + _ => {} + } + set_space(sh.color_space(), s.space); + sh.function(fr); + } + ShadeKind::Triangles | ShadeKind::Coons | ShadeKind::Tensor => { + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for (x, y) in &s.points { + x0 = x0.min(*x); + y0 = y0.min(*y); + x1 = x1.max(*x); + y1 = y1.max(*y); + } + if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) { + return; + } + let (x1, y1) = (x1.max(x0 + 1e-3), y1.max(y0 + 1e-3)); + let q = |v: f64, lo: f64, hi: f64| (((v - lo) / (hi - lo)).clamp(0.0, 1.0) * f64::from(u32::MAX)).round() as u32; + let mut data = Vec::new(); + let (per, cols) = match s.kind { + ShadeKind::Triangles => (1, 1), + ShadeKind::Coons => (12, 4), + _ => (16, 4), + }; + let colors: Vec<&[u8]> = s.data.chunks(n).collect(); + for (i, chunk) in s.points.chunks(per).enumerate() { + if chunk.len() != per { + break; + } + data.push(0u8); + for (x, y) in chunk { + data.extend(q(*x, x0, x1).to_be_bytes()); + data.extend(q(*y, y0, y1).to_be_bytes()); + } + for k in 0..cols { + data.extend_from_slice(colors.get(i * cols + k).copied().unwrap_or(&[])); + } + } + let z = miniz_oxide::deflate::compress_to_vec_zlib(&data, 6); + let mut sh = pdf.stream_shading(r, &z); + sh.filter(Filter::FlateDecode); + sh.shading_type(match s.kind { + ShadeKind::Triangles => StreamShadingType::FreeformGouraud, + ShadeKind::Coons => StreamShadingType::CoonsPatch, + _ => StreamShadingType::TensorProductPatch, + }); + set_space(sh.color_space(), s.space); + sh.bits_per_coordinate(32); + sh.bits_per_component(8); + sh.bits_per_flag(8); + let mut decode = vec![f(x0), f(x1), f(y0), f(y1)]; + decode.extend(range); + sh.decode(decode); + } + } +} diff --git a/crates/ps/src/read/scan.rs b/crates/ps/src/read/scan.rs new file mode 100644 index 000000000..9f6aa14c3 --- /dev/null +++ b/crates/ps/src/read/scan.rs @@ -0,0 +1,375 @@ +//! The scanner: turns a file's bytes into objects, building procedures `{ … }` whole. + +use crate::read::obj::{Obj, PArr, PStr, name}; +use crate::read::source::Sources; + +/// How deeply procedures may nest. +const MAX_NESTING: usize = 1000; +/// The longest string or name token. +const MAX_TOKEN: usize = 64 << 20; + +pub enum Token { + Obj(Obj), + /// `//name`: replaced by its value when scanned. + Immediate(Vec<u8>), +} + +pub fn is_ws(c: u8) -> bool { + matches!(c, 0 | b'\t' | b'\n' | 0x0c | b'\r' | b' ') +} + +pub fn is_delim(c: u8) -> bool { + matches!(c, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') +} + +/// One token from `src`, or None at its end. Procedures come back whole, as executable arrays; +/// `//name` inside them is resolved through `resolve`. +pub fn next(srcs: &mut Sources, src: usize, resolve: &mut dyn FnMut(&[u8]) -> Option<Obj>) -> Result<Option<Obj>, String> { + let mut stack: Vec<Vec<Obj>> = Vec::new(); + loop { + let Some(tok) = token(srcs, src)? else { + return if stack.is_empty() { Ok(None) } else { Err("unterminated procedure".into()) }; + }; + let obj = match tok { + Token::Obj(Obj::Name(n, true)) if &*n == b"{" => { + if stack.len() >= MAX_NESTING { + return Err("procedures nest too deeply".into()); + } + stack.push(Vec::new()); + continue; + } + Token::Obj(Obj::Name(n, true)) if &*n == b"}" => { + let Some(body) = stack.pop() else { return Err("unmatched }".into()) }; + Obj::Array(PArr::new(body), true) + } + Token::Obj(o) => o, + Token::Immediate(n) => resolve(&n).ok_or_else(|| format!("undefined //{}", String::from_utf8_lossy(&n)))?, + }; + match stack.last_mut() { + Some(body) => body.push(obj), + None => return Ok(Some(obj)), + } + } +} + +fn token(srcs: &mut Sources, src: usize) -> Result<Option<Token>, String> { + // Whitespace and comments. + let c = loop { + let Some(c) = srcs.read(src) else { return Ok(None) }; + if is_ws(c) { + continue; + } + if c == b'%' { + while let Some(c) = srcs.read(src) { + if c == b'\n' || c == b'\r' { + break; + } + } + continue; + } + break c; + }; + match c { + b'(' => string(srcs, src).map(|s| Some(Token::Obj(Obj::Str(PStr::new(s), false)))), + b'<' => match srcs.read(src) { + Some(b'<') => Ok(Some(Token::Obj(Obj::Name(name(b"<<"), true)))), + Some(b'~') => ascii85(srcs, src).map(|s| Some(Token::Obj(Obj::Str(PStr::new(s), false)))), + Some(c) => { + srcs.unread(src); + let _ = c; + hex(srcs, src).map(|s| Some(Token::Obj(Obj::Str(PStr::new(s), false)))) + } + None => Err("unterminated hex string".into()), + }, + b'>' => match srcs.read(src) { + Some(b'>') => Ok(Some(Token::Obj(Obj::Name(name(b">>"), true)))), + _ => Err("stray >".into()), + }, + b'[' | b']' | b'{' | b'}' => Ok(Some(Token::Obj(Obj::Name(name(&[c]), true)))), + b')' => Err("stray )".into()), + b'/' => { + let immediate = srcs.peek(src) == Some(b'/'); + if immediate { + srcs.read(src); + } + let n = regular(srcs, src, None)?; + Ok(Some(if immediate { Token::Immediate(n) } else { Token::Obj(Obj::Name(name(&n), false)) })) + } + _ => { + let t = regular(srcs, src, Some(c))?; + Ok(Some(Token::Obj(number(&t).unwrap_or_else(|| Obj::Name(name(&t), true))))) + } + } +} + +/// A run of regular characters. The whitespace character that ends it is consumed (a CR LF +/// pair as one), a delimiter is left for the next token. +fn regular(srcs: &mut Sources, src: usize, first: Option<u8>) -> Result<Vec<u8>, String> { + let mut t: Vec<u8> = first.into_iter().collect(); + while let Some(c) = srcs.read(src) { + if is_ws(c) { + if c == b'\r' && srcs.peek(src) == Some(b'\n') { + srcs.read(src); + } + break; + } + if is_delim(c) { + srcs.unread(src); + break; + } + t.push(c); + if t.len() > MAX_TOKEN { + return Err("token too long".into()); + } + } + Ok(t) +} + +fn string(srcs: &mut Sources, src: usize) -> Result<Vec<u8>, String> { + let mut out = Vec::new(); + let mut depth = 0usize; + loop { + let c = srcs.read(src).ok_or("unterminated string")?; + match c { + b'(' => { + depth += 1; + out.push(c); + } + b')' => { + if depth == 0 { + return Ok(out); + } + depth -= 1; + out.push(c); + } + b'\\' => { + let e = srcs.read(src).ok_or("unterminated string")?; + match e { + b'n' => out.push(b'\n'), + b'r' => out.push(b'\r'), + b't' => out.push(b'\t'), + b'b' => out.push(8), + b'f' => out.push(12), + b'\r' => { + if srcs.peek(src) == Some(b'\n') { + srcs.read(src); + } + } + b'\n' => {} + b'0'..=b'7' => { + let mut v = u32::from(e - b'0'); + for _ in 0..2 { + match srcs.peek(src) { + Some(d @ b'0'..=b'7') => { + srcs.read(src); + v = v * 8 + u32::from(d - b'0'); + } + _ => break, + } + } + out.push((v & 0xFF) as u8); + } + other => out.push(other), + } + } + // An end of line inside a string is a newline, whatever its form. + b'\r' => { + if srcs.peek(src) == Some(b'\n') { + srcs.read(src); + } + out.push(b'\n'); + } + _ => out.push(c), + } + if out.len() > MAX_TOKEN { + return Err("string too long".into()); + } + } +} + +fn hex(srcs: &mut Sources, src: usize) -> Result<Vec<u8>, String> { + let mut out = Vec::new(); + let mut hi: Option<u8> = None; + loop { + let c = srcs.read(src).ok_or("unterminated hex string")?; + if c == b'>' { + break; + } + if is_ws(c) { + continue; + } + let v = match c { + b'0'..=b'9' => c - b'0', + b'a'..=b'f' => c - b'a' + 10, + b'A'..=b'F' => c - b'A' + 10, + _ => return Err("bad hex string".into()), + }; + match hi.take() { + Some(h) => out.push(h << 4 | v), + None => hi = Some(v), + } + if out.len() > MAX_TOKEN { + return Err("string too long".into()); + } + } + if let Some(h) = hi { + out.push(h << 4); + } + Ok(out) +} + +fn ascii85(srcs: &mut Sources, src: usize) -> Result<Vec<u8>, String> { + let mut out = Vec::new(); + let mut group = [0u64; 5]; + let mut n = 0; + loop { + let c = srcs.read(src).ok_or("unterminated ASCII85 string")?; + if is_ws(c) { + continue; + } + if c == b'~' { + if srcs.read(src) != Some(b'>') { + return Err("bad ASCII85 end".into()); + } + break; + } + if c == b'z' && n == 0 { + out.extend([0; 4]); + continue; + } + if !(b'!'..=b'u').contains(&c) { + return Err("bad ASCII85 string".into()); + } + if let Some(g) = group.get_mut(n) { + *g = u64::from(c - b'!'); + } + n += 1; + if n == 5 { + let v = group.iter().fold(0u64, |a, d| a * 85 + d); + out.extend(u32::try_from(v).map_err(|_| "ASCII85 overflow")?.to_be_bytes()); + n = 0; + } + if out.len() > MAX_TOKEN { + return Err("string too long".into()); + } + } + if n > 1 { + for g in group.iter_mut().skip(n) { + *g = 84; + } + let v = group.iter().fold(0u64, |a, d| a * 85 + d).min(u64::from(u32::MAX)); + let v = u32::try_from(v).unwrap_or(u32::MAX); + out.extend(v.to_be_bytes().iter().take(n - 1)); + } + Ok(out) +} + +/// An integer, radix number (`16#FF`) or real; None for anything else. +pub fn number(t: &[u8]) -> Option<Obj> { + let s = std::str::from_utf8(t).ok()?; + let first = *t.first()?; + if !(first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.')) { + return None; + } + if let Some((base, digits)) = s.split_once('#') { + let base: u32 = base.parse().ok()?; + if !(2..=36).contains(&base) || digits.is_empty() { + return None; + } + let v = u64::from_str_radix(digits, base).ok()?; + // Radix numbers are unsigned 32-bit patterns. + return Some(Obj::Int(i64::from(v as u32 as i32))); + } + let digits_only = s.strip_prefix(['+', '-']).unwrap_or(s); + if !digits_only.is_empty() && digits_only.bytes().all(|b| b.is_ascii_digit()) { + return Some(match s.parse::<i64>() { + Ok(i) if i32::try_from(i).is_ok() => Obj::Int(i), + _ => Obj::Real(s.parse::<f64>().ok()?), + }); + } + // Reals: digits with a point and/or an exponent; nothing else (`1e` or `.` alone are names). + let mut seen_digit = false; + let mut seen_e = false; + for (i, b) in digits_only.bytes().enumerate() { + match b { + b'0'..=b'9' => seen_digit = true, + b'.' if !seen_e => {} + b'e' | b'E' if seen_digit && !seen_e => seen_e = true, + b'+' | b'-' if seen_e && matches!(digits_only.as_bytes().get(i.wrapping_sub(1)), Some(b'e' | b'E')) => {} + _ => return None, + } + } + if !seen_digit || digits_only.ends_with(['e', 'E', '+', '-']) { + return None; + } + let v: f64 = s.parse().ok()?; + v.is_finite().then_some(Obj::Real(v)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::read::source::Source; + + fn all(text: &[u8]) -> Vec<Obj> { + let mut s = Sources::default(); + let id = s.add(Source::bytes(text.to_vec())); + let mut out = Vec::new(); + while let Some(o) = next(&mut s, id, &mut |_| Some(Obj::Int(42))).unwrap() { + out.push(o); + } + out + } + + #[test] + fn scans_the_token_kinds() { + let t = all(b"12 -3.5 1e3 16#FF /lit name (a\\(b\\)\\101\\\n c) <41 42> <~87cURDZ~> {1 {2} add} //x [ ] << >> % note\n.5 1.e2 -."); + let kinds: Vec<String> = t + .iter() + .map(|o| match o { + Obj::Int(i) => format!("i{i}"), + Obj::Real(r) => format!("r{r}"), + Obj::Name(n, x) => format!("{}{}", if *x { "x" } else { "/" }, String::from_utf8_lossy(n)), + Obj::Str(s, _) => format!("s{}", String::from_utf8_lossy(&s.bytes())), + Obj::Array(a, true) => format!("p{}", a.len), + _ => "?".into(), + }) + .collect(); + assert_eq!( + kinds, + [ + "i12", "r-3.5", "r1000", "i255", "/lit", "xname", "sa(b)A c", "sAB", "sHello", "p3", "i42", "x[", "x]", "x<<", "x>>", "r0.5", "r100", + "x-." + ] + ); + } + + #[test] + fn a_token_ending_in_whitespace_consumes_it() { + let mut s = Sources::default(); + let id = s.add(Source::bytes(b"image\r\nDATA".to_vec())); + let _ = next(&mut s, id, &mut |_| None).unwrap(); + assert_eq!(s.read(id), Some(b'D')); + } + + #[test] + fn malformed_input_is_an_error() { + for bad in [&b"(open"[..], b"<4g>", b"{ 1 2", b"}", b"<~ab~x"] { + let mut s = Sources::default(); + let id = s.add(Source::bytes(bad.to_vec())); + let mut r = Ok(None); + for _ in 0..5 { + r = next(&mut s, id, &mut |_| None); + if r.is_err() { + break; + } + } + assert!(r.is_err(), "{}", String::from_utf8_lossy(bad)); + } + // Deep nesting is refused, not a stack overflow. + let deep = vec![b'{'; 5000]; + let mut s = Sources::default(); + let id = s.add(Source::bytes(deep)); + assert!(next(&mut s, id, &mut |_| None).is_err()); + } +} diff --git a/crates/ps/src/read/source.rs b/crates/ps/src/read/source.rs new file mode 100644 index 000000000..c2f6c8246 --- /dev/null +++ b/crates/ps/src/read/source.rs @@ -0,0 +1,986 @@ +//! Files: the program itself, strings run as code, decoding filters and `eexec` sections. +//! +//! Filters decode as they are read, so a filter made over `currentfile` before the operator +//! that consumes it (`currentfile /ASCII85Decode filter … image`) reads the data that follows +//! that operator. A filter takes from the file beneath only what its encoding needs: bytes a +//! decompressor fetched past its end are pushed back, so the program carries on after the data. + +use std::collections::VecDeque; +use std::rc::Rc; + +/// The most bytes one filter may decode to, and one reusable stream may hold. +const MAX_DECODED: usize = 256 << 20; +/// How deep files may sit on one another. +const MAX_CHAIN: usize = 16; + +pub enum Dec { + Hex { + hi: Option<u8>, + }, + A85 { + group: [u8; 5], + n: usize, + first: bool, + }, + RunLength, + Lzw { + dec: Box<weezl::decode::Decoder>, + pending: Vec<u8>, + }, + Flate { + state: Box<miniz_oxide::inflate::stream::InflateState>, + pending: Vec<u8>, + }, + SubFile { + eod: Vec<u8>, + count: usize, + left: Option<usize>, + skip_on_pop: bool, + window: VecDeque<u8>, + }, + /// JPEG data: only images take it (whole, as it is). + Dct, +} + +pub enum Kind { + Bytes(Rc<Vec<u8>>), + /// A window onto a string's storage, read in place (`token`, executing a string). + Shared { + buf: Rc<std::cell::RefCell<Vec<u8>>>, + off: usize, + len: usize, + }, + /// Decrypting `eexec` over another file. `hex` is decided by the first four bytes. + Eexec { + up: usize, + r: u16, + hex: Option<bool>, + skipped: u8, + }, + Filter { + up: usize, + dec: Dec, + out: VecDeque<u8>, + done: bool, + produced: usize, + }, +} + +pub struct Source { + pub kind: Kind, + pub pos: usize, + pub closed: bool, + /// Raw JPEG data for a DCTDecode filter, once taken. + pub dct: Option<Rc<Vec<u8>>>, + /// The last byte given, and bytes pushed back (read again first; the last pushed first). + pub last: Option<u8>, + pub back: Vec<u8>, + /// A PNG or TIFF predictor under Flate or LZW. + pub predictor: Option<Predictor>, +} + +impl Source { + pub fn bytes(data: Vec<u8>) -> Self { + Self::shared(Rc::new(data)) + } + + pub fn shared(data: Rc<Vec<u8>>) -> Self { + Self::of(Kind::Bytes(data)) + } + + /// A string read in place, without copying it. + pub fn string(s: &crate::read::obj::PStr) -> Self { + Self::of(Kind::Shared { buf: s.buf.clone(), off: s.off, len: s.len }) + } + + pub fn eexec(up: usize) -> Self { + Self::of(Kind::Eexec { up, r: 55665, hex: None, skipped: 0 }) + } + + fn of(kind: Kind) -> Self { + Source { kind, pos: 0, closed: false, dct: None, last: None, back: Vec::new(), predictor: None } + } +} + +fn is_ws(c: u8) -> bool { + matches!(c, 0 | b'\t' | b'\n' | 0x0c | b'\r' | b' ') +} + +fn hex_val(c: u8) -> Option<u8> { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } +} + +#[derive(Debug, Default)] +pub struct FilterParams { + pub early_change: bool, + pub predictor: i64, + pub colors: i64, + pub bpc: i64, + pub columns: i64, + pub eod_count: usize, + pub eod_string: Vec<u8>, +} + +#[derive(Debug, Clone)] +pub struct Predictor { + kind: i64, + bpp: usize, + row: usize, + prev: Vec<u8>, + cur: Vec<u8>, +} + +/// The sources, read through one another (`eexec` over the program, filters over both). +pub struct Sources { + pub list: Vec<Source>, + /// Bytes read so far, at every level (a filter's input and its output both count): the + /// interpreter charges them as work. + pub read: u64, + /// The most bytes that may be read; past it every file is at its end and `exhausted` is set. + pub max_read: u64, + pub exhausted: bool, +} + +impl Default for Sources { + fn default() -> Self { + Sources { list: Vec::new(), read: 0, max_read: u64::MAX, exhausted: false } + } +} + +impl Sources { + pub fn add(&mut self, s: Source) -> usize { + self.list.push(s); + self.list.len() - 1 + } + + pub fn is_subfile_filter(&self, id: usize) -> bool { + self.list.get(id).is_some_and(|source| matches!(&source.kind, Kind::Filter { dec: Dec::SubFile { skip_on_pop: true, .. }, .. })) + } + + pub fn read(&mut self, id: usize) -> Option<u8> { + self.read_depth(id, 0) + } + + fn read_depth(&mut self, id: usize, depth: usize) -> Option<u8> { + if self.read >= self.max_read { + self.exhausted = true; + return None; + } + let c = self.read_inner(id, depth); + if c.is_some() { + self.read += 1; + } + c + } + + fn read_inner(&mut self, id: usize, depth: usize) -> Option<u8> { + if depth > MAX_CHAIN { + return None; + } + let src = self.list.get_mut(id)?; + if src.closed { + return None; + } + if let Some(c) = src.back.pop() { + src.last = Some(c); + return Some(c); + } + let c = match &mut src.kind { + Kind::Bytes(data) => { + let c = data.get(src.pos).copied(); + if c.is_some() { + src.pos += 1; + } + return c; + } + Kind::Shared { buf, off, len } => { + let c = if src.pos < *len { off.checked_add(src.pos).and_then(|i| buf.borrow().get(i).copied()) } else { None }; + if c.is_some() { + src.pos += 1; + } + return c; + } + Kind::Eexec { .. } => self.read_eexec(id, depth), + Kind::Filter { .. } => self.read_filter(id, depth), + }; + if let Some(s) = self.list.get_mut(id) { + s.last = c; + if c.is_some() { + s.pos += 1; + } + } + c + } + + fn read_eexec(&mut self, id: usize, depth: usize) -> Option<u8> { + let Some(Source { kind: Kind::Eexec { up, hex, .. }, .. }) = self.list.get(id) else { return None }; + let (up, hex) = (*up, *hex); + let hex = match hex { + Some(h) => h, + None => { + let h = self.leading_hex(up, depth)?; + if let Some(Source { kind: Kind::Eexec { hex, .. }, .. }) = self.list.get_mut(id) { + *hex = Some(h); + } + h + } + }; + loop { + let cipher = if hex { + let mut digits = [0u8; 2]; + let mut n = 0; + while n < 2 { + let c = self.read_depth(up, depth + 1)?; + if is_ws(c) { + continue; + } + digits[n] = hex_val(c)?; + n += 1; + } + digits[0] << 4 | digits[1] + } else { + self.read_depth(up, depth + 1)? + }; + let Some(Source { kind: Kind::Eexec { r, skipped, .. }, .. }) = self.list.get_mut(id) else { return None }; + let plain = cipher ^ (*r >> 8) as u8; + *r = (u16::from(cipher).wrapping_add(*r)).wrapping_mul(52845).wrapping_add(22719); + // The first four plain bytes are random. + if *skipped < 4 { + *skipped += 1; + continue; + } + return Some(plain); + } + } + + /// Whether the next four bytes after whitespace are hex digits (the whitespace is consumed + /// when they are; the four bytes are pushed back either way). + fn leading_hex(&mut self, up: usize, depth: usize) -> Option<bool> { + let mut skipped = Vec::new(); + let first = loop { + let c = self.read_depth(up, depth + 1)?; + if !is_ws(c) { + break c; + } + skipped.push(c); + }; + let mut four = vec![first]; + while four.len() < 4 { + match self.read_depth(up, depth + 1) { + Some(c) => four.push(c), + None => break, + } + } + let hex = four.len() == 4 && four.iter().all(|c| hex_val(*c).is_some()); + self.unread_many(up, &four); + if !hex { + self.unread_many(up, &skipped); + } + Some(hex) + } + + /// Push bytes back so they are read again, in order. + pub fn unread_many(&mut self, id: usize, bytes: &[u8]) { + let Some(src) = self.list.get_mut(id) else { return }; + match src.kind { + Kind::Bytes(_) | Kind::Shared { .. } if src.back.is_empty() => src.pos = src.pos.saturating_sub(bytes.len()), + _ => src.back.extend(bytes.iter().rev()), + } + } + + /// Step back over the byte just read (the scanner's look-ahead). + pub fn unread(&mut self, id: usize) { + let Some(src) = self.list.get_mut(id) else { return }; + match src.kind { + Kind::Bytes(_) | Kind::Shared { .. } if src.back.is_empty() => src.pos = src.pos.saturating_sub(1), + _ => { + if let Some(c) = src.last { + src.back.push(c); + } + } + } + } + + pub fn peek(&mut self, id: usize) -> Option<u8> { + let c = self.read(id)?; + self.unread(id); + Some(c) + } + + /// Build a decoding source without retaining it, so the interpreter can charge its memory + /// budget before registering the source. + pub fn filter(&mut self, up: usize, name: &[u8], p: &FilterParams, max_owned: usize) -> Result<(Source, usize), String> { + let dec = match name { + b"ASCIIHexDecode" | b"AHx" => Dec::Hex { hi: None }, + b"ASCII85Decode" | b"A85" => Dec::A85 { group: [0; 5], n: 0, first: true }, + b"RunLengthDecode" | b"RL" => Dec::RunLength, + b"LZWDecode" | b"LZW" => { + let dec = if p.early_change { + weezl::decode::Decoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8) + } else { + weezl::decode::Decoder::new(weezl::BitOrder::Msb, 8) + }; + Dec::Lzw { dec: Box::new(dec), pending: Vec::new() } + } + b"FlateDecode" | b"Fl" => { + Dec::Flate { state: miniz_oxide::inflate::stream::InflateState::new_boxed(miniz_oxide::DataFormat::Zlib), pending: Vec::new() } + } + b"DCTDecode" | b"DCT" => Dec::Dct, + b"SubFileDecode" => Dec::SubFile { + eod: p.eod_string.clone(), + count: p.eod_count, + // A byte count; with no count and no end string, everything passes through. + left: (p.eod_string.is_empty() && p.eod_count > 0).then_some(p.eod_count), + skip_on_pop: true, + window: VecDeque::new(), + }, + b"NullEncode" => Dec::SubFile { eod: Vec::new(), count: 0, left: None, skip_on_pop: false, window: VecDeque::new() }, + b"ReusableStreamDecode" => { + // Reads its data when made, and can be read again (`resetfile`, positions). + let mut data = Vec::new(); + while let Some(c) = self.read(up) { + let next = data.len().saturating_add(1); + if next > MAX_DECODED || next > max_owned { + return Err("out of memory".into()); + } + if next > data.capacity() { + let target = next.saturating_add(4095).min(max_owned).min(MAX_DECODED); + data.try_reserve_exact(target.saturating_sub(data.len())).map_err(|_| "out of memory")?; + } + data.push(c); + } + // The capacity is retained by the reusable byte source, so charge it rather + // than only the initialized bytes. + let bytes = data.capacity(); + return Ok((Source::bytes(data), bytes)); + } + _ => return Err(format!("unsupported filter {}", String::from_utf8_lossy(name))), + }; + let mut s = Source::of(Kind::Filter { up, dec, out: VecDeque::new(), done: false, produced: 0 }); + if p.predictor > 1 && matches!(name, b"FlateDecode" | b"Fl" | b"LZWDecode" | b"LZW") { + let colors = usize::try_from(p.colors.clamp(1, 32)).unwrap_or(1); + let bpc = usize::try_from(p.bpc.clamp(1, 16)).unwrap_or(8); + let columns = usize::try_from(p.columns.clamp(1, 1 << 20)).unwrap_or(1); + let row = (colors * bpc * columns).div_ceil(8); + if row > max_owned { + return Err("out of memory".into()); + } + let mut prev = Vec::new(); + prev.try_reserve_exact(row).map_err(|_| "out of memory")?; + prev.resize(row, 0); + s.predictor = Some(Predictor { kind: p.predictor, bpp: (colors * bpc).div_ceil(8).max(1), row, prev, cur: Vec::new() }); + return Ok((s, row)); + } + Ok((s, 0)) + } + + fn read_filter(&mut self, id: usize, depth: usize) -> Option<u8> { + loop { + let src = self.list.get_mut(id)?; + let Kind::Filter { out, done, .. } = &mut src.kind else { return None }; + if let Some(c) = out.pop_front() { + return Some(c); + } + if *done { + return None; + } + if !self.fill(id, depth) + && let Some(Source { kind: Kind::Filter { done, .. }, .. }) = self.list.get_mut(id) + { + // What the last step produced is still read first. + *done = true; + } + } + } + + /// Decode some more of filter `id`; false once its data has ended. + #[allow(clippy::cognitive_complexity, reason = "one streaming decoder state machine preserves filter read-ahead and predictor ordering")] + fn fill(&mut self, id: usize, depth: usize) -> bool { + let Some(Source { kind: Kind::Filter { up, dec, .. }, .. }) = self.list.get(id) else { return false }; + let up = *up; + let mut produced: Vec<u8> = Vec::new(); + let mut more = true; + match dec { + Dec::Dct => more = false, + Dec::Hex { hi } => { + let mut hi = *hi; + while produced.is_empty() { + let Some(c) = self.read_depth(up, depth + 1) else { + more = false; + break; + }; + if c == b'>' { + more = false; + break; + } + let Some(v) = hex_val(c) else { continue }; + match hi.take() { + Some(h) => produced.push(h << 4 | v), + None => hi = Some(v), + } + } + if !more && let Some(h) = hi.take() { + produced.push(h << 4); + } + if let Some(Source { kind: Kind::Filter { dec: Dec::Hex { hi: slot }, .. }, .. }) = self.list.get_mut(id) { + *slot = hi; + } + } + Dec::A85 { group, n, first } => { + let (mut group, mut n, mut first) = (*group, *n, *first); + while produced.is_empty() { + let Some(c) = self.read_depth(up, depth + 1) else { + more = false; + break; + }; + if is_ws(c) { + continue; + } + if c == b'<' && first { + // A leading `<~` is optional; `<` is itself a valid ASCII85 digit. + let next = self.read_depth(up, depth + 1); + if next == Some(b'~') { + first = false; + continue; + } + if next.is_some() { + self.unread(up); + } + } + first = false; + if c == b'~' { + let _ = self.read_depth(up, depth + 1); + more = false; + break; + } + if c == b'z' && n == 0 { + produced.extend([0; 4]); + continue; + } + if !(b'!'..=b'u').contains(&c) { + more = false; + break; + } + if let Some(slot) = group.get_mut(n) { + *slot = c - b'!'; + } + n += 1; + if n == 5 { + let v = group.iter().fold(0u64, |a, &d| a * 85 + u64::from(d)).min(u64::from(u32::MAX)); + produced.extend(u32::try_from(v).unwrap_or(u32::MAX).to_be_bytes()); + n = 0; + } + } + if !more && n > 1 { + for slot in group.iter_mut().skip(n) { + *slot = 84; + } + let v = group.iter().fold(0u64, |a, &d| a * 85 + u64::from(d)).min(u64::from(u32::MAX)); + produced.extend(u32::try_from(v).unwrap_or(u32::MAX).to_be_bytes().iter().take(n - 1)); + n = 0; + } + if let Some(Source { kind: Kind::Filter { dec: Dec::A85 { group: g, n: nn, first: f }, .. }, .. }) = self.list.get_mut(id) { + *g = group; + *nn = n; + *f = first; + } + } + Dec::RunLength => match self.read_depth(up, depth + 1) { + None | Some(128) => more = false, + Some(len @ 0..=127) => { + for _ in 0..=len { + match self.read_depth(up, depth + 1) { + Some(c) => produced.push(c), + None => { + more = false; + break; + } + } + } + } + Some(len) => match self.read_depth(up, depth + 1) { + Some(c) => produced.extend(std::iter::repeat_n(c, 257 - usize::from(len))), + None => more = false, + }, + }, + Dec::SubFile { eod, count, left, window, .. } => { + let (eod, mut count, mut left, mut window) = (eod.clone(), *count, *left, window.clone()); + if let Some(n) = left.as_mut() { + if *n == 0 { + more = false; + } else if let Some(c) = self.read_depth(up, depth + 1) { + *n -= 1; + produced.push(c); + } else { + more = false; + } + } else if eod.is_empty() { + match self.read_depth(up, depth + 1) { + Some(c) => produced.push(c), + None => more = false, + } + } else { + while produced.is_empty() && more { + let Some(c) = self.read_depth(up, depth + 1) else { + produced.extend(window.drain(..)); + more = false; + break; + }; + window.push_back(c); + if window.len() >= eod.len() && window.iter().skip(window.len() - eod.len()).eq(eod.iter()) { + if count == 0 { + let keep = window.len() - eod.len(); + produced.extend(window.drain(..keep)); + window.clear(); + more = false; + break; + } + count -= 1; + if count == 0 { + // Positive EODCount includes the Nth terminating occurrence. + produced.extend(window.drain(..)); + more = false; + break; + } + } + while window.len() > eod.len() { + if let Some(b) = window.pop_front() { + produced.push(b); + } + } + } + } + if let Some(Source { kind: Kind::Filter { dec: Dec::SubFile { count: c, left: l, window: w, .. }, .. }, .. }) = self.list.get_mut(id) + { + *c = count; + *l = left; + *w = window; + } + } + Dec::Flate { .. } | Dec::Lzw { .. } => { + // Feed what is pending, or a chunk from beneath; keep what wasn't used. + let mut input = match self.list.get_mut(id).map(|s| &mut s.kind) { + Some(Kind::Filter { dec: Dec::Flate { pending, .. } | Dec::Lzw { pending, .. }, .. }) => std::mem::take(pending), + _ => Vec::new(), + }; + let mut eof = false; + if input.is_empty() { + while input.len() < 4096 { + match self.read_depth(up, depth + 1) { + Some(c) => input.push(c), + None => { + eof = true; + break; + } + } + } + } + let mut buf = vec![0u8; 64 * 1024]; + let (used, written, finished) = match self.list.get_mut(id).map(|s| &mut s.kind) { + Some(Kind::Filter { dec: Dec::Flate { state, .. }, .. }) => { + let r = miniz_oxide::inflate::stream::inflate(state, &input, &mut buf, miniz_oxide::MZFlush::None); + let finished = matches!(r.status, Ok(miniz_oxide::MZStatus::StreamEnd) | Err(_)); + (r.bytes_consumed, r.bytes_written, finished) + } + Some(Kind::Filter { dec: Dec::Lzw { dec, .. }, .. }) => { + // One byte at a time: the decoder must not read past its end code. + let (mut used, mut written, mut finished) = (0, 0, false); + while used < input.len() && written + 4096 < buf.len() { + let r = dec.decode_bytes(input.get(used..used + 1).unwrap_or(&[]), buf.get_mut(written..).unwrap_or(&mut [])); + used += r.consumed_in; + written += r.consumed_out; + if matches!(r.status, Ok(weezl::LzwStatus::Done) | Err(_)) { + finished = true; + break; + } + if r.consumed_in == 0 && r.consumed_out == 0 { + break; + } + } + (used, written, finished) + } + _ => (0, 0, true), + }; + produced.extend_from_slice(buf.get(..written).unwrap_or(&[])); + let rest = input.get(used..).unwrap_or(&[]).to_vec(); + if finished { + // The stream ended inside this chunk: what follows belongs to the file. + self.unread_many(up, &rest); + more = false; + } else if used == 0 && written == 0 && (eof || input.is_empty()) { + more = false; + } else if let Some(Source { kind: Kind::Filter { dec: Dec::Flate { pending, .. } | Dec::Lzw { pending, .. }, .. }, .. }) = + self.list.get_mut(id) + { + *pending = rest; + } + } + } + // Predictors work on whole rows. + let predicted = match self.list.get_mut(id).and_then(|s| s.predictor.as_mut()) { + Some(pr) => unpredict(pr, &produced, !more), + None => produced, + }; + let Some(Source { kind: Kind::Filter { out, produced: total, .. }, .. }) = self.list.get_mut(id) else { return false }; + *total = total.saturating_add(predicted.len()); + if *total > MAX_DECODED { + return false; + } + out.extend(predicted); + more + } + + /// The JPEG a DCTDecode filter reads: through its end marker when it sits on the program + /// itself, all of the filter beneath otherwise. + pub fn dct(&mut self, id: usize) -> Option<Rc<Vec<u8>>> { + let src = self.list.get(id)?; + if let Some(d) = &src.dct { + return Some(d.clone()); + } + let Kind::Filter { up, dec: Dec::Dct, .. } = &src.kind else { return None }; + let up = *up; + let direct = match self.list.get(up) { + Some(Source { kind: Kind::Bytes(data), pos, back, .. }) if back.is_empty() => Some((data.clone(), *pos)), + _ => None, + }; + let raw = match direct { + Some((data, pos)) => { + let rest = data.get(pos..).unwrap_or(&[]); + let end = jpeg_end(rest).unwrap_or(rest.len()); + if let Some(s) = self.list.get_mut(up) { + s.pos = s.pos.saturating_add(end); + } + rest.get(..end).unwrap_or(&[]).to_vec() + } + None => { + let mut raw = Vec::new(); + while let Some(c) = self.read(up) { + raw.push(c); + if raw.len() > MAX_DECODED { + break; + } + } + raw + } + }; + let raw = Rc::new(raw); + if let Some(s) = self.list.get_mut(id) { + s.dct = Some(raw.clone()); + } + Some(raw) + } + + pub fn is_filter(&self, id: usize) -> bool { + matches!(self.list.get(id).map(|s| &s.kind), Some(Kind::Filter { .. })) + } + + /// Read a filter to its end marker, so the file beneath carries on after the data. + pub fn drain(&mut self, id: usize) { + let mut n = 0usize; + while n < MAX_DECODED && self.read(id).is_some() { + n += 1; + } + } + + pub fn close(&mut self, id: usize) { + if let Some(s) = self.list.get_mut(id) { + s.closed = true; + } + } + + pub fn reset(&mut self, id: usize) { + if let Some(s) = self.list.get_mut(id) + && matches!(s.kind, Kind::Bytes(_) | Kind::Shared { .. }) + { + s.pos = 0; + s.back.clear(); + s.closed = false; + } + } + + pub fn position(&self, id: usize) -> Option<usize> { + let s = self.list.get(id)?; + Some(s.pos.saturating_sub(s.back.len())) + } + + pub fn set_position(&mut self, id: usize, pos: usize) -> bool { + match self.list.get_mut(id) { + Some(s) if matches!(&s.kind, Kind::Bytes(d) if pos <= d.len()) || matches!(&s.kind, Kind::Shared { len, .. } if pos <= *len) => { + s.pos = pos; + s.back.clear(); + s.closed = false; + true + } + _ => false, + } + } + + pub fn available(&self, id: usize) -> i64 { + match self.list.get(id) { + Some(s) if s.closed => -1, + Some(Source { kind: Kind::Bytes(d), pos, back, .. }) => i64::try_from(d.len().saturating_sub(*pos) + back.len()).unwrap_or(i64::MAX), + Some(Source { kind: Kind::Shared { len, .. }, pos, back, .. }) => { + i64::try_from(len.saturating_sub(*pos) + back.len()).unwrap_or(i64::MAX) + } + Some(_) => 1, + None => -1, + } + } +} + +/// Undo a predictor on newly decoded bytes (`last`: no more will come). +fn unpredict(p: &mut Predictor, data: &[u8], last: bool) -> Vec<u8> { + let mut out = Vec::new(); + if p.kind == 2 { + // TIFF: 8-bit horizontal differencing. + for &b in data { + p.cur.push(b); + if p.cur.len() == p.row { + for i in p.bpp..p.row { + let prev = p.cur.get(i - p.bpp).copied().unwrap_or(0); + if let Some(c) = p.cur.get_mut(i) { + *c = c.wrapping_add(prev); + } + } + out.append(&mut p.cur); + } + } + if last { + out.append(&mut p.cur); + } + return out; + } + // PNG: a filter byte before each row. + for &b in data { + p.cur.push(b); + if p.cur.len() == p.row + 1 { + let kind = p.cur.first().copied().unwrap_or(0); + let mut row: Vec<u8> = p.cur.get(1..).unwrap_or(&[]).to_vec(); + for i in 0..row.len() { + let a = if i >= p.bpp { row.get(i - p.bpp).copied().unwrap_or(0) } else { 0 }; + let up = p.prev.get(i).copied().unwrap_or(0); + let c = if i >= p.bpp { p.prev.get(i - p.bpp).copied().unwrap_or(0) } else { 0 }; + let add = match kind { + 1 => a, + 2 => up, + 3 => ((u16::from(a) + u16::from(up)) / 2) as u8, + 4 => { + let pp = i16::from(a) + i16::from(up) - i16::from(c); + let (pa, pb, pc) = ((pp - i16::from(a)).abs(), (pp - i16::from(up)).abs(), (pp - i16::from(c)).abs()); + if pa <= pb && pa <= pc { + a + } else if pb <= pc { + up + } else { + c + } + } + _ => 0, + }; + if let Some(v) = row.get_mut(i) { + *v = v.wrapping_add(add); + } + } + out.extend_from_slice(&row); + p.prev = row; + p.cur.clear(); + } + } + out +} + +/// The length of the JPEG at the start of `d` (through its EOI marker). +fn jpeg_end(d: &[u8]) -> Option<usize> { + if d.get(..2)? != [0xFF, 0xD8] { + return None; + } + let mut i = 2; + loop { + while d.get(i)? == &0xFF && d.get(i + 1)? == &0xFF { + i += 1; + } + if d.get(i)? != &0xFF { + return None; + } + let m = *d.get(i + 1)?; + i += 2; + match m { + 0xD9 => return Some(i), + 0x01 | 0xD0..=0xD7 => continue, + _ => { + let len = usize::from(u16::from_be_bytes([*d.get(i)?, *d.get(i + 1)?])); + i = i.checked_add(len)?; + if m == 0xDA { + // Entropy-coded data: up to the next marker that isn't a stuffed byte or restart. + loop { + if d.get(i)? == &0xFF { + let n = *d.get(i + 1)?; + if n != 0 && !(0xD0..=0xD7).contains(&n) { + break; + } + i += 2; + } else { + i += 1; + } + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn all(s: &mut Sources, id: usize) -> Vec<u8> { + let mut out = Vec::new(); + while let Some(c) = s.read(id) { + out.push(c); + } + out + } + + fn add_filter(s: &mut Sources, up: usize, name: &[u8], params: &FilterParams) -> usize { + let (source, _) = s.filter(up, name, params, usize::MAX).unwrap(); + s.add(source) + } + + #[test] + fn filter_owned_buffers_are_preflighted_against_memory_budget() { + let mut sources = Sources::default(); + let id = sources.add(Source::bytes(Vec::new())); + let predictor = FilterParams { predictor: 12, colors: 32, bpc: 16, columns: 1 << 20, ..Default::default() }; + assert!(matches!(sources.filter(id, b"FlateDecode", &predictor, 4096), Err(e) if e == "out of memory")); + + let id = sources.add(Source::bytes(vec![b'x'; 10])); + assert!(matches!(sources.filter(id, b"ReusableStreamDecode", &FilterParams::default(), 9), Err(e) if e == "out of memory")); + let id = sources.add(Source::bytes(vec![b'x'; 10])); + let (_, owned) = sources.filter(id, b"ReusableStreamDecode", &FilterParams::default(), 10).unwrap(); + assert_eq!(owned, 10); + } + + #[test] + fn filters_stop_at_their_end_markers() { + let mut s = Sources::default(); + let id = s.add(Source::bytes(b"48656c6c6f>rest".to_vec())); + let f = add_filter(&mut s, id, b"ASCIIHexDecode", &FilterParams::default()); + assert_eq!(all(&mut s, f), b"Hello"); + assert_eq!(all(&mut s, id), b"rest"); + let id = s.add(Source::bytes(b"87cURD]i,\"Ebo80~>rest".to_vec())); + let f = add_filter(&mut s, id, b"ASCII85Decode", &FilterParams::default()); + assert_eq!(all(&mut s, f), b"Hello World!"); + assert_eq!(all(&mut s, id), b"rest"); + let id = s.add(Source::bytes(b"<!!!!~>rest".to_vec())); + let f = add_filter(&mut s, id, b"ASCII85Decode", &FilterParams::default()); + let value = 27u32 * 85u32.pow(4); + assert_eq!(all(&mut s, f), value.to_be_bytes()); + assert_eq!(all(&mut s, id), b"rest"); + let id = s.add(Source::bytes(vec![2, b'a', b'b', b'c', 254, b'x', 128, b'!'])); + let f = add_filter(&mut s, id, b"RunLengthDecode", &FilterParams::default()); + assert_eq!(all(&mut s, f), b"abcxxx"); + assert_eq!(all(&mut s, id), b"!"); + let id = s.add(Source::bytes(b"data%%EndBinary tail".to_vec())); + let p = FilterParams { eod_string: b"%%EndBinary".to_vec(), ..Default::default() }; + let f = add_filter(&mut s, id, b"SubFileDecode", &p); + assert_eq!(all(&mut s, f), b"data"); + assert_eq!(all(&mut s, id), b" tail"); + let id = s.add(Source::bytes(b"aENDtailENDrest".to_vec())); + let p = FilterParams { eod_count: 1, eod_string: b"END".to_vec(), ..Default::default() }; + let f = add_filter(&mut s, id, b"SubFileDecode", &p); + assert_eq!(all(&mut s, f), b"aEND"); + assert_eq!(all(&mut s, id), b"tailENDrest"); + } + + fn ascii85(data: &[u8]) -> String { + let mut out = String::new(); + for chunk in data.chunks(4) { + let mut b = [0u8; 4]; + b[..chunk.len()].copy_from_slice(chunk); + let mut v = u32::from_be_bytes(b); + let mut digits = [0u8; 5]; + for d in digits.iter_mut().rev() { + *d = (v % 85) as u8 + b'!'; + v /= 85; + } + out.push_str(std::str::from_utf8(&digits[..chunk.len() + 1]).unwrap()); + } + out + } + + #[test] + fn flate_and_lzw_read_only_their_streams() { + let mut z = miniz_oxide::deflate::compress_to_vec_zlib(&b"abcabcabc".repeat(2000), 6); + z.extend_from_slice(b"tail"); + let mut s = Sources::default(); + let id = s.add(Source::bytes(z)); + let f = add_filter(&mut s, id, b"FlateDecode", &FilterParams::default()); + assert_eq!(all(&mut s, f), b"abcabcabc".repeat(2000)); + assert_eq!(all(&mut s, id), b"tail"); + // Flate over ASCII85 over the program: bytes pushed back return to the filter beneath. + let z = miniz_oxide::deflate::compress_to_vec_zlib(b"xyz", 6); + let mut s = Sources::default(); + let id = s.add(Source::bytes(format!("{}~> after", ascii85(&z)).into_bytes())); + let a = add_filter(&mut s, id, b"ASCII85Decode", &FilterParams::default()); + let f = add_filter(&mut s, a, b"FlateDecode", &FilterParams::default()); + assert_eq!(all(&mut s, f), b"xyz"); + assert_eq!(all(&mut s, id), b" after"); + let mut enc = weezl::encode::Encoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8); + let mut l = enc.encode(b"lzw lzw lzw").unwrap(); + l.extend_from_slice(b"!"); + let mut s = Sources::default(); + let id = s.add(Source::bytes(l)); + let f = add_filter(&mut s, id, b"LZWDecode", &FilterParams { early_change: true, ..Default::default() }); + assert_eq!(all(&mut s, f), b"lzw lzw lzw"); + assert_eq!(all(&mut s, id), b"!"); + } + + #[test] + fn eexec_decrypts_binary_and_hex() { + let encrypt = |plain: &[u8]| { + let mut r: u16 = 55665; + let mut out = Vec::new(); + for &p in [0u8, 0, 0, 0].iter().chain(plain) { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + out.push(c); + } + out + }; + let enc = encrypt(b"hello"); + for hex in [false, true] { + let data = if hex { enc.iter().map(|b| format!("{b:02x}")).collect::<String>().into_bytes() } else { enc.clone() }; + let mut s = Sources::default(); + let up = s.add(Source::bytes(data)); + let e = s.add(Source::eexec(up)); + assert_eq!(s.peek(e), Some(b'h'), "look-ahead inside the section"); + let got: Vec<u8> = (0..5).filter_map(|_| s.read(e)).collect(); + assert_eq!(got, b"hello", "hex {hex}"); + } + } + + #[test] + fn broken_filter_data_ends_the_filter_not_the_program() { + for (name, data) in [ + (&b"ASCIIHexDecode"[..], &b"zz>"[..]), + (b"ASCII85Decode", b"\x7f~>"), + (b"FlateDecode", b"\x78\x9c\xff\xff"), + (b"RunLengthDecode", b"\x05a"), + (b"LZWDecode", b"\xff\xff\xff"), + ] { + let mut s = Sources::default(); + let id = s.add(Source::bytes(data.to_vec())); + let f = add_filter(&mut s, id, name, &FilterParams::default()); + let _ = all(&mut s, f); + } + let mut s = Sources::default(); + let id = s.add(Source::bytes(b"\xff\xd8\xff".to_vec())); + let f = add_filter(&mut s, id, b"DCTDecode", &FilterParams::default()); + assert!(s.dct(f).is_some()); + } +} diff --git a/crates/ps/src/read/tests.rs b/crates/ps/src/read/tests.rs new file mode 100644 index 000000000..152041659 --- /dev/null +++ b/crates/ps/src/read/tests.rs @@ -0,0 +1,755 @@ +//! End-to-end: EPS programs in, PDF content out. + +use super::*; + +/// The page content stream of a converted EPS, inflated. +fn content(pdf: &[u8]) -> String { + // The content stream is object 4, written right after the page. + let at = pdf.windows(7).position(|w| w == b"4 0 obj").expect("content object"); + let rest = &pdf[at..]; + let s = rest.windows(6).position(|w| w == b"stream").unwrap() + 6; + let s = s + if rest[s] == b'\r' { 2 } else { 1 }; + let e = rest.windows(9).position(|w| w == b"endstream").unwrap(); + let raw = miniz_oxide::inflate::decompress_to_vec_zlib(&rest[s..e]) + .unwrap_or_else(|_| miniz_oxide::inflate::decompress_to_vec_zlib(&rest[s..e - 1]).unwrap()); + String::from_utf8_lossy(&raw).into_owned() +} + +fn eps(body: &str) -> Vec<u8> { + format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 110 70\n%%EndComments\n{body}\n%%EOF\n").into_bytes() +} + +fn run(body: &str) -> (String, Converted) { + let c = eps_to_pdf(&eps(body), Limits::default()).unwrap(); + (content(&c.pdf), c) +} + +#[test] +fn eps_sections_and_deferred_bounding_boxes_use_craft_eps() { + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%HiResBoundingBox: (atend)\n%%BoundingBox: (atend)\n%%EndComments\n%%Trailer\n%%BoundingBox: 0 0 100 50\n%%HiResBoundingBox: 0.5 1.5 90.5 40.5\n"; + let wrapped = craft_eps::wrap(ps, Some(b"tiff"), None).unwrap(); + assert!(is_eps(&wrapped)); + assert_eq!(postscript_section(&wrapped), ps); + assert_eq!(bounding_box(ps), Some([0.5, 1.5, 90.5, 40.5])); +} + +#[test] +fn bounding_box_keeps_the_historical_256k_header_scan() { + let mut ps = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); + ps.resize(ps.len() + (70 << 10), b' '); + ps.extend_from_slice(b"\n%%BoundingBox: 0 0 20 10\n%%EndComments\n"); + assert_eq!(craft_eps::Comments::read(&ps).page_box(), None); + assert_eq!(bounding_box(&ps), Some([0.0, 0.0, 20.0, 10.0])); +} + +#[test] +fn damaged_dos_preview_does_not_hide_the_executable_postscript() { + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n%%EndComments\n0 0 10 10 rectfill\n"; + let mut wrapped = craft_eps::wrap(ps, Some(b"tiff"), None).unwrap(); + wrapped[20..24].copy_from_slice(&u32::MAX.to_le_bytes()); + wrapped[24..28].copy_from_slice(&1u32.to_le_bytes()); + assert_eq!(postscript_section(&wrapped), ps); + assert!(craft_eps::sections(&wrapped).is_err()); + assert!(eps_to_pdf(&wrapped, Limits::default()).is_ok()); +} + +#[test] +fn paths_fill_and_stroke_in_their_colours() { + let (c, conv) = run("0 0 1 0 setcmykcolor 10 20 50 30 rectfill 1 0 0 setrgbcolor 2 setlinewidth newpath 10 20 moveto 100 60 lineto stroke"); + assert_eq!(conv.bbox, [10.0, 20.0, 110.0, 70.0]); + // The bounding box's corner moves to the page origin. + assert!(c.starts_with("1 0 0 1 -10 -20 cm"), "{c}"); + assert!(c.contains("0 0 1 0 k"), "CMYK stays CMYK: {c}"); + assert!(c.contains("10 20 m") && c.contains("f"), "{c}"); + assert!(c.contains("1 0 0 RG") && c.contains("2 w") && c.contains("S"), "{c}"); +} + +#[test] +fn procedures_loops_and_dictionaries_run() { + let (c, _) = run("/sq { newpath moveto 10 0 rlineto 0 10 rlineto -10 0 rlineto closepath fill } bind def + 0 1 2 { 15 mul 10 add 30 sq } for + /d 3 dict def d /n 7 put d /n get 7 eq { 0.5 setgray 60 20 5 5 rectfill } if + { 1 0 div } stopped { 0.25 setgray 70 20 5 5 rectfill } if + [ 1 2 3 ] { pop } forall 3 { } repeat 0 { 1 add dup 4 ge { exit } if } loop pop"); + assert_eq!(c.lines().filter(|l| *l == "f").count(), 5, "{c}"); + assert!(c.contains("0.5 g") && c.contains("0.25 g"), "{c}"); +} + +#[test] +fn integer_division_overflow_returns_zero() { + let (c, _) = run("-9223372036854775808 -1 idiv 0 eq { 10 20 5 5 rectfill } if + -9223372036854775808 -1 mod 0 eq { 20 20 5 5 rectfill } if"); + assert_eq!(c.lines().filter(|line| *line == "f").count(), 2, "{c}"); +} + +#[test] +fn copy_past_operand_limit_is_a_noop() { + let body = format!("10 20 5 5 rectfill {} 60000 copy 20 20 5 5 rectfill", "0 ".repeat(60_000)); + let compatible = eps_to_pdf(&eps(&body), Limits { stack_overflow_noop: true, ..Limits::default() }).unwrap(); + let compatible_content = content(&compatible.pdf); + assert_eq!(compatible_content.lines().filter(|line| *line == "f").count(), 2, "{compatible_content}"); + + let strict = eps_to_pdf(&eps(&body), Limits { keep_unpainted: true, ..Limits::default() }).unwrap(); + assert!(strict.warnings.iter().any(|warning| warning.contains("stackoverflow")), "{:?}", strict.warnings); + assert_eq!(content(&strict.pdf).lines().filter(|line| *line == "f").count(), 1); +} + +#[test] +fn transforms_curves_and_clips() { + let (c, _) = run("gsave 60 45 translate 2 2 scale newpath 0 0 10 0 360 arc clip newpath -20 -20 40 40 rectfill grestore 10 20 5 5 rectfill"); + assert!(c.contains(" c"), "arcs become curves: {c}"); + assert!(c.contains("W") && c.contains("q") && c.contains("Q"), "clip in its own q: {c}"); + // The circle is centred at (60, 45) with radius 20 in device space. + assert!(c.contains("80 45 m"), "{c}"); +} + +#[test] +fn huge_arc_checks_temporary_and_retained_memory_before_building_curves() { + let limits = Limits { memory: 4096, keep_unpainted: true, ..Limits::default() }; + let converted = eps_to_pdf(&eps("10 20 5 5 rectfill newpath 0 0 1e16 0 360 arc"), limits).unwrap(); + assert!(converted.warnings.iter().any(|warning| warning == "out of memory"), "{:?}", converted.warnings); + assert_eq!(content(&converted.pdf).lines().filter(|line| *line == "f").count(), 1); +} + +#[test] +fn separation_colours_use_their_tint_transform() { + let (c, _) = run("[/Separation (Spot) /DeviceCMYK { dup 0 exch 0 } ] setcolorspace 0.5 setcolor 10 20 10 10 rectfill"); + assert!(c.contains("0.5 0 0.5 0 k") || c.contains(".5 0 .5 0 k"), "{c}"); +} + +#[test] +fn images_and_masks_become_xobjects() { + let (c, conv) = run("gsave 10 20 translate 20 10 scale 2 1 8 [2 0 0 -1 0 1] <00ff> image grestore + gsave 40 20 translate 10 10 scale 0 0 1 setrgbcolor 8 1 true [8 0 0 -1 0 1] <f0> imagemask grestore + gsave 60 20 translate 10 10 scale 1 1 8 [1 0 0 -1 0 1] currentfile /ASCIIHexDecode filter false 3 colorimage +ff8000> +grestore"); + assert_eq!(c.matches("Do").count(), 3, "{c}"); + let pdf = String::from_utf8_lossy(&conv.pdf); + assert!(pdf.contains("/ImageMask true") && pdf.contains("/DeviceRGB") && pdf.contains("/DeviceGray"), "{pdf}"); +} + +#[test] +fn type3_fonts_draw_their_glyphs() { + let (c, _) = run("/T3 8 dict dup begin /FontType 3 def /FontMatrix [0.001 0 0 0.001 0 0] def /FontBBox [0 0 1000 1000] def + /Encoding 256 array def 0 1 255 { Encoding exch /.notdef put } for Encoding 65 /A put + /BuildChar { pop pop 600 0 0 0 500 500 setcachedevice 0 0 500 500 rectfill } def end def + /T3 T3 definefont pop /T3 findfont 20 scalefont setfont 10 20 moveto (AA) show"); + // Two glyphs, the second 12 points (600 units at 20 pt) to the right. + assert_eq!(c.lines().filter(|l| *l == "f").count(), 2, "{c}"); + assert!(c.contains("22 20 m"), "{c}"); +} + +#[test] +fn type3_glyph_paints_after_prior_outline_glyphs() { + let ttf = tiny_ttf(); + let sfnts: String = ttf.chunks(64).map(|c| format!("<{}>\n", c.iter().map(|b| format!("{b:02x}")).collect::<String>())).collect(); + let (c, _) = run(&format!( + "/T42 11 dict dup begin /FontType 42 def /FontMatrix [0.001 0 0 0.001 0 0] def /PaintType 0 def /FontBBox [0 0 1 1] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /CharStrings 2 dict dup /.notdef 0 put dup /A 1 put def /sfnts [ {sfnts} ] def end /T42 exch definefont pop + /T3 8 dict dup begin /FontType 3 def /FontMatrix [0.001 0 0 0.001 0 0] def /FontBBox [0 0 1000 700] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /BuildChar {{ pop pop 1000 0 0 0 1000 700 setcachedevice 1 setgray 0 0 1000 700 rectfill }} def end /T3 exch definefont pop + /T0 6 dict dup begin /FontType 0 def /FMapType 2 def /FontMatrix [1 0 0 1 0 0] def + /FDepVector [ /T42 findfont /T3 findfont ] def end /T0 exch definefont pop + /T0 findfont 20 scalefont setfont 10 10 moveto <00410141> show" + )); + let lines: Vec<&str> = c.lines().collect(); + let first_fill = lines.iter().position(|line| *line == "f").unwrap_or_else(|| panic!("outline fill missing: {c}")); + let white_paint = lines.iter().position(|line| *line == "1 g").unwrap_or_else(|| panic!("Type 3 white paint missing: {c}")); + let second_fill = lines + .iter() + .enumerate() + .skip(white_paint + 1) + .find(|(_, line)| **line == "f") + .map(|(index, _)| index) + .unwrap_or_else(|| panic!("Type 3 fill missing: {c}")); + assert!(first_fill < white_paint && white_paint < second_fill, "glyph paints are out of order: {c}"); +} + +#[test] +fn type3_measurement_suppresses_nested_outline_painting() { + let ttf = tiny_ttf(); + let sfnts: String = ttf.chunks(64).map(|c| format!("<{}>\n", c.iter().map(|b| format!("{b:02x}")).collect::<String>())).collect(); + let (c, _) = run(&format!( + "/T42 11 dict dup begin /FontType 42 def /FontMatrix [0.001 0 0 0.001 0 0] def /PaintType 0 def /FontBBox [0 0 1 1] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /CharStrings 2 dict dup /.notdef 0 put dup /A 1 put def /sfnts [ {sfnts} ] def end /T42 exch definefont pop + /T3 8 dict dup begin /FontType 3 def /FontMatrix [0.001 0 0 0.001 0 0] def /FontBBox [0 0 1000 700] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /BuildChar {{ pop pop 1000 0 0 0 1000 700 setcachedevice /T42 findfont 20 scalefont setfont 10 10 moveto (A) show }} def end /T3 exch definefont pop + /T3 findfont 20 scalefont setfont (A) stringwidth pop pop 0 0 10 10 rectfill" + )); + assert_eq!(c.lines().filter(|line| *line == "f").count(), 1, "measurement painted nested outline text: {c}"); +} + +#[test] +fn a_string_made_a_file_runs_as_a_program() { + // Adobe's idiom: `(code) 0 () /SubFileDecode filter cvx exec`. + let (c, _) = run("(0.5 setgray 10 20 5 5 rectfill) 0 () /SubFileDecode filter cvx exec"); + assert!(c.contains("0.5 g"), "{c}"); +} + +#[test] +fn subfiledecode_exec_reads_the_following_program_lazily() { + let (c, converted) = run("currentfile 0 () /SubFileDecode filter exec\n0 0 10 10 rectfill"); + assert!(converted.warnings.is_empty(), "{:?}", converted.warnings); + assert_eq!(c.lines().filter(|line| *line == "f").count(), 1, "{c}"); +} + +#[test] +fn discarded_subfiledecode_skips_payload_without_materializing_it() { + let payload = "x".repeat(8192); + let bytes = eps(&format!("0 0 10 10 rectfill currentfile 0 (END) /SubFileDecode filter pop\n{payload}END")); + let limits = Limits { memory: 4096, ..Limits::default() }; + let converted = eps_to_pdf(&bytes, limits).unwrap(); + assert!(!converted.warnings.iter().any(|warning| warning == "out of memory"), "{:?}", converted.warnings); + assert!(converted.memory <= limits.memory, "{} bytes", converted.memory); + let c = content(&converted.pdf); + assert!(c.contains("0 0 m") && c.contains("10 10 l"), "{c}"); +} + +#[test] +fn pop_does_not_drain_a_subfiledecode_stream_with_another_reference() { + let (c, converted) = run("currentfile 0 () /SubFileDecode filter 1 copy pop exec\n1 0 0 setrgbcolor 0 0 10 10 rectfill"); + assert!(converted.warnings.is_empty(), "{:?}", converted.warnings); + assert!(c.contains("1 0 0 rg") && c.contains("0 0 m") && c.contains("10 10 l"), "{c}"); +} + +#[test] +fn predictor_and_reusable_stream_buffers_are_charged_before_retention() { + let limits = Limits { memory: 4096, keep_unpainted: true, ..Limits::default() }; + let predictor = eps_to_pdf( + &eps("10 20 1 1 rectfill () << /Predictor 12 /Colors 32 /BitsPerComponent 16 /Columns 1048576 >> /FlateDecode filter pop"), + limits, + ) + .unwrap(); + assert!(predictor.warnings.iter().any(|warning| warning == "out of memory"), "{:?}", predictor.warnings); + assert!(predictor.memory <= limits.memory, "{} bytes", predictor.memory); + + let payload = "x".repeat(2500); + let reusable = eps_to_pdf(&eps(&format!("10 20 1 1 rectfill ({payload}) /ReusableStreamDecode filter pop")), limits).unwrap(); + assert!(reusable.warnings.iter().any(|warning| warning == "out of memory"), "{:?}", reusable.warnings); +} + +#[test] +fn empty_filter_source_records_are_charged_to_the_memory_limit() { + let limits = Limits { memory: 4096, keep_unpainted: true, ..Limits::default() }; + let converted = eps_to_pdf(&eps("10 20 1 1 rectfill 100000 { () 0 () /SubFileDecode filter pop } repeat"), limits).unwrap(); + assert!(converted.warnings.iter().any(|warning| warning == "out of memory"), "{:?}", converted.warnings); + assert!(converted.memory > limits.memory, "{} bytes", converted.memory); + assert!(converted.steps < limits.steps, "the test hit the work limit first: {} steps", converted.steps); +} + +#[test] +fn eexec_sections_run() { + // `(1 0 0 setrgbcolor 10 20 5 5 rectfill) ` encrypted with the eexec key, as hex. + let plain = b"1 0 0 setrgbcolor 10 20 5 5 rectfill currentfile closefile\n"; + let mut r: u16 = 55665; + let mut hex = String::new(); + for &p in [1u8, 2, 3, 4].iter().chain(plain.iter()) { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + hex.push_str(&format!("{c:02x}")); + } + let (c, _) = run(&format!("currentfile eexec\n{hex}\n0 1 0 setrgbcolor 20 20 5 5 rectfill")); + assert!(c.contains("1 0 0 rg") && c.contains("0 1 0 rg"), "the program carries on after the section: {c}"); +} + +#[test] +fn completed_embedded_type1_fonts_get_a_fid_when_registered() { + let plain = b"pop currentfile closefile\n"; + let mut r: u16 = 55665; + let mut hex = String::new(); + for &p in [1u8, 2, 3, 4].iter().chain(plain.iter()) { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + hex.push_str(&format!("{c:02x}")); + } + let body = format!( + "/T 6 dict dup begin /FontName /T def /FontType 1 def /FontMatrix [0.001 0 0 0.001 0 0] def /Private 1 dict def end def + T begin currentfile eexec\n{hex}\nT end + T /FID known {{ 1 0 0 setrgbcolor 10 20 5 5 rectfill }} if" + ); + let (content, _) = run(&body); + assert!(content.contains("1 0 0 rg"), "the recovered font has a FID: {content}"); +} + +#[test] +fn repeated_eexec_font_searches_charge_the_operand_stack_work() { + let plain = b"pop end currentfile closefile\n"; + let mut r: u16 = 55665; + let mut hex = String::new(); + for &p in [1u8, 2, 3, 4].iter().chain(plain.iter()) { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + hex.push_str(&format!("{c:02x}")); + } + let mut body = format!( + "/T 6 dict dup begin /FontName /T def /FontType 1 def /FontMatrix [0.001 0 0 0.001 0 0] def /Private 1 dict def end def\nT begin {} ", + "0 ".repeat(4096) + ); + for _ in 0..16 { + body.push_str(&format!("currentfile eexec\n{hex}\n")); + } + let limits = Limits { steps: 20_000, keep_unpainted: true, ..Limits::default() }; + let converted = eps_to_pdf(&eps(&body), limits).expect("bounded recovery keeps completed output"); + assert!(converted.warnings.iter().any(|warning| warning == "the program runs too long"), "{:?}", converted.warnings); + assert!(converted.steps >= limits.steps, "stack search work was not charged: {}", converted.steps); +} + +#[test] +fn hostile_programs_end_with_an_error_not_a_hang_or_panic() { + let limits = Limits { + steps: 200_000, + memory: 64 << 20, + stack_overflow_noop: false, + skip_images: false, + keep_unpainted: false, + zero_division_zero: false, + fallback_font: None, + }; + for body in [ + "{ } loop", + "/f { f } def f", + "/f { 1 f } def f", + "{ 1 } loop", + "1000000000 array", + "0 1 1e9 { pop } for", + "[ 1 2", + "/x 10 dict def x begin x begin", + "100000 { gsave } repeat", + "{ { { { { { stop } exec } exec } exec } exec } exec } loop", + "(unterminated", + "1 0 idiv", + "mark { 0 0 moveto } 1000000 { dup exec } repeat", + "currentfile 100000000 string readstring", + "/A85 currentfile /ASCII85Decode filter def ~>", + "0 0 moveto 1 1 1e300 1e300 0 0 curveto stroke", + "[1e300 0 0 1e300 0 0] concat 0 0 1 1 rectfill", + ] { + let _ = eps_to_pdf(&eps(body), limits); + } + // Nothing painted and an error: no PDF, so the caller keeps the preview. + assert!(eps_to_pdf(&eps("1 0 div"), limits).is_err()); + assert!(eps_to_pdf(b"%!PS-Adobe-3.0 EPSF-3.0\n0 0 1 1 rectfill\n", limits).is_err(), "no bounding box"); + assert!(eps_to_pdf(b"not postscript", limits).is_err()); +} + +#[test] +fn mutually_bound_executable_names_stop_at_a_bounded_depth() { + let err = eps_to_pdf(&eps("/n /m cvx def /m /n cvx def n"), Limits::default()).unwrap_err(); + assert_eq!(err, "executable name resolution limit"); +} + +#[test] +fn a_file_in_a_name_is_data_until_executed() { + // cairo keeps its image filter in a name and calls `status` and `flushfile` on it. + let (c, _) = run("/f (0.5 setgray 10 20 5 5 rectfill) 0 () /SubFileDecode filter def f status pop f cvx exec"); + assert!(c.contains("0.5 g"), "{c}"); +} + +#[test] +fn smooth_shadings_become_pdf_shadings() { + let (c, conv) = run("<< /ShadingType 2 /ColorSpace /DeviceCMYK /Coords [10 20 110 20] /Extend [true true] + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0 0] /C1 [0 0 1 0] /N 1 >> >> shfill + << /ShadingType 3 /ColorSpace [/Separation (Gold) /DeviceCMYK { dup 0.2 mul exch 0 exch 0 } ] + /Coords [60 45 0 60 45 20] /Function { } >> shfill"); + assert_eq!(c.matches(" sh").count(), 2, "{c}"); + let pdf = String::from_utf8_lossy(&conv.pdf); + assert!(pdf.contains("/ShadingType 2") && pdf.contains("/ShadingType 3"), "{pdf}"); + // CMYK and a spot made of CMYK stay CMYK. + assert_eq!(pdf.matches("/ColorSpace /DeviceCMYK").count(), 2, "{pdf}"); +} + +#[test] +fn shading_patterns_fill_their_path() { + let (c, _) = run("<< /PatternType 2 /Shading << /ShadingType 2 /ColorSpace /DeviceRGB /Coords [0 0 100 0] + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> >> matrix makepattern + setpattern 10 20 50 30 rectfill"); + assert!(c.contains("W") && c.contains(" sh"), "clipped to the rectangle, then shaded: {c}"); +} + +#[test] +fn mesh_shadings_keep_their_vertices() { + // Two free-form triangles from an array, the second sharing an edge (flag 1). + let (_, conv) = run("<< /ShadingType 4 /ColorSpace /DeviceRGB + /DataSource [0 10 20 1 0 0 0 110 20 0 1 0 0 60 70 0 0 1 1 110 70 1 1 0] >> shfill + << /ShadingType 6 /ColorSpace /DeviceGray /DataSource [0 10 20 10 30 10 40 10 50 20 50 30 50 40 50 50 50 50 40 50 30 50 20 40 20 30 20 20 20 0 0.3 0.6 1] >> shfill"); + let pdf = String::from_utf8_lossy(&conv.pdf); + assert!(pdf.contains("/ShadingType 4") && pdf.contains("/ShadingType 6"), "{pdf}"); + // Malformed meshes draw what they hold, or nothing. + for bad in [ + "<< /ShadingType 4 /ColorSpace /DeviceRGB /DataSource [0 1] >> shfill", + "<< /ShadingType 7 /ColorSpace /DeviceGray /DataSource (abc) /BitsPerCoordinate 32 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [0 1 0 1 0 1] >> shfill 0 0 1 1 rectfill", + ] { + let _ = eps_to_pdf(&eps(bad), Limits::default()); + } +} + +/// A two-glyph TrueType font: .notdef (empty) and a 500 × 700 box at x 50, 600 wide, in +/// 1000 units to the em. +fn tiny_ttf() -> Vec<u8> { + let be16 = |v: i32| (v as i16 as u16).to_be_bytes(); + // The box: one contour of four on-curve points, coordinates as 16-bit deltas. + let mut glyph = Vec::new(); + for v in [1, 50, 0, 550, 700, 3] { + glyph.extend(be16(v)); + } + glyph.extend([0, 0]); // no instructions + glyph.extend([1, 1, 1, 1]); // on-curve, long coordinates + for dx in [50, 500, 0, -500] { + glyph.extend(be16(dx)); + } + for dy in [0, 0, 700, 0] { + glyph.extend(be16(dy)); + } + let mut head = Vec::new(); + head.extend(0x0001_0000u32.to_be_bytes()); + head.extend(0x0001_0000u32.to_be_bytes()); + head.extend(0u32.to_be_bytes()); + head.extend(0x5F0F_3CF5u32.to_be_bytes()); + head.extend(be16(0)); + head.extend(be16(1000)); + head.extend([0; 16]); + for v in [0, 0, 600, 700, 0, 8, 2, 0, 0] { + head.extend(be16(v)); + } + let mut hhea = 0x0001_0000u32.to_be_bytes().to_vec(); + for v in [800, -200, 0, 600, 0, 0, 550, 1, 0, 0, 0, 0, 0, 0, 0, 2] { + hhea.extend(be16(v)); + } + let mut maxp = 0x0000_5000u32.to_be_bytes().to_vec(); + maxp.extend(be16(2)); + let mut hmtx = Vec::new(); + for v in [500, 0, 600, 50] { + hmtx.extend(be16(v)); + } + let mut loca = Vec::new(); + for v in [0, 0, glyph.len() as i32 / 2] { + loca.extend(be16(v)); + } + let tables: [(&[u8; 4], Vec<u8>); 6] = [(b"glyf", glyph), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)]; + let mut out = 0x0001_0000u32.to_be_bytes().to_vec(); + out.extend(be16(tables.len() as i32)); + out.extend([0; 6]); + let mut at = 12 + 16 * tables.len(); + let mut body = Vec::new(); + for (tag, data) in &tables { + out.extend(*tag); + out.extend(0u32.to_be_bytes()); + out.extend((at as u32).to_be_bytes()); + out.extend((data.len() as u32).to_be_bytes()); + let mut d = data.clone(); + d.resize(data.len().div_ceil(4) * 4, 0); + at += d.len(); + body.extend(d); + } + out.extend(body); + out +} + +fn fallback_tiny_ttf(_: &[u8]) -> Option<&'static [u8]> { + static FONT: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new(); + Some(FONT.get_or_init(tiny_ttf).as_slice()) +} + +#[test] +fn fallback_font_bytes_are_charged_before_copying() { + let limits = Limits { memory: 256, fallback_font: Some(fallback_tiny_ttf), ..Limits::default() }; + let error = eps_to_pdf(&eps("/Missing findfont pop"), limits).unwrap_err(); + assert_eq!(error, "out of memory"); +} + +#[test] +fn actual_text_uses_the_selected_encoding_and_omits_unknown_names() { + let (content, _) = run("/F /Helvetica findfont def F /Encoding get 65 /B put F 10 scalefont setfont 10 20 moveto (A) show"); + assert!(content.contains("/ActualText (B)"), "{content}"); + + let (content, _) = run("/F /Helvetica findfont def F /Encoding get 65 /customGlyph put F 10 scalefont setfont 10 20 moveto (A) show"); + assert!(!content.contains("/ActualText"), "{content}"); +} + +#[test] +fn text_paint_keeps_completed_glyphs_when_a_later_glyph_hits_the_work_limit() { + let ttf = tiny_ttf(); + let sfnts: String = ttf.chunks(64).map(|c| format!("<{}>\n", c.iter().map(|b| format!("{b:02x}")).collect::<String>())).collect(); + let body = format!( + "/T42 11 dict dup begin /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /PaintType 0 def /FontBBox [0 0 1 1] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /CharStrings 2 dict dup /.notdef 0 put dup /A 1 put def /sfnts [ {sfnts} ] def end definefont + 20 scalefont setfont 10 20 moveto (AA) show" + ); + let bytes = eps(&body); + let complete = eps_to_pdf(&bytes, Limits::default()).unwrap(); + let mut found_prefix = false; + for steps in (complete.steps.saturating_sub(100))..complete.steps { + let limits = Limits { steps, keep_unpainted: true, ..Limits::default() }; + let Ok(converted) = eps_to_pdf(&bytes, limits) else { continue }; + if converted.warnings.iter().any(|warning| warning == "the program runs too long") { + let content = content(&converted.pdf); + if content.lines().filter(|line| *line == "f").count() == 1 { + found_prefix = true; + break; + } + } + } + assert!(found_prefix, "no partial PDF retained the first completed glyph"); +} + +#[test] +fn type42_fonts_draw_their_truetype_glyphs() { + let ttf = tiny_ttf(); + // sfnts strings split at an even length below the string limit. + let sfnts: String = ttf.chunks(64).map(|c| format!("<{}>\n", c.iter().map(|b| format!("{b:02x}")).collect::<String>())).collect(); + let (c, _) = run(&format!( + "/T42 11 dict dup begin /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /PaintType 0 def /FontBBox [0 0 1 1] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /CharStrings 2 dict dup /.notdef 0 put dup /A 1 put def /sfnts [ {sfnts} ] def end definefont + 20 scalefont setfont 10 20 moveto (AA) show" + )); + // Each glyph is filled independently; 1 point (50 units at 20 pt) in, the second 12 points on. + assert_eq!(c.lines().filter(|l| *l == "f").count(), 2, "{c}"); + assert_eq!(c.lines().filter(|l| *l == "EMC").count(), 1, "{c}"); + assert!(c.contains("11 20 m") && c.contains("23 20 m"), "{c}"); +} + +/// A CFF INDEX of `items` (4-byte offsets). +fn cff_index(items: &[Vec<u8>]) -> Vec<u8> { + let mut out = (items.len() as u16).to_be_bytes().to_vec(); + if items.is_empty() { + return out; + } + out.push(4); + let mut off = 1u32; + out.extend(off.to_be_bytes()); + for it in items { + off += it.len() as u32; + out.extend(off.to_be_bytes()); + } + for it in items { + out.extend(it); + } + out +} + +/// A DICT integer operand in its five-byte form (so offsets don't change the length). +fn cff_int(v: i32) -> Vec<u8> { + [vec![29], v.to_be_bytes().to_vec()].concat() +} + +/// A one-glyph CFF font set: glyph 1 is a 500 × 700 box, 600 wide. CID-keyed fonts give it CID 5. +fn tiny_cff(cid: bool) -> Vec<u8> { + let n = |v: i32| vec![(v + 139) as u8]; + let box_glyph = + [n(-100), n(50), n(0), vec![21], vec![247, 136], n(0), vec![5], n(0), vec![248, 80], vec![5], vec![251, 136], n(0), vec![5], vec![14]] + .concat(); + // 600 = width as the first (odd) operand: nominalWidthX 700 → −100. + let charstrings = cff_index(&[vec![14], box_glyph]); + let charset = if cid { vec![0, 0, 5] } else { vec![0, 0, 34] }; + let private = [cff_int(700), vec![21]].concat(); + let strings = cff_index(&[b"Adobe".to_vec(), b"Identity".to_vec()]); + let head = vec![1, 0, 4, 4]; + let names = cff_index(&[b"T".to_vec()]); + // Lay out: header, names, top dict, strings, gsubrs, charset, charstrings, private, [fdarray, fdselect]. + let top_len = |extra: usize| 1 + 2 + 4 + 4 + (5 + 1) * 2 + (5 + 5 + 1) + extra; + let extra = if cid { 5 + 5 + 5 + 2 + 5 + 2 + 5 + 2 + 5 + 2 } else { 0 }; + let top_index_len = 2 + 1 + 8 + (top_len(extra) - 11); + let mut at = head.len() + names.len() + top_index_len + strings.len() + 2; + let charset_at = at; + at += charset.len(); + let cs_at = at; + at += charstrings.len(); + let priv_at = at; + at += private.len(); + let fd_private = private.clone(); + let fd_dict = [cff_int(fd_private.len() as i32), cff_int(priv_at as i32), vec![18]].concat(); + let fdarray = cff_index(&[fd_dict]); + let fdarray_at = at; + at += fdarray.len(); + let fdselect_at = at; + let fdselect = vec![0, 0, 0]; + let mut top = + [cff_int(charset_at as i32), vec![15], cff_int(cs_at as i32), vec![17], cff_int(private.len() as i32), cff_int(priv_at as i32), vec![18]] + .concat(); + if cid { + top = [ + cff_int(391), + cff_int(392), + cff_int(0), + vec![12, 30], + cff_int(6), + vec![12, 34], + cff_int(fdarray_at as i32), + vec![12, 36], + cff_int(fdselect_at as i32), + vec![12, 37], + top, + ] + .concat(); + } + let tops = cff_index(&[top]); + let mut out = [head, names, tops, strings, vec![0, 0]].concat(); + assert_eq!(out.len(), charset_at, "layout"); + out.extend(charset); + out.extend(charstrings); + out.extend(private); + if cid { + out.extend(fdarray); + out.extend(fdselect); + } + out +} + +fn startdata_eps(cff: &[u8], body: &str) -> Vec<u8> { + let mut v = + format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 110 70\n/FontSetInit /ProcSet findresource begin\n/T {} StartData ", cff.len()) + .into_bytes(); + v.extend_from_slice(cff); + v.extend_from_slice(format!("\n{body}\n%%EOF\n").as_bytes()); + v +} + +#[test] +fn cff_fonts_from_startdata_draw_their_glyphs() { + let c = content( + &eps_to_pdf(&startdata_eps(&tiny_cff(false), "/T findfont 10 scalefont setfont 10 20 moveto (AA) show"), Limits::default()).unwrap().pdf, + ); + assert_eq!(c.lines().filter(|l| *l == "f").count(), 2, "{c}"); + assert_eq!(c.lines().filter(|l| *l == "EMC").count(), 1, "{c}"); + // The box starts 0.5 points (50 units) in; the second glyph 6 points (600 units) on. + assert!(c.contains("10.5 20 m") && c.contains("16.5 20 m"), "{c}"); +} + +#[test] +fn cid_fonts_draw_through_cmaps() { + let body = "/T-Identity-H findfont 10 scalefont setfont 10 20 moveto <00050005> show + /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /One-H def + 1 begincodespacerange <00> <ff> endcodespacerange 1 begincidchar <41> 5 endcidchar + endcmap CMapName currentdict /CMap defineresource pop end end + /U /One-H [/T] composefont pop /U findfont 10 scalefont setfont 10 40 moveto (AA) show"; + let c = content(&eps_to_pdf(&startdata_eps(&tiny_cff(true), body), Limits::default()).unwrap().pdf); + assert_eq!(c.lines().filter(|l| *l == "f").count(), 4, "{c}"); + assert_eq!(c.lines().filter(|l| *l == "EMC").count(), 0, "{c}"); + assert!(c.contains("16.5 20 m") && c.contains("16.5 40 m"), "{c}"); + // Broken font data is a warning, not a failure. + let r = eps_to_pdf(&startdata_eps(b"\x01\x00\x04\x04\xff\xff\xff", "0 0 1 1 rectfill"), Limits::default()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("CFF")), "{:?}", r.warnings); +} + +#[test] +fn tiling_patterns_become_pdf_patterns() { + let (c, conv) = run("<< /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 + /PaintProc { pop 1 0 0 setrgbcolor 0 0 5 5 rectfill } >> matrix makepattern setpattern + 10 20 50 30 rectfill + << /PatternType 1 /PaintType 2 /TilingType 1 /BBox [0 0 4 4] /XStep 4 /YStep 4 + /PaintProc { pop 1 0 0 setrgbcolor 0 0 2 4 rectfill } >> matrix makepattern /S exch def + [/Pattern /DeviceCMYK] setcolorspace 0 1 0 0 S setcolor 60 20 40 30 rectfill"); + assert!(c.contains("/Pattern cs") && c.contains("/P0 scn") && c.contains("/P1 scn"), "{c}"); + let pdf = String::from_utf8_lossy(&conv.pdf); + assert!(pdf.contains("/PatternType 1") && pdf.contains("/XStep 10"), "{pdf}"); + // A cell that fails or nests too deeply ends cleanly. + for bad in [ + "<< /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 1 1] /XStep 0 /YStep 1 /PaintProc { pop } >> matrix makepattern setpattern 0 0 1 1 rectfill", + "/P << /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 1 1] /XStep 1 /YStep 1 /PaintProc { pop P setpattern 0 0 1 1 rectfill } >> matrix makepattern def P setpattern 0 0 1 1 rectfill", + "<< /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 1 1] /XStep 1 /YStep 1 /PaintProc { 1 0 div } >> matrix makepattern setpattern 0 0 1 1 rectfill", + ] { + let _ = eps_to_pdf(&eps(bad), Limits::default()); + } +} + +#[test] +fn strokepath_outlines_the_stroke() { + // A 4-point butt-capped line from (10,20) to (60,20): its outline is the band y 18–22. + let (c, _) = run("newpath 10 30 moveto 60 30 lineto 4 setlinewidth strokepath 0 setgray fill"); + assert!(c.lines().any(|l| l == "f"), "{c}"); + assert!(!c.contains(" S\n") && !c.lines().any(|l| l == "S"), "filled, not stroked: {c}"); + for y in ["28", "32"] { + assert!(c.contains(&format!(" {y} l")) || c.contains(&format!(" {y} m")), "edge at y={y}: {c}"); + } + // Dashes split it; a path through a degenerate matrix ends empty; a clip to a stroke works. + let (c, _) = run("newpath 10 30 moveto 110 30 lineto 2 setlinewidth [10 10] 0 setdash strokepath fill"); + assert!(c.matches(" m").count() >= 5, "five dashes: {c}"); + let _ = run("[0 0 0 0 0 0] concat newpath 0 0 moveto 1 1 lineto strokepath fill"); + let (c, _) = run("newpath 10 30 moveto 100 30 lineto 10 setlinewidth strokepath clip newpath 10 20 100 50 rectfill"); + assert!(c.contains("W"), "{c}"); +} + +#[test] +fn vertical_cid_text_runs_down_from_its_vertical_origin() { + let body = "/T-Identity-V findfont 10 scalefont setfont 10 40 moveto <00050005> show"; + let c = content(&eps_to_pdf(&startdata_eps(&tiny_cff(true), body), Limits::default()).unwrap().pdf); + // v = (300, 880) units: the glyph's origin is 3 left and 8.8 below the point; the second + // glyph is one em (10) lower. The box starts 0.5 in from its origin. + assert!(c.contains("7.5 31.2 m") && c.contains("7.5 21.2 m"), "{c}"); + // A CMap program can make a font vertical too. + let body = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /V1 def /WMode 1 def + 1 begincodespacerange <00> <ff> endcodespacerange 1 begincidchar <41> 5 endcidchar + endcmap CMapName currentdict /CMap defineresource pop end end + /U /V1 [/T] composefont pop /U findfont 10 scalefont setfont 10 40 moveto (AA) show"; + let c = content(&eps_to_pdf(&startdata_eps(&tiny_cff(true), body), Limits::default()).unwrap().pdf); + assert!(c.contains("7.5 31.2 m") && c.contains("7.5 21.2 m"), "{c}"); +} + +#[test] +fn a_tiny_dash_on_a_long_path_draws_solid() { + let body = "newpath 0 30 moveto 100000 30 lineto [0.0001] 0 setdash"; + let (c, _) = run(&format!("{body} stroke")); + assert!(!c.contains(" d\n") && !c.contains("] 0 d"), "{c}"); + let (c, _) = run(&format!("{body} strokepath fill")); + assert!(c.matches(" m").count() < 10, "{}", &c[..c.len().min(300)]); +} + +#[test] +fn metrics_without_two_numbers_dont_underflow() { + // `[/a /b]` has two elements but no numbers: the width index used to go below zero. + let (c, _) = run("/Helvetica findfont dup length 1 add dict copy dup /Metrics << /A [/a /b] /B [7] >> put + /H exch definefont 10 scalefont setfont 10 20 moveto (AB) show 10 20 1 1 rectfill"); + assert!(c.contains("re") || c.contains(" m"), "{c}"); +} + +#[test] +fn work_in_proportion_to_operands_counts_against_the_limits() { + let limits = Limits { + steps: 200_000, + memory: 8 << 20, + stack_overflow_noop: false, + skip_images: false, + keep_unpainted: false, + zero_division_zero: false, + fallback_font: None, + }; + let ends = |body: &str| { + let r = eps_to_pdf(&eps(&format!("10 20 1 1 rectfill {body}")), limits).expect("what was painted is kept"); + let w = r.warnings.join(" "); + assert!(w.contains("too long") || w.contains("memory") || w.contains("too much data"), "{body}: {w}"); + // It stops at the charge that crosses the limit: overshoot is one operand's worth at most. + assert!(r.steps <= limits.steps + 1_000_000 || r.memory > limits.memory, "{body}: {} steps", r.steps); + }; + // Each would take seconds to minutes in a few steps without its charge. + ends("/h 1000000 string def /n 500 string def { h n search pop pop } loop"); + ends("100000 { 0 } repeat { 100000 copy 100000 { pop } repeat } loop"); + ends("/a 4000000 string def /b 4000000 string def { a b eq pop } loop"); + ends("newpath 0 0 moveto 100000 { 1 0 rlineto } repeat { gsave grestore } loop"); + ends("{ 4000000 string pop } loop"); + ends("/d 100000 dict def 0 1 99999 { d exch 0 put } for { d { pop pop } forall } loop"); + ends("/Helvetica findfont 10 scalefont setfont /s 1000000 string def { 0 0 moveto s show } loop"); + ends("mark 100000 { 0 } repeat { counttomark pop } loop"); + // Reading counts: a stream decoded over and over. + let z = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 1 << 20], 9); + let hex: String = z.iter().map(|b| format!("{b:02x}")).collect(); + ends(&format!("/z <{hex}> def {{ z /FlateDecode filter dup 2000000 string readstring pop pop closefile }} loop")); + // Tiny programs that only loop still end at the step limit. + ends("{ } loop"); +} + +#[test] +fn the_web_gets_smaller_default_limits() { + let l = Limits::default(); + if cfg!(target_arch = "wasm32") { + assert!(l.memory <= 256 << 20 && l.steps <= 20_000_000); + } else { + assert!(l.memory <= 1 << 30 && l.steps <= 50_000_000); + } +} diff --git a/crates/ps/src/read/type1.rs b/crates/ps/src/read/type1.rs new file mode 100644 index 000000000..7ea3476e2 --- /dev/null +++ b/crates/ps/src/read/type1.rs @@ -0,0 +1,357 @@ +//! Type 1 glyphs: charstrings decrypted and run into outlines (Adobe Type 1 Font Format). + +use crate::read::gstate::Seg; +use crate::read::obj::{Key, Obj, PDict, name}; + +/// A glyph outline in glyph space and its advance. +#[derive(Debug, Clone, Default)] +pub struct Glyph { + pub path: Vec<Seg>, + pub width: (f64, f64), + /// The work making it took (charstring operators run, or outline points). + pub cost: usize, +} + +/// The most charstring operators run for one glyph (subroutines included). +const MAX_OPS: usize = 100_000; +const MAX_CALL_DEPTH: usize = 12; + +pub fn decrypt(data: &[u8], skip: usize) -> Vec<u8> { + let mut r: u16 = 4330; + let mut out = Vec::with_capacity(data.len()); + for &c in data { + out.push(c ^ (r >> 8) as u8); + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + } + out.into_iter().skip(skip).collect() +} + +fn string_bytes(o: &Obj) -> Option<Vec<u8>> { + match o { + Obj::Str(s, _) => Some(s.bytes()), + _ => None, + } +} + +struct Font { + charstrings: PDict, + subrs: Vec<Vec<u8>>, + len_iv: i64, +} + +impl Font { + fn of(font: &PDict) -> Option<Font> { + let Some(Obj::Dict(charstrings)) = font.get_name(b"CharStrings") else { return None }; + let private = match font.get_name(b"Private") { + Some(Obj::Dict(p)) => Some(p), + _ => None, + }; + let len_iv = private.as_ref().and_then(|p| p.get_name(b"lenIV")).and_then(|o| o.num()).unwrap_or(4.0) as i64; + let subrs = match private.as_ref().and_then(|p| p.get_name(b"Subrs")) { + Some(Obj::Array(a, _)) => a.items().iter().map(|o| string_bytes(o).unwrap_or_default()).collect(), + _ => Vec::new(), + }; + Some(Font { charstrings, subrs, len_iv }) + } + + fn plain(&self, data: &[u8]) -> Vec<u8> { + if self.len_iv < 0 { data.to_vec() } else { decrypt(data, usize::try_from(self.len_iv).unwrap_or(4)) } + } + + fn charstring(&self, glyph: &[u8]) -> Option<Vec<u8>> { + let o = self.charstrings.get(&Key::Name(name(glyph))).or_else(|| self.charstrings.get(&Key::Name(name(b".notdef"))))?; + string_bytes(&o).map(|d| self.plain(&d)) + } +} + +#[derive(Default)] +struct Run { + path: Vec<Seg>, + x: f64, + y: f64, + open: bool, + width: (f64, f64), + sb: (f64, f64), + stack: Vec<f64>, + ps: Vec<f64>, + flex: Option<Vec<(f64, f64)>>, + ops: usize, + done: bool, +} + +impl Run { + fn move_to(&mut self, x: f64, y: f64) { + self.x = x; + self.y = y; + if let Some(pts) = self.flex.as_mut() { + pts.push((x, y)); + return; + } + if self.open { + self.path.push(Seg::Close); + } + self.path.push(Seg::Move(x, y)); + self.open = true; + } + + fn line_to(&mut self, x: f64, y: f64) { + if !self.open { + self.path.push(Seg::Move(self.x, self.y)); + self.open = true; + } + self.x = x; + self.y = y; + self.path.push(Seg::Line(x, y)); + } + + fn curve_to(&mut self, a: (f64, f64), b: (f64, f64), c: (f64, f64)) { + if !self.open { + self.path.push(Seg::Move(self.x, self.y)); + self.open = true; + } + self.x = c.0; + self.y = c.1; + self.path.push(Seg::Curve(a.0, a.1, b.0, b.1, c.0, c.1)); + } + + fn close(&mut self) { + if self.open { + self.path.push(Seg::Close); + self.open = false; + } + } +} + +fn exec(font: &Font, code: &[u8], run: &mut Run, depth: usize, std_glyph: &dyn Fn(usize) -> Option<Vec<u8>>) -> Option<()> { + if depth > MAX_CALL_DEPTH { + return None; + } + let mut i = 0; + while i < code.len() && !run.done { + run.ops += 1; + if run.ops > MAX_OPS || run.stack.len() > 64 { + return None; + } + let v = *code.get(i)?; + i += 1; + if v >= 32 { + let n = match v { + 32..=246 => f64::from(v) - 139.0, + 247..=250 => { + let w = *code.get(i)?; + i += 1; + (f64::from(v) - 247.0) * 256.0 + f64::from(w) + 108.0 + } + 251..=254 => { + let w = *code.get(i)?; + i += 1; + -(f64::from(v) - 251.0) * 256.0 - f64::from(w) - 108.0 + } + _ => { + let b: [u8; 4] = code.get(i..i + 4)?.try_into().ok()?; + i += 4; + f64::from(i32::from_be_bytes(b)) + } + }; + run.stack.push(n); + continue; + } + let s = std::mem::take(&mut run.stack); + let a = |k: usize| s.get(k).copied().unwrap_or(0.0); + match v { + // hstem, vstem: hints only. + 1 | 3 => {} + 4 => run.move_to(run.x, run.y + a(0)), + 5 => run.line_to(run.x + a(0), run.y + a(1)), + 6 => run.line_to(run.x + a(0), run.y), + 7 => run.line_to(run.x, run.y + a(0)), + 8 => { + let p1 = (run.x + a(0), run.y + a(1)); + let p2 = (p1.0 + a(2), p1.1 + a(3)); + let p3 = (p2.0 + a(4), p2.1 + a(5)); + run.curve_to(p1, p2, p3); + } + 9 => run.close(), + 10 => { + let n = usize::try_from(a(s.len().saturating_sub(1)) as i64).ok()?; + // Arguments below the subroutine number stay for it. + run.stack = s.get(..s.len().saturating_sub(1)).map(<[f64]>::to_vec).unwrap_or_default(); + let sub = font.subrs.get(n)?; + let plain = font.plain(sub); + exec(font, &plain, run, depth + 1, std_glyph)?; + continue; + } + 11 => { + run.stack = s; + return Some(()); + } + 12 => { + let e = *code.get(i)?; + i += 1; + match e { + // dotsection, vstem3, hstem3: hints. + 0..=2 => {} + 6 => { + // seac: an accented character from two StandardEncoding glyphs. + let (asb, adx, ady, bchar, achar) = (a(0), a(1), a(2), a(3) as usize, a(4) as usize); + let base = font.charstring(&std_glyph(bchar)?)?; + let accent = font.charstring(&std_glyph(achar)?)?; + let mut b = Run::default(); + exec(font, &base, &mut b, depth + 1, std_glyph)?; + let mut acc = Run::default(); + exec(font, &accent, &mut acc, depth + 1, std_glyph)?; + let (dx, dy) = (adx - asb + run.sb.0, ady); + run.path.extend(b.path); + run.path.extend(acc.path.iter().map(|s| s.map(&crate::read::gstate::M([1.0, 0.0, 0.0, 1.0, dx, dy])))); + run.done = true; + } + 7 => { + run.sb = (a(0), a(1)); + run.width = (a(2), a(3)); + run.x = a(0); + run.y = a(1); + } + 12 => { + let n = s.len(); + let d = a(n.saturating_sub(1)); + let q = if d != 0.0 { a(n.saturating_sub(2)) / d } else { 0.0 }; + run.stack = s.get(..n.saturating_sub(2)).map(<[f64]>::to_vec).unwrap_or_default(); + run.stack.push(q); + continue; + } + 16 => { + // callothersubr: flex (0–2) and hint replacement (3) are done here. + let n = s.len(); + let other = a(n.saturating_sub(1)) as i64; + let argc = usize::try_from(a(n.saturating_sub(2)) as i64).unwrap_or(0).min(n.saturating_sub(2)); + let args: Vec<f64> = s.get(n.saturating_sub(2) - argc..n.saturating_sub(2)).map(<[f64]>::to_vec).unwrap_or_default(); + run.stack = s.get(..n.saturating_sub(2) - argc).map(<[f64]>::to_vec).unwrap_or_default(); + match other { + 1 => run.flex = Some(Vec::new()), + 2 => {} + 0 => { + let pts = run.flex.take().unwrap_or_default(); + if let (Some(&p1), Some(&p2), Some(&p3), Some(&p4), Some(&p5), Some(&p6)) = + (pts.get(1), pts.get(2), pts.get(3), pts.get(4), pts.get(5), pts.get(6)) + { + run.curve_to(p1, p2, p3); + run.curve_to(p4, p5, p6); + } + // The end point for `pop pop setcurrentpoint`. + run.ps = vec![run.y, run.x]; + } + _ => { + // Hint replacement and others: their arguments come back. + run.ps = args.into_iter().rev().collect(); + } + } + continue; + } + 17 => { + let v = run.ps.pop().unwrap_or(0.0); + run.stack = s; + run.stack.push(v); + continue; + } + 33 => { + run.x = a(0); + run.y = a(1); + } + _ => {} + } + } + 13 => { + run.sb = (a(0), 0.0); + run.width = (a(1), 0.0); + run.x = a(0); + run.y = 0.0; + } + 14 => { + run.close(); + run.done = true; + } + 21 => run.move_to(run.x + a(0), run.y + a(1)), + 22 => run.move_to(run.x + a(0), run.y), + 30 => { + let p1 = (run.x, run.y + a(0)); + let p2 = (p1.0 + a(1), p1.1 + a(2)); + let p3 = (p2.0 + a(3), p2.1); + run.curve_to(p1, p2, p3); + } + 31 => { + let p1 = (run.x + a(0), run.y); + let p2 = (p1.0 + a(1), p1.1 + a(2)); + let p3 = (p2.0, p2.1 + a(3)); + run.curve_to(p1, p2, p3); + } + _ => {} + } + } + Some(()) +} + +/// The outline and advance of `glyph` in a Type 1 font dictionary, None when it has none. +pub fn glyph(font: &PDict, glyph: &[u8], std_names: &[&str]) -> Option<Glyph> { + let f = Font::of(font)?; + let code = f.charstring(glyph)?; + let mut run = Run::default(); + let std_glyph = |i: usize| std_names.get(i).map(|n| n.as_bytes().to_vec()); + exec(&f, &code, &mut run, 0, &std_glyph)?; + run.close(); + Some(Glyph { cost: run.ops + run.path.len(), path: run.path, width: run.width }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::read::obj::{PArr, PStr}; + + fn encrypt(plain: &[u8]) -> Vec<u8> { + let mut r: u16 = 4330; + let mut out = Vec::new(); + for &p in [0u8; 4].iter().chain(plain) { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + out.push(c); + } + out + } + + fn num(v: i32) -> Vec<u8> { + match v { + -107..=107 => vec![(v + 139) as u8], + 108..=1131 => { + let v = v - 108; + vec![(v / 256 + 247) as u8, (v % 256) as u8] + } + -1131..=-108 => { + let v = -v - 108; + vec![(v / 256 + 251) as u8, (v % 256) as u8] + } + _ => [vec![255], v.to_be_bytes().to_vec()].concat(), + } + } + + #[test] + fn a_square_glyph_and_its_width() { + // 50 600 hsbw; 0 0 rmoveto... : a 500 × 700 box through a subroutine. + let sub = [num(500), vec![6], num(700), vec![7], vec![11]].concat(); + let cs = [num(50), num(600), vec![13], num(0), num(0), vec![21], num(0), vec![10], num(-500), vec![6], vec![9], vec![14]].concat(); + let font = PDict::new(4); + let chars = PDict::new(2); + chars.put_name(b"A", Obj::Str(PStr::new(encrypt(&cs)), false)); + font.put_name(b"CharStrings", Obj::Dict(chars)); + let private = PDict::new(2); + private.put_name(b"Subrs", Obj::Array(PArr::new(vec![Obj::Str(PStr::new(encrypt(&sub)), false)]), false)); + font.put_name(b"Private", Obj::Dict(private)); + let g = glyph(&font, b"A", &[]).unwrap(); + assert_eq!(g.width, (600.0, 0.0)); + assert_eq!(g.path.first(), Some(&Seg::Move(50.0, 0.0))); + assert!(g.path.contains(&Seg::Line(550.0, 700.0)), "{:?}", g.path); + // Garbage doesn't panic or loop. + let chars = PDict::new(1); + chars.put_name(b"B", Obj::Str(PStr::new(encrypt(&[10, 10, 10, 255, 255])), false)); + font.put_name(b"CharStrings", Obj::Dict(chars)); + let _ = glyph(&font, b"B", &[]); + } +} diff --git a/crates/ps/src/read/type42.rs b/crates/ps/src/read/type42.rs new file mode 100644 index 000000000..0b2bf7fbf --- /dev/null +++ b/crates/ps/src/read/type42.rs @@ -0,0 +1,81 @@ +//! Type 42 fonts: a TrueType font in the `sfnts` strings, glyphs found through CharStrings +//! (glyph name → glyph index), drawn in em units (Adobe Technical Note 5012). + +use skrifa::instance::{LocationRef, Size}; +use skrifa::outline::{DrawSettings, OutlinePen}; +use skrifa::raw::TableProvider; +use skrifa::{GlyphId, MetadataProvider}; + +use crate::read::gstate::Seg; +use crate::read::obj::{Key, Obj, PDict, name}; +use crate::read::type1::Glyph; + +/// The TrueType data of a Type 42 font: its `sfnts` strings joined (an odd string's last byte +/// is padding). +pub fn sfnts(font: &PDict) -> Option<Vec<u8>> { + let Some(Obj::Array(a, _)) = font.get_name(b"sfnts") else { return None }; + let mut out = Vec::new(); + for s in a.items() { + let Obj::Str(s, _) = s else { return None }; + let mut b = s.bytes(); + if b.len() % 2 == 1 { + b.pop(); + } + out.extend_from_slice(&b); + } + Some(out) +} + +struct Pen { + path: Vec<Seg>, + scale: f64, + cur: (f64, f64), +} + +impl OutlinePen for Pen { + fn move_to(&mut self, x: f32, y: f32) { + let p = (f64::from(x) * self.scale, f64::from(y) * self.scale); + self.path.push(Seg::Move(p.0, p.1)); + self.cur = p; + } + fn line_to(&mut self, x: f32, y: f32) { + let p = (f64::from(x) * self.scale, f64::from(y) * self.scale); + self.path.push(Seg::Line(p.0, p.1)); + self.cur = p; + } + fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) { + // A quadratic as the cubic with the same shape. + let (c, p) = ((f64::from(cx) * self.scale, f64::from(cy) * self.scale), (f64::from(x) * self.scale, f64::from(y) * self.scale)); + let a = (self.cur.0 + 2.0 / 3.0 * (c.0 - self.cur.0), self.cur.1 + 2.0 / 3.0 * (c.1 - self.cur.1)); + let b = (p.0 + 2.0 / 3.0 * (c.0 - p.0), p.1 + 2.0 / 3.0 * (c.1 - p.1)); + self.path.push(Seg::Curve(a.0, a.1, b.0, b.1, p.0, p.1)); + self.cur = p; + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + let s = self.scale; + let p = (f64::from(x) * s, f64::from(y) * s); + self.path.push(Seg::Curve(f64::from(x1) * s, f64::from(y1) * s, f64::from(x2) * s, f64::from(y2) * s, p.0, p.1)); + self.cur = p; + } + fn close(&mut self) { + self.path.push(Seg::Close); + } +} + +/// The glyph index for a glyph name (CharStrings maps names to indices). +pub fn glyph_index(font: &PDict, glyph: &[u8]) -> u32 { + let Some(Obj::Dict(cs)) = font.get_name(b"CharStrings") else { return 0 }; + cs.get(&Key::Name(name(glyph))).and_then(|o| o.num()).and_then(|v| u32::try_from(v as i64).ok()).unwrap_or(0) +} + +/// Glyph `gid` of TrueType `data` in em units, with its advance. +pub fn glyph(data: &[u8], gid: u32) -> Option<Glyph> { + let f = skrifa::FontRef::new(data).ok()?; + let upem = f64::from(f.head().ok()?.units_per_em()).max(1.0); + let mut pen = Pen { path: Vec::new(), scale: 1.0 / upem, cur: (0.0, 0.0) }; + if let Some(g) = f.outline_glyphs().get(GlyphId::new(gid)) { + let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), LocationRef::default()), &mut pen); + } + let adv = f.glyph_metrics(Size::unscaled(), LocationRef::default()).advance_width(GlyphId::new(gid)).map_or(0.0, f64::from) / upem; + Some(Glyph { cost: pen.path.len() * 4 + 16, path: pen.path, width: (adv, 0.0) }) +} diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index d684525a8..b41936a04 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -10,6 +10,43 @@ use crate::error::{PsdError, Result}; use crate::header::{Version, row_bytes}; use crate::io::Reader; +/// An incremental zlib encoder for PSD/PSB channel streams. +/// +/// PhotoCraft can encode very large channels a band at a time without keeping the compressed +/// stream's full input or output beside the pixels. `take_output` drains bytes produced so far; +/// call [`finish`](Self::finish) once all channel data has been written. +pub struct ZlibEncoder { + inner: flate2::write::ZlibEncoder<Vec<u8>>, +} + +impl ZlibEncoder { + /// Starts a zlib stream using the PSD writer's default compression level. + pub fn new() -> ZlibEncoder { + ZlibEncoder { inner: flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()) } + } + + /// Adds decoded or predicted channel bytes to the stream. + pub fn write_all(&mut self, bytes: &[u8]) -> Result<()> { + self.inner.write_all(bytes).map_err(|error| PsdError::Invalid(format!("zlib: {error}"))) + } + + /// Takes the compressed bytes produced so far, leaving the stream ready for more input. + pub fn take_output(&mut self) -> Vec<u8> { + std::mem::take(self.inner.get_mut()) + } + + /// Finishes the zlib stream and returns its remaining compressed bytes. + pub fn finish(self) -> Result<Vec<u8>> { + self.inner.finish().map_err(|error| PsdError::Invalid(format!("zlib: {error}"))) + } +} + +impl Default for ZlibEncoder { + fn default() -> Self { + Self::new() + } +} + /// Maximum number of decoded bytes a single decode call may produce: 8 GiB on /// 64-bit targets, 2 GiB elsewhere. /// diff --git a/crates/psd/src/compression/tests.rs b/crates/psd/src/compression/tests.rs index 9f8c61664..6e0d86a7e 100644 --- a/crates/psd/src/compression/tests.rs +++ b/crates/psd/src/compression/tests.rs @@ -1,5 +1,21 @@ use super::*; +#[test] +fn incremental_zlib_encoder_roundtrips_across_drains() { + let expected = (0usize..32_768).map(|n| (n.wrapping_mul(37) % 251) as u8).collect::<Vec<_>>(); + let mut encoder = ZlibEncoder::new(); + let mut encoded = Vec::new(); + for chunk in expected.chunks(997) { + encoder.write_all(chunk).unwrap(); + encoded.extend(encoder.take_output()); + } + encoded.extend(encoder.finish().unwrap()); + + let mut decoded = Vec::new(); + flate2::read::ZlibDecoder::new(encoded.as_slice()).read_to_end(&mut decoded).unwrap(); + assert_eq!(decoded, expected); +} + /// The straightforward index-based versions, kept as the oracle for the /// register-carried rewrites in [`predict`] and [`unpredict`]. mod reference { diff --git a/crates/psd/src/io.rs b/crates/psd/src/io.rs index d8aa4b51d..8ca8353b9 100644 --- a/crates/psd/src/io.rs +++ b/crates/psd/src/io.rs @@ -440,6 +440,18 @@ pub(crate) fn write_unicode_units(out: &mut Vec<u8>, units: &[u16]) { #[cfg(test)] mod tests { + /// A section length that does not fit the file's 32-bit field is refused, not truncated: + /// this is what keeps every `as u32` on a length inside a serialized file from ever wrapping, + /// and it is why an over-large PSD fails the write instead of producing a short length. + #[test] + fn a_length_that_does_not_fit_32_bits_is_refused() { + let mut out = Vec::new(); + assert!(out.put_len(u64::from(u32::MAX), false).is_ok(), "the largest 32-bit length fits"); + assert!(matches!(out.put_len(u64::from(u32::MAX) + 1, false), Err(PsdError::LimitExceeded(_)))); + // A PSB length field is 64 bits, so the same value is written there. + assert!(out.put_len(u64::from(u32::MAX) + 1, true).is_ok(), "PSB has room for it"); + } + use super::*; #[test] diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index a8f778ccd..a2195bf5d 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -470,6 +470,55 @@ fn linked_file(item: &[u8], at: usize) -> Result<LinkedFile> { Ok(out) } +/// Header of an embedded (`liFD`) linked-layer item, without reading its payload. +/// Offsets are relative to the item (not its enclosing eight-byte length field). +/// A deferred reader can supply just the header, then validate the payload range +/// against the full record length before reading those bytes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EmbeddedFileHeader { + /// Lossy UTF-8 identifier, matching Photoshop metadata display semantics. + pub uuid: String, + /// Lossy UTF-16 filename with trailing NULs removed. + pub name: String, + /// Start of the payload within the item. + pub data_offset: usize, + /// Declared payload length; the payload need not be resident. + pub data_len: usize, +} + +impl EmbeddedFileHeader { + /// Borrow the payload only when the supplied complete item contains it. + pub fn payload<'a>(&self, item: &'a [u8]) -> Option<&'a [u8]> { + item.get(self.data_offset..self.data_offset.checked_add(self.data_len)?) + } +} + +/// Read an embedded item's header from a possibly partial/deferred item buffer. +/// This deliberately does not require its declared payload to be present. A malformed +/// header or a non-embedded item is an error, not an empty embedded file. Callers walking +/// framed records may continue to the next record after such an error. +/// Ported from PhotoCraft's linked-item reader; record versions remain forward-compatible. +pub fn embedded_file_header(item: &[u8]) -> Result<EmbeddedFileHeader> { + let mut r = Reader::new(item); + let kind = r.array::<4>()?; + let _version = r.u32()?; + let uuid = String::from_utf8_lossy(&read_pascal(&mut r, 1)?).into_owned(); + // A filename is metadata, never an unbounded allocation. Check before decoding. + if r.clone().u32()? > 32_768 { + return Err(PsdError::LimitExceeded("linked filename exceeds 32768 UTF-16 units")); + } + let name = UnicodeString::read(&mut r)?.to_string_lossy(); + r.skip(8)?; // file type and creator + let data_len = usize::try_from(r.u64()?).map_err(|_| PsdError::LimitExceeded("linked payload exceeds address space"))?; + if r.u8()? != 0 { + crate::descriptor::VersionedDescriptor::read(&mut r)?; + } + if kind != *b"liFD" { + return Err(PsdError::invalid("linked item is not embedded")); + } + Ok(EmbeddedFileHeader { uuid, name, data_offset: r.pos(), data_len }) +} + /// The four-character file type Photoshop records for an embedded file, from its first bytes: /// `8BPS` (`8BPB` for a PSB), `PNGf`, `JPEG`, `TIFF`, `GIFf`, or four spaces. pub fn file_type(bytes: &[u8]) -> [u8; 4] { @@ -519,7 +568,29 @@ pub struct LinkedRecord<'a> { pub raw: &'a [u8], } -impl LinkedRecord<'_> { +impl<'a> LinkedRecord<'a> { + /// The complete item, excluding framing and padding; absent for a damaged tail. + pub fn item(&self) -> Option<&'a [u8]> { + framed_record(self.raw).map(|(item, _)| item) + } + + /// Copy this complete record under a new ID, leaving the payload byte-identical. + /// Selection policy belongs to the caller; malformed tails cannot be copied. + pub fn copy_with_uuid(&self, new_uuid: &str) -> Option<Vec<u8>> { + let item = self.item()?; + let old_end = 9usize.checked_add(usize::from(*item.get(8)?))?; + let new_len = u8::try_from(new_uuid.len()).ok()?; + let mut copy = item.get(..8)?.to_vec(); + copy.push(new_len); + copy.extend_from_slice(new_uuid.as_bytes()); + copy.extend_from_slice(item.get(old_end..)?); + let mut out = Vec::with_capacity(copy.len() + 11); + out.put_u64(copy.len() as u64); + out.extend(copy); + out.resize(out.len().next_multiple_of(4), 0); + Some(out) + } + /// The unique id as text, when it is readable and valid UTF-8. pub fn uuid_str(&self) -> Option<&str> { std::str::from_utf8(self.uuid?).ok() @@ -545,17 +616,26 @@ fn record_uuid(item: &[u8]) -> Option<&[u8]> { /// The records of a linked layer block's data, in order, each with its unique id when its header /// is readable. A tail that is no complete record is returned as one record without an id. pub fn linked_records(data: &[u8]) -> Vec<LinkedRecord<'_>> { - let mut out = Vec::new(); + iter_linked_records(data).collect() +} + +/// Stream the same raw views as [`linked_records`] without allocating a record list. +/// Complete frames with malformed inner headers do not hide subsequent frames; +/// an incomplete tail is yielded once with no identifier. +pub fn iter_linked_records(data: &[u8]) -> impl Iterator<Item = LinkedRecord<'_>> { let mut rest = data; - while !rest.is_empty() { + std::iter::from_fn(move || { + if rest.is_empty() { + return None; + } let Some((item, raw)) = framed_record(rest) else { - out.push(LinkedRecord { uuid: None, raw: rest }); - break; + let tail = rest; + rest = &[]; + return Some(LinkedRecord { uuid: None, raw: tail }); }; - out.push(LinkedRecord { uuid: record_uuid(item), raw }); rest = rest.get(raw.len()..).unwrap_or_default(); - } - out + Some(LinkedRecord { uuid: record_uuid(item), raw }) + }) } /// The unique ids of every record of a linked layer block's data that has a readable one. @@ -653,18 +733,7 @@ pub fn contains_linked_record(data: &[u8], record: &[u8]) -> bool { /// field and padding; the rest of the record (embedded, external or alias data) is kept. pub fn copy_linked_record(data: &[u8], uuid: &str, new_uuid: &str) -> Option<Vec<u8>> { let record = linked_records(data).into_iter().find(|r| r.uuid == Some(uuid.as_bytes()))?; - let (item, _) = framed_record(record.raw)?; - let old_end = 9usize.checked_add(usize::from(*item.get(8)?))?; - let new_len = u8::try_from(new_uuid.len()).ok()?; - let mut copy = item.get(..8)?.to_vec(); - copy.push(new_len); - copy.extend_from_slice(new_uuid.as_bytes()); - copy.extend_from_slice(item.get(old_end..)?); - let mut out = Vec::with_capacity(copy.len() + 11); - out.put_u64(copy.len() as u64); - out.extend(copy); - out.resize(out.len().next_multiple_of(4), 0); - Some(out) + record.copy_with_uuid(new_uuid) } impl PsdFile { @@ -1111,3 +1180,57 @@ mod tests { assert!(u64::from(w) * u64::from(h) <= MAX_BAKE_PIXELS); } } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod embedded_header_tests { + use super::*; + + #[test] + fn headers_do_not_require_resident_payload() { + let data = encode_embedded_file("id", "a.psd", b"payload"); + let record = iter_linked_records(&data).next().unwrap(); + let item = record.item().unwrap(); + let header = embedded_file_header(item).unwrap(); + assert_eq!(header.uuid, "id"); + assert_eq!(header.name, "a.psd"); + assert_eq!(header.payload(item), Some(&b"payload"[..])); + assert_eq!(embedded_file_header(&item[..header.data_offset]).unwrap(), header); + assert_eq!(header.payload(&item[..header.data_offset]), None); + for n in 0..header.data_offset { + assert!(embedded_file_header(&item[..n]).is_err()); + } + } + + #[test] + fn filename_limits_and_lossy_metadata_are_preserved() { + let data = encode_embedded_file("x", &"a".repeat(32767), b""); + let item = iter_linked_records(&data).next().unwrap().item().unwrap(); + assert_eq!(embedded_file_header(item).unwrap().name.len(), 32767); + let data = encode_embedded_file("x", &"a".repeat(32768), b""); + assert!(embedded_file_header(iter_linked_records(&data).next().unwrap().item().unwrap()).is_err()); + let data = encode_embedded_file("x", "y", b"payload"); + let mut item = iter_linked_records(&data).next().unwrap().item().unwrap().to_vec(); + item[9] = 0xff; + item[14..16].copy_from_slice(&0xd800u16.to_be_bytes()); + let h = embedded_file_header(&item).unwrap(); + assert_eq!(h.uuid, "\u{fffd}"); + assert_eq!(h.name, "\u{fffd}"); + item[0..4].copy_from_slice(b"liFE"); + assert!(embedded_file_header(&item).is_err()); + } + + #[test] + fn malformed_inner_records_do_not_hide_later_files() { + let mut data = vec![0; 8]; // A complete empty item, not a truncated frame. + data.extend(encode_embedded_file("wanted", "x", b"ok")); + data.extend([1, 2, 3]); // Incomplete tail retained, never interpreted as an item. + let records: Vec<_> = iter_linked_records(&data).collect(); + assert_eq!(records, linked_records(&data)); + assert!(embedded_file_header(records[0].item().unwrap()).is_err()); + let item = records[1].item().unwrap(); + assert_eq!(embedded_file_header(item).unwrap().payload(item), Some(&b"ok"[..])); + assert_eq!(records[2].item(), None); + assert_eq!(records[2].raw, &[1, 2, 3]); + } +} diff --git a/crates/raster-codecs/Cargo.toml b/crates/raster-codecs/Cargo.toml index a29cda403..50bb61de8 100644 --- a/crates/raster-codecs/Cargo.toml +++ b/crates/raster-codecs/Cargo.toml @@ -15,4 +15,3 @@ base64 = "0.23" craft-image-codecs = { workspace = true } thiserror = { workspace = true } image = { version = "0.25", default-features = false } - diff --git a/crates/raster-codecs/tests/shared_contract.rs b/crates/raster-codecs/tests/shared_contract.rs new file mode 100644 index 000000000..390242a65 --- /dev/null +++ b/crates/raster-codecs/tests/shared_contract.rs @@ -0,0 +1,46 @@ +//! The compatibility facade must retain its policy while sharing the codec implementation. +use craft_raster_codecs::{ChannelLayout, CodecError, Image, Limits, SampleType, dds, fits, iff, pnm, xpm}; + +#[test] +fn facade_refuses_conversions_the_generic_encoder_can_plan() { + for layout in [ChannelLayout::GrayA, ChannelLayout::Rgba, ChannelLayout::Cmyk, ChannelLayout::CmykA] { + let image = Image::from_f32(1, 1, layout, &vec![0.5; layout.channels()]).unwrap(); + assert!(matches!(pnm::encode(&image), Err(CodecError::Encode { .. }))); + assert!(matches!(fits::encode(&image), Err(CodecError::Encode { .. }))); + } + for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Cmyk, ChannelLayout::CmykA] { + let image = Image::from_u8(1, 1, layout, vec![127; layout.channels()]).unwrap(); + for compression in [dds::DdsCompression::Bc1, dds::DdsCompression::Bc2, dds::DdsCompression::Bc3] { + assert!(matches!(dds::encode(&image, dds::DdsOptions { compression, mipmaps: false }), Err(CodecError::Encode { .. }))); + } + } + for layout in [ChannelLayout::Rgb, ChannelLayout::Rgba] { + let image = Image::from_u16(1, 1, layout, &vec![32768; layout.channels()]).unwrap(); + assert!(matches!(iff::encode(&image), Err(CodecError::Encode { .. }))); + assert!(matches!(dds::encode(&image, dds::DdsOptions::default()), Err(CodecError::Encode { .. }))); + } +} + +#[test] +fn fits_facade_keeps_metadata_samples_and_explicit_limits() { + let mut image = Image::from_u16(2, 1, ChannelLayout::Gray, &[0, 65535]).unwrap(); + image.text.push(("OBJECT".into(), "shared codec".into())); + let bytes = fits::encode(&image).unwrap(); + let decoded = fits::decode(&bytes, &Limits::default()).unwrap(); + assert_eq!(decoded.sample_type(), SampleType::U16); + assert_eq!(decoded.data(), image.data()); + assert!(decoded.text.contains(&("OBJECT".into(), "shared codec".into()))); + for limits in + [Limits { max_width: 1, ..Limits::default() }, Limits { max_pixels: 1, ..Limits::default() }, Limits { max_alloc: 3, ..Limits::default() }] + { + assert!(matches!(fits::decode(&bytes, &limits), Err(CodecError::LimitExceeded(_)))); + } +} + +#[test] +fn x11_table_lookup_does_not_adopt_xpm_aliases_or_normalization() { + assert_eq!(xpm::x11_color_rgb("red"), Some([1.0, 0.0, 0.0])); + for name in ["Red", "light blue", "light-blue", "light_blue", "none", "transparent", ""] { + assert_eq!(xpm::x11_color_rgb(name), None, "{name}"); + } +} diff --git a/crates/raw/docs/nikon-lens-corrections.md b/crates/raw/docs/nikon-lens-corrections.md index 2431cd6db..74e35cc77 100644 --- a/crates/raw/docs/nikon-lens-corrections.md +++ b/crates/raw/docs/nikon-lens-corrections.md @@ -1,10 +1,10 @@ # Nikon embedded distortion corrections Nikon writes its own distortion correction into NEFs from its mirrorless bodies, in the raw SubIFD tag `0xc7d5` -(NikonNEFInfo). LightCraft reads it for the NIKON Z 6_2 (Z 6II), the NIKON Z 8 and the NIKON Z f and turns it into an +(NikonNEFInfo). LightCraft reads it for the NIKON Z 6, NIKON Z 7, NIKON Z 6_2 (Z 6II), NIKON Z 8 and NIKON Z f and turns it into an `OpcodeList3` `WarpRectilinear`, so it goes through the same profile correction control, optics path, orientation handling and DNG export as the other embedded corrections. Other bodies are left alone for now even if they have the -same tag, because I've only checked files from these three. +same tag. Body recognition is limited to files checked against their camera JPEGs. This is distortion only. The vignetting block (`0x0006`) and what looks like lateral CA (`0x0007`) aren't applied yet. Like the Sony, Fujifilm and Panasonic corrections it's on by default and can be turned off under Lens @@ -24,7 +24,7 @@ NikonNEFInfo starts with `"Nikon\0"` and a 4-byte version, followed by a small T | Entry | Bytes | What it holds | |---|---|---| | `0x0005` DistortionInfo | 0–3 | `"0100"` | -| | 4 | correction mode: 1 "On (Optional)", 3 "On (Required)", 0 none | +| | 4 | correction mode: 1 "On (Optional)", 3 "On (Required)"; 0 none, 2 "Off" and unknown modes are skipped | | | 8–15 | normalisation radius in mm, a signed rational. It's 21.6 (the FX half diagonal) in every file I looked at | | | 16–19 | number of terms, 4 | | | 20, 28, 36 | the three coefficients, called `k1`, `k2`, `k3` here after ExifTool's names | @@ -84,18 +84,38 @@ extra correction for Z lenses that isn't in the readable coefficients. NikonNEFI didn't try to decode it. Even so, the readable correction takes most of the distortion out. At 24 mm the error at 0.7 half diagonals goes from −82 px to +25 px, and at 70 mm from about −137 px to under 4 px. +## Z 6 and Z 7 validation + +Six CC0 raw.pixls.us files were checked: three Z 6 and three Z 7 exposures of two repeated scenes, all with one +NIKKOR Z 24-70mm f/4 S (Z 6 at 52 mm and f/6.7, Z 7 at 56 mm and f/5.6). They don't establish coverage at other focal +lengths or with other lenses. Log-green patches in a quarter-size sensor proxy were matched against the full-size +embedded JPEG (normalised correlation at least 0.90, and a peak at least 0.02 above competing matches outside its 7 by +7 neighbourhood). The stored coefficients, zoom and optical centre were used as stored, with no per-photo fit. Radial +errors are full-size pixels over reliable matches between 0.15 and 0.95 image half diagonals: + +| Body | Files | Uncorrected radial median | Corrected radial median | Corrected radial p95 | +|---|---:|---:|---:|---:| +| Z 6 | 3 | 82.84-84.00 px | 0.88-0.96 px | 4.69-4.99 px | +| Z 7 | 3 | 124.21-124.80 px | 1.37-1.46 px | 6.18-6.38 px | + +Reliable patches reach about 0.90 half diagonals on the Z 6 and 0.94 on the Z 7, so the extreme corners aren't +validated. The remaining smooth edge error matches the native Z lens residual described above. The method, file +hashes and a production render sweep are in +[LightCraft PR #3796](https://github.com/storytold/lightcraft/pull/3796). + ## What's left out -Only `NIKON Z 6_2`, `NIKON Z 8` and `NIKON Z f` are corrected, matched exactly. A matching tag on another body doesn't tell us its +Only `NIKON Z 6`, `NIKON Z 7`, `NIKON Z 6_2`, `NIKON Z 8` and `NIKON Z f` are corrected, matched exactly. A matching tag on another body doesn't tell us its pixel pitch or image area, so other bodies can be added once someone checks their files. Only the full-frame 3:2 image area is corrected, because the stored 21.6 mm radius is the FX half diagonal, so DX and other crops are skipped. -The decoder also skips data it doesn't recognise (another layout, radius or term count, or no correction mode), +The decoder also skips data it doesn't recognise (another layout, radius or term count, or a correction mode other than 1 or 3), values that are clearly wrong (coefficients past ±1, a zoom past ±0.5, a sensor shift over 5% of the frame) and any mapping that folds back on itself before the farthest corner. The tests in `nef_lens` cover the polynomial and zoom, the sensor-shift center and refusing other bodies, layouts and crops. `nikon_in_file_distortion_becomes_a_warp` runs a synthetic Z 6II NEF through the header and full decode -and a DNG export. `nikon_in_file_distortion_is_limited_to_validated_bodies` checks the corpus: the Z f sample gets the -warp and the D5100, D7000, D7500 and Coolpix B700 samples don't. +and a DNG export. `nikon_distortion_modes_are_respected_by_probe_and_full_decode` checks that only modes 1 and 3 +give a warp, in the header probe and the full decode alike. `nikon_in_file_distortion_is_limited_to_validated_bodies` +checks the corpus: the Z f sample gets the warp and the D5100, D7000, D7500 and Coolpix B700 samples don't. None of my photos, crops or reference images are committed, only the numbers above. diff --git a/crates/raw/src/arw.rs b/crates/raw/src/arw.rs index 639fc0032..1b25aacda 100644 --- a/crates/raw/src/arw.rs +++ b/crates/raw/src/arw.rs @@ -629,6 +629,19 @@ fn raw_ifd(tiff: &Tiff) -> Option<&Ifd> { .max_by_key(|i| i.u64(t::IMAGE_WIDTH).unwrap_or(0).saturating_mul(i.u64(t::IMAGE_LENGTH).unwrap_or(0))) } +fn valid_arw2_curve(curve: &[u64]) -> bool { + curve.len() == 4 && curve.iter().all(|&v| v <= 16383) && curve.windows(2).all(|v| (v[0] >> 2) < (v[1] >> 2)) +} + +fn declared_arw2_curve(raw: &Ifd, compression: u16, one_byte_per_sample: bool) -> Result<Option<Vec<u64>>> { + let curve = raw.u64s(TONE_CURVE); + if compression == 32767 && one_byte_per_sample && curve.as_ref().is_some_and(|curve| !valid_arw2_curve(curve)) { + // Reordering or clamping malformed breakpoints fabricates a different transfer curve. + return Err(RawError::Unsupported("Sony ARW2 with an invalid tone curve".into())); + } + Ok(curve) +} + pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawImage> { let tiff = Tiff::parse(bytes)?; let ifd0 = tiff.ifds.first().ok_or_else(|| RawError::Corrupt("TIFF without IFDs".into()))?; @@ -645,6 +658,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma // archive measure exactly width x height. A200/A230/A350 files carry a strip 4-23 % larger than that (and A290/A390 one // smaller), which is a different packing, so they are refused rather than read with the wrong layout. let one_byte_per_sample = chunks.len() == 1 && strip_len == samples; + let declared_curve = declared_arw2_curve(raw, info.compression, one_byte_per_sample)?; let packed12 = info.compression == 32767 && is_packed12(&info, chunks.len(), strip_len); let (data, out_bits) = match info.compression { 7 if linear_rgb => (RawData::U16(read_ycbcr_tiles(bytes, &info, raw, mode, limits)?), 14), @@ -720,13 +734,16 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma // agree too. Genuinely packed 12-bit strips retain their 12-bit scale. let scale_bits = if info.compression == 1 && out_bits < 14 && strip_len >= (w * h * 2) as u64 { 14 } else { out_bits }; - let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { + let (cfa, assumed_cfa) = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => { - Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: 0 } + (Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: 0 }, false) } - _ => Cfa::bayer_static("RGGB"), + _ => (Cfa::bayer_static("RGGB"), true), }; - let default_black = if scale_bits >= 14 { 512.0 } else { 128.0 }; + let curve_black = (info.compression == 32767 && one_byte_per_sample) + .then(|| declared_curve.as_ref().and_then(|curve| code_curve(curve).get(256).copied()).map(f32::from)) + .flatten(); + let default_black = curve_black.unwrap_or(if scale_bits >= 14 { 512.0 } else { 128.0 }); // the decrypted SR2SubIFD, read once and only when a plain black level or white balance is missing let sr2_cell = std::cell::OnceCell::new(); let sr2 = || sr2_cell.get_or_init(|| crate::sr2::SubIfd::read(bytes, ifd0, tiff.order)).as_ref(); @@ -741,7 +758,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma _ if linear_rgb => (BlackLevel::uniform(default_black + YCBCR_OFFSET), crate::LevelSource::Fallback), _ => match (scale_bits >= 14).then(|| sr2().and_then(sr2_black)).flatten() { Some(b) => (BlackLevel::uniform(b), crate::LevelSource::Metadata), - None => (BlackLevel::uniform(default_black), crate::LevelSource::Fallback), + None => (BlackLevel::uniform(default_black), curve_black.map_or(crate::LevelSource::Fallback, |_| crate::LevelSource::Metadata)), }, }; // ARW6 samples are in 2 x 14-bit units, so the file's 14-bit levels double; without the tag the white is the @@ -842,6 +859,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma cinema: Default::default(), lens_metadata: LensMetadata { sony: sony_lens }, level_sources: crate::LevelSources { black: black_source, white: white_source }, + notices: crate::RawNotices { assumed_cfa: assumed_cfa && !linear_rgb, ..Default::default() }, }; img.validate_for(mode)?; Ok(img) @@ -873,6 +891,8 @@ mod tests { assert_eq!(header.info(), full.info()); assert_eq!((full.width, full.height, full.cpp), (4, 4, 3)); assert!(full.cfa.is_none()); + assert!(!header.notices.assumed_cfa); + assert!(!full.notices.assumed_cfa); assert_eq!(full.data.len(), 48); assert_eq!(full.wb_multipliers, Some([1.0; 3])); // the YCbCr data sit 512 above the recorded sensor black level; white moves with it @@ -911,6 +931,10 @@ mod tests { /// A 32767-compressed ARW whose single strip is `strip` bytes for a 32 x 4 image. fn arw_with_strip(strip: usize) -> Vec<u8> { + arw_with_strip_and_cfa(strip, None) + } + + fn arw_with_strip_and_cfa(strip: usize, cfa: Option<(Vec<u16>, Vec<u8>)>) -> Vec<u8> { use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let mut raw = IfdBuilder::new(); raw.set(t::MAKE, Value::Ascii("SONY".into())); @@ -921,11 +945,37 @@ mod tests { raw.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![1])); raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); raw.set(t::COMPRESSION, Value::Short(vec![32767])); + if let Some((dimensions, pattern)) = cfa { + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(dimensions)); + raw.set(t::CFA_PATTERN_EP, Value::Byte(pattern)); + } raw.set(TONE_CURVE, Value::Short(vec![8000, 10400, 12900, 14100])); raw.set_image(ImageData::Strips { rows_per_strip: 4, strips: vec![vec![0u8; strip]] }); TiffWriter::default().write(&[raw]).unwrap() } + #[test] + fn cfa_fallback_notices_follow_missing_malformed_and_valid_source_tags() { + for (tags, expected, assumed) in [ + (None, "RGGB", true), + (Some((vec![1, 4], vec![0, 1, 1, 2])), "RGGB", true), + (Some((vec![2, 2], vec![0, 1, 3, 2])), "RGGB", true), + (Some((vec![2, 2], vec![0, 1, 2])), "RGGB", true), + (Some((vec![2, 2], vec![1, 0, 2, 1])), "GRBG", false), + ] { + let file = arw_with_strip_and_cfa(32 * 4, tags); + let header = decode(&file, Mode::Header, &Limits::default()).unwrap(); + let full = decode(&file, Mode::Full, &Limits::default()).unwrap(); + assert_eq!(header.info(), full.info()); + for image in [&header, &full] { + assert_eq!(image.cfa.as_ref().unwrap().name(), expected); + assert_eq!(image.notices.assumed_cfa, assumed); + } + assert!(header.data.is_empty()); + assert_eq!(full.data.len(), 32 * 4); + } + } + /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow. #[test] fn strip_byte_counts_past_u64_max_do_not_overflow() { @@ -1110,6 +1160,25 @@ mod tests { let _ = code_curve(&[60000, 1, 0, 0]); } + #[test] + fn arw2_rejects_non_increasing_declared_curve_in_header_and_full_decode() { + let valid = arw_with_strip(32 * 4); + assert!(crate::decode(&valid).is_ok()); + let mut damaged = valid.clone(); + let tiff = Tiff::parse(&damaged).unwrap(); + let curve = raw_ifd(&tiff).unwrap().get(TONE_CURVE).unwrap(); + let at = curve.offset as usize; + for (dst, value) in damaged[at..at + 8].as_chunks_mut::<2>().0.iter_mut().zip([9000u16, 8000, 12000, 13000]) { + dst.copy_from_slice(&value.to_le_bytes()); + } + for mode in [Mode::Header, Mode::Full] { + assert!(matches!(decode(&damaged, mode, &Limits::default()), Err(RawError::Unsupported(why)) if why.contains("curve"))); + let image = decode(&valid, mode, &Limits::default()).unwrap(); + assert_eq!(image.black.mean(), 512.0); + assert_eq!(image.level_sources.black, crate::LevelSource::Metadata, "the declared curve maps the black code"); + } + } + #[test] fn decipher_inverts_the_cube_substitution() { let mut seen = [false; 256]; diff --git a/crates/raw/src/cr2.rs b/crates/raw/src/cr2.rs index ec98ea48e..025384582 100644 --- a/crates/raw/src/cr2.rs +++ b/crates/raw/src/cr2.rs @@ -10,8 +10,11 @@ //! - Colour filter layout: IFD#3 tag `0xc5e0` (`CR2CFAPattern` in the ExifTool EXIF tag-name docs): 1 = RGGB, //! 2 = BGGR, 3 = GBRG, 4 = GRBG, anchored at the top-left of the full decoded sensor (masked borders included). //! It differs by model (e.g. 3 on the 50D/60D/7D/550D/5D Mark II, 1 on the 40D/5D Mark III/6D/5DS R), so it is -//! read per file (no model table); files without the tag fall back to RGGB (storytold/lightcraft#85). The parity of the +//! read per file first. Without a known tag, observed model IDs provide the fallback; scene-derived +//! measurements are not authoritative enough to establish sensor phase. The parity of the //! `SensorInfo` borders does *not* predict it (RGGB files come with both even and odd top borders). +//! Header-only probes do not decode pixels for this fallback: without the tag their reported CFA +//! is assumed and can refine on full decode, as indicated by `RawNotices::assumed_cfa`. //! - `SensorInfo` (maker note `0x00e0`): sensor width/height and the left/top/right/bottom borders of the image //! area. Light already reaches some columns left of that border (EOS 6D: masked columns 0–70, border 84; 10–36 //! such columns on every corpus body), so the masked columns that give the black level are measured from the @@ -38,6 +41,7 @@ const SRAW_TYPE: u16 = 0xc6c5; /// `SRAW_TYPE` value of the YCbCr frames of sRAW / mRAW (IFD2's preview image carries 3). const SRAW_YCC: u32 = 4; const CR2_CFA_PATTERN: u16 = 0xc5e0; +const CANON_MODEL_ID: u16 = 0x0010; const SENSOR_INFO: u16 = 0x00e0; const COLOR_BALANCE: u16 = 0x4001; /// ShotInfo, whose value 7 is the white-balance setting. @@ -61,6 +65,13 @@ fn cfa_from_tag(v: Option<u64>) -> Option<Cfa> { Some(Cfa::bayer_static(name)) } +/// Fallback for files without CR2CFAPattern. Image content cannot establish sensor phase safely. +fn fallback_cfa(_data: &[u16], _width: usize, _area: Rect, _black: f32, _white: f32, model: Option<u64>) -> (Cfa, bool) { + // Observed CC0 raw.pixls.us captures: 5D II, 7D, 550D, 600D and 1200D. + let green_first = [0x8000_0218, 0x8000_0250, 0x8000_0270, 0x8000_0286, 0x8000_0327].into_iter().any(|id| model == Some(id)); + (Cfa::bayer_static(if green_first { "GBRG" } else { "RGGB" }), true) +} + /// The 16-bit words of a maker-note array. Canon writes `ColorData` as SHORT in most models, but as UNDEFINED /// bytes (count = byte length, e.g. 5120) in the PowerShot / EOS M models with ColorData versions -3 and -4; /// those bytes are the same 16-bit words in the maker note's byte order, so they are paired up, not read one by @@ -198,6 +209,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma let chunk = craft_tiff::image::Chunk { index: 0, x: 0, y: 0, width: 0, height: 0, plane: 0, offset: off, len }; let src = chunk_bytes(bytes, &chunk).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?; let (fw, fh, nc, prec) = ljpeg::frame_info(src)?; + let tagged_cfa = cfa_from_tag(raw.u64(CR2_CFA_PATTERN)); let frame = match mode { Mode::Full => { let total = (fw as u64) @@ -270,12 +282,19 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma let color_data = mn.as_ref().and_then(|m| m.ifd.value(COLOR_BALANCE).map(|v| words(v, m.order))); let kelvin_presets = color_data.as_deref().and_then(kelvin_presets_from_color_data); let wb = color_data.as_deref().and_then(wb_from_color_balance).or_else(|| wb_from_wb_info(mn.as_ref()?)); - let cfa = cfa_from_tag(raw.u64(CR2_CFA_PATTERN)).unwrap_or_else(|| Cfa::bayer_static("RGGB")); let (white, white_source) = white_from_data_sourced(&active_rows(&data, width, active), prec as u32); let (black, black_source) = match masked_columns(&data, width, active, white) { cols if cols.len() >= 2 => black_from_columns_sourced(&data, width, cols, active.y..active.y + active.height, active), _ => (BlackLevel::uniform(0.0), crate::LevelSource::Fallback), }; + let model = mn.as_ref().and_then(|m| m.ifd.u64(CANON_MODEL_ID)); + let (cfa, assumed_cfa) = match tagged_cfa { + Some(cfa) => (cfa, false), + None => { + let (cfa, guessed) = fallback_cfa(&data, width, active, black.mean(), white, model); + (cfa, guessed || mode == Mode::Header) + } + }; let img = RawImage { format: RawFormat::Cr2, width, @@ -298,6 +317,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma cinema: Default::default(), lens_metadata: Default::default(), level_sources: crate::LevelSources { black: black_source, white: white_source }, + notices: crate::RawNotices { assumed_cfa, ..Default::default() }, }; img.validate_for(mode)?; Ok(img) @@ -397,6 +417,112 @@ pub(crate) mod tests { assert_eq!(name(None), None); } + #[test] + fn absent_cfa_tag_uses_safe_phase_without_shifting_for_crop_parity() { + let (w, h) = (192usize, 96usize); + for red_row in [0usize, 1] { + let samples: Vec<u16> = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let texture = ((x / 2 + y / 2) % 17) as u16; + if i % 97 == 0 { + return 13000; + } + 100 + if (y & 1) == red_row { + if x & 1 == 0 { 500 + texture } else { 1000 + texture } + } else if x & 1 == 0 { + 1000 + texture + } else { + 667 + texture + } + }) + .collect(); + for (left, top) in [(16, 4), (17, 4), (16, 5), (17, 5)] { + let area = Rect::new(left, top, w - left, h - top); + let (cfa, assumed) = fallback_cfa(&samples, w, area, 100.0, 4000.0, None); + assert_eq!(cfa.name(), "RGGB"); + assert!(assumed); + } + let mut bytes = synthetic_cr2_of(&samples, w, h, None, None); + let marker = [0xe0, 0xc5, 4, 0, 1, 0, 0, 0]; + let at = bytes.windows(marker.len()).position(|b| b == marker).unwrap(); + // The explicit tag remains authoritative even when the observed sensor phase disagrees. + bytes[at + 8..at + 12].copy_from_slice(&4u32.to_le_bytes()); + let explicit = crate::decode(&bytes).unwrap(); + assert_eq!(explicit.cfa.as_ref().unwrap().name(), "GRBG"); + assert_eq!(explicit.info(), crate::probe_info(&bytes).unwrap()); + assert!(!explicit.notices.assumed_cfa); + bytes[at..at + 2].copy_from_slice(&0xc5dfu16.to_le_bytes()); + let full = crate::decode(&bytes).unwrap(); + assert_eq!(full.cfa.as_ref().unwrap().name(), "RGGB"); + assert!(full.notices.assumed_cfa); + let header = decode(&bytes, Mode::Header, &Limits::default()).unwrap(); + assert!(header.notices.assumed_cfa); + assert!(matches!(header.data, RawData::U16(ref v) if v.is_empty())); + assert_eq!(full.data, RawData::U16(samples)); + } + } + + #[test] + fn inconclusive_cfa_measurement_keeps_observed_model_fallback_and_safe_geometry() { + let data = vec![512; 64 * 32]; + let area = Rect::new(0, 0, 64, 32); + assert_eq!(fallback_cfa(&data, 64, area, 512.0, 16000.0, Some(0x8000_0250)).0.name(), "GBRG"); + assert!(fallback_cfa(&data, 64, area, 512.0, 16000.0, Some(0x8000_0250)).1); + assert_eq!(fallback_cfa(&data, 64, area, 512.0, 16000.0, None).0.name(), "RGGB"); + assert!(fallback_cfa(&data, 64, area, 512.0, 16000.0, None).1); + let gradient: Vec<u16> = (0..192 * 96) + .map(|i| { + let (x, y) = (i % 192, i / 192); + if y % 2 == 0 { + if x % 2 == 0 { 500 } else { 1000 + 8 * x as u16 } + } else if x % 2 == 0 { + 1000 + 8 * x as u16 + } else { + 500 + } + }) + .collect(); + let (cfa, assumed) = fallback_cfa(&gradient, 192, Rect::new(0, 0, 192, 96), 0.0, 4000.0, None); + assert_eq!(cfa.name(), "RGGB"); + assert!(assumed); + let mut bytes = synthetic_cr2_of(&gradient, 192, 96, None, None); + let marker = [0xe0, 0xc5, 4, 0, 1, 0, 0, 0]; + let at = bytes.windows(marker.len()).position(|b| b == marker).unwrap(); + // Exercise the decoder's missing-tag fallback, not the fixture's default CFA tag. + bytes[at..at + 2].copy_from_slice(&0xc5dfu16.to_le_bytes()); + let decoded = crate::decode(&bytes).unwrap(); + assert_eq!(decoded.cfa.as_ref().unwrap().name(), "RGGB"); + assert!(decoded.notices.assumed_cfa); + } + + #[test] + fn model_cfa_fallback_is_disclosed_in_header_and_full_decodes() { + // A single inline LONG maker-note entry needs no external offsets. + let mut note = Vec::new(); + note.extend_from_slice(&1u16.to_le_bytes()); + note.extend_from_slice(&CANON_MODEL_ID.to_le_bytes()); + note.extend_from_slice(&4u16.to_le_bytes()); + note.extend_from_slice(&1u32.to_le_bytes()); + note.extend_from_slice(&0x8000_0250u32.to_le_bytes()); + note.extend_from_slice(&0u32.to_le_bytes()); + let samples = vec![512u16; 64 * 32]; + let mut bytes = synthetic_cr2_of(&samples, 64, 32, None, Some(note)); + let marker = [0xe0, 0xc5, 4, 0, 1, 0, 0, 0]; + let at = bytes.windows(marker.len()).position(|b| b == marker).unwrap(); + // Remove only the CFA tag; the model ID and encoded samples stay intact. + bytes[at..at + 2].copy_from_slice(&0xc5dfu16.to_le_bytes()); + let header = decode(&bytes, Mode::Header, &Limits::default()).unwrap(); + let full = decode(&bytes, Mode::Full, &Limits::default()).unwrap(); + for image in [&header, &full] { + assert_eq!(image.cfa.as_ref().unwrap().name(), "GBRG"); + assert!(image.notices.assumed_cfa); + } + assert_eq!(header.info(), full.info()); + assert_eq!(full.data, RawData::U16(samples)); + assert!(header.data.is_empty()); + } + #[test] fn wb_probe() { let mut v = vec![0u64; 120]; diff --git a/crates/raw/src/cr2/sraw.rs b/crates/raw/src/cr2/sraw.rs index 7ad98906b..4b02881d2 100644 --- a/crates/raw/src/cr2/sraw.rs +++ b/crates/raw/src/cr2/sraw.rs @@ -393,6 +393,7 @@ pub(super) fn decode(bytes: &[u8], tiff: &Tiff, raw: &Ifd, mode: Mode, limits: & camera: tiff.ifds.first().map(Camera::from_ifd0).unwrap_or_default(), cinema: Default::default(), lens_metadata: Default::default(), + notices: Default::default(), level_sources: Default::default(), }; img.validate_for(mode)?; diff --git a/crates/raw/src/cr3.rs b/crates/raw/src/cr3.rs index 956446c6e..14bec6132 100644 --- a/crates/raw/src/cr3.rs +++ b/crates/raw/src/cr3.rs @@ -274,6 +274,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma camera: ifd0.map(Camera::from_ifd0).unwrap_or_default(), cinema: Default::default(), lens_metadata: Default::default(), + notices: Default::default(), level_sources: Default::default(), }; // Canon's stated white level can sit below the sensor's true saturation (EOS RP: 14558 @@ -404,6 +405,15 @@ mod tests { } fn track(entry: &[u8], offset: u64, size: u32) -> Vec<u8> { + let mapping = [0u32, 1, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>(); + track_with_mapping(entry, offset, size, &mapping) + } + + fn track_with_mapping(entry: &[u8], offset: u64, size: u32, mapping: &[u8]) -> Vec<u8> { + track_with_table(entry, offset, size, b"stsc", mapping) + } + + fn track_with_table(entry: &[u8], offset: u64, size: u32, table: &[u8; 4], payload: &[u8]) -> Vec<u8> { let mut stsd = vec![0u8; 4]; stsd.extend(1u32.to_be_bytes()); stsd.extend(entry); @@ -413,7 +423,15 @@ mod tests { let mut co64 = vec![0u8; 4]; co64.extend(1u32.to_be_bytes()); co64.extend(offset.to_be_bytes()); - let tables = [box_bytes(b"stsd", &stsd), box_bytes(b"stsz", &stsz), box_bytes(b"co64", &co64)].concat(); + let mapping = [0u32, 1, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>(); + let offsets = if table == b"stco" { box_bytes(b"stco", payload) } else { box_bytes(b"co64", if table == b"co64" { payload } else { &co64 }) }; + let tables = [ + box_bytes(b"stsd", &stsd), + box_bytes(b"stsc", if table == b"stsc" { payload } else { &mapping }), + box_bytes(b"stsz", if table == b"stsz" { payload } else { &stsz }), + offsets, + ] + .concat(); box_bytes(b"trak", &box_bytes(b"mdia", &box_bytes(b"minf", &box_bytes(b"stbl", &tables)))) } @@ -636,6 +654,105 @@ mod tests { assert!(matches!(decode(&missing, Mode::Header, &Limits::default()), Err(RawError::Corrupt(_)))); } + /// Independently framed constant-value CRX: each 4x4 tile has four 2x2 + /// planes whose one-byte 0x1e entropy streams reconstruct sensor value8193. + fn flat_raw_track(tiles: u32) -> (Vec<u8>, Vec<u8>) { + let mut sample = Vec::new(); + let marker = |out: &mut Vec<u8>, code: u16, size: u32, flags: u32| { + out.extend(code.to_be_bytes()); + out.extend(8u16.to_be_bytes()); + out.extend(size.to_be_bytes()); + out.extend(flags.to_be_bytes()); + }; + for tile in 0..tiles { + marker(&mut sample, 0xff01, 4, tile << 16); + for plane in 0..4 { + marker(&mut sample, 0xff02, 1, (plane << 28) | 0x0800_0000); + marker(&mut sample, 0xff03, 1, 0x0020_0000); + } + } + let header_size = sample.len() as u32; + sample.extend(std::iter::repeat_n(0x1e, tiles as usize * 4)); + let mut coding = vec![0u8; 52]; + coding[..2].copy_from_slice(&0xff00u16.to_be_bytes()); + coding[2..4].copy_from_slice(&48u16.to_be_bytes()); + coding[4..6].copy_from_slice(&0x100u16.to_be_bytes()); + for (offset, value) in [(8, tiles * 4), (12, 4), (16, 4), (20, 4), (28, header_size)] { + coding[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); + } + coding[24] = 14; + coding[25] = 0x40; + let mut entry = vec![0u8; 82]; + entry[24..26].copy_from_slice(&((tiles * 4) as u16).to_be_bytes()); + entry[26..28].copy_from_slice(&4u16.to_be_bytes()); + entry.extend(box_bytes(b"CMP1", &coding)); + (box_bytes(b"CRAW", &entry), sample) + } + + #[test] + fn truncated_main_sample_mapping_cannot_silently_select_a_valid_reduced_raw() { + let mapping = [0u32, 1, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>(); + let (reduced_entry, reduced_sample) = flat_raw_track(1); + let (main_entry, main_sample) = flat_raw_track(2); + let main_offset = 4096 + reduced_sample.len(); + let file = |main_table: Option<(&[u8; 4], &[u8])>, main_first: bool| { + let reduced = track_with_mapping(&reduced_entry, 4096, reduced_sample.len() as u32, &mapping); + let tracks = if let Some((table, payload)) = main_table { + let main = track_with_table(&main_entry, main_offset as u64, main_sample.len() as u32, table, payload); + if main_first { [main, reduced].concat() } else { [reduced, main].concat() } + } else { + reduced + }; + let mut bytes = box_bytes(b"ftyp", b"crx \0\0\0\x01crx isom"); + bytes.extend(box_bytes(b"moov", &tracks)); + assert!(bytes.len() < 4096); + bytes.resize(4096, 0); + bytes.extend_from_slice(&reduced_sample); + bytes.extend_from_slice(&main_sample); + bytes + }; + let mut co64 = vec![0u8; 4]; + co64.extend(1u32.to_be_bytes()); + co64.extend((main_offset as u64).to_be_bytes()); + let valid_tables = [ + (b"stsc", mapping.clone()), + (b"stsz", [0u32, main_sample.len() as u32, 1].into_iter().flat_map(u32::to_be_bytes).collect()), + (b"co64", co64), + (b"stco", [0u32, 1, main_offset as u32].into_iter().flat_map(u32::to_be_bytes).collect()), + ]; + for mode in [Mode::Header, Mode::Full] { + // The smaller source is genuinely decodable, so dropping the larger + // track would return success rather than merely a different failure. + let reduced = decode(&file(None, false), mode, &Limits::default()).unwrap(); + assert_eq!((reduced.width, reduced.height), (4, 4)); + if mode == Mode::Full { + assert_eq!(reduced.data, RawData::U16(vec![8193; 16])); + } + for main_first in [false, true] { + for (table, payload) in &valid_tables { + let valid = decode(&file(Some((table, payload)), main_first), mode, &Limits::default()).unwrap(); + assert_eq!((valid.width, valid.height), (8, 4)); + if mode == Mode::Full { + assert_eq!(valid.data, RawData::U16(vec![8193; 32])); + } + for truncated in [vec![], vec![0; 4], vec![0, 0, 0, 0, 0, 0, 0, 1]] { + let bytes = file(Some((table, &truncated)), main_first); + let container = parse_cr3(&bytes).unwrap(); + assert_eq!(container.tracks.len(), 2, "mapping damage cannot erase the main track"); + let selected = main_track(&container.tracks).unwrap(); + assert!(matches!(selected.kind, Cr3TrackKind::Raw { width: 8, height: 4, .. })); + assert!(selected.data.is_none()); + assert!(selected.compression(&bytes).is_some()); + assert!( + matches!(decode(&bytes, mode, &Limits::default()), Err(RawError::Corrupt(message)) if message.contains("sample")), + "{mode:?}/{table:?}: main mapping damage cannot decode the reduced source" + ); + } + } + } + } + } + #[test] fn color_data_uses_versioned_as_shot_offsets() { for (version, wb_at, black_at, white_at) in @@ -712,6 +829,7 @@ mod tests { camera: Camera::default(), cinema: Default::default(), lens_metadata: Default::default(), + notices: Default::default(), level_sources: Default::default(), } } diff --git a/crates/raw/src/crw.rs b/crates/raw/src/crw.rs index 690966751..b51c04261 100644 --- a/crates/raw/src/crw.rs +++ b/crates/raw/src/crw.rs @@ -65,6 +65,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, caller: &Limits) -> Result<RawIma cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: crate::RawNotices::default(), }; img.validate_for(mode)?; Ok(img) diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rs index 7c5b361cd..aaa08e49a 100644 --- a/crates/raw/src/dng.rs +++ b/crates/raw/src/dng.rs @@ -5,8 +5,8 @@ use crate::gaintable::GainTableMap; use crate::profile::{HsvTable, ProfileLook, ToneCurve}; use crate::tiffraw::{Packing, read_image_in}; use crate::{ - BlackLevel, Camera, Cfa, CinemaTags, ColorData, Limits, Matrix3, Mode, Orientation, RawData, RawError, RawFormat, RawImage, Rect, Result, - Timecode, opcodes, + BlackLevel, Camera, Cfa, CinemaTags, ColorData, LevelSource, LevelSources, Limits, Matrix3, Mode, Orientation, RawData, RawError, RawFormat, + RawImage, RawNotices, Rect, Result, Timecode, opcodes, }; use craft_tiff::tags::{self as t, photometric}; use craft_tiff::{ByteOrder, Ifd, Tiff, Value}; @@ -178,7 +178,15 @@ pub(crate) fn is_plain_cfa_tiff(tiff: &Tiff, bytes: &[u8]) -> bool { if !raw.contains(t::AS_SHOT_NEUTRAL) && !tiff.ifds.first().is_some_and(|i| i.contains(t::AS_SHOT_NEUTRAL)) { return false; } - let Ok(info) = raw.image() else { return false }; + let Ok(info) = raw.image() else { + // Recognition must not turn a damaged, otherwise supported plain CFA + // image into an unsupported container. Let decode_as report its layout + // error; these tags alone never decompress or allocate pixel samples. + return raw.u16(t::COMPRESSION).unwrap_or(1) == t::compression::NONE + && raw.u16(t::SAMPLES_PER_PIXEL).unwrap_or(1) == 1 + && (1..=16).contains(&raw.u16(t::BITS_PER_SAMPLE).unwrap_or(1)) + && raw.u16(t::SAMPLE_FORMAT).unwrap_or(1) != 3; + }; if info.samples_per_pixel != 1 || !(1..=16).contains(&info.bits()) || info.sample_format == 3 { return false; } @@ -274,8 +282,13 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f let bits = info.bits() as u32; // DNG 1.4 stores lossy JPEG at 8 bits per sample: the tiles are 8-bit baseline JPEGs whatever the tag says, // and reading them as a deeper sample would put the picture at the bottom of its range - if info.compression == t::compression::LOSSY_JPEG && bits != 8 { - return Err(RawError::Unsupported(format!("lossy JPEG DNG with {bits}-bit samples (DNG allows only 8)"))); + if info.compression == t::compression::LOSSY_JPEG { + if bits != 8 { + return Err(RawError::Unsupported(format!("lossy JPEG DNG with {bits}-bit samples (DNG allows only 8)"))); + } + if !matches!(cpp, 1 | 3) { + return Err(RawError::Unsupported(format!("lossy JPEG DNG with {cpp} samples per pixel"))); + } } let mut data = read_image_in(mode, bytes, &info, tiff.order, Packing::Msb, limits)?; @@ -312,6 +325,7 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f // (a DOUBLE past `f32::MAX` casts to infinity, which would black the picture out: ignored like a zero one) let mut white: Vec<f32> = levels(t::WHITE_LEVEL).f64s(t::WHITE_LEVEL).unwrap_or_default().into_iter().map(|v| v as f32).filter(|v| v.is_finite() && *v > 0.0).collect(); + let white_source = if !white.is_empty() || table_max.is_some() { LevelSource::Metadata } else { LevelSource::Fallback }; if white.is_empty() { white = vec![default_white]; } @@ -333,7 +347,13 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f }; // (a FLOAT / DOUBLE tag can hold NaN or infinity: such a level reads as 0, in its place) let level = |v: f64| Some(v as f32).filter(|v| v.is_finite()).unwrap_or(0.0); - let mut values: Vec<f32> = levels(t::BLACK_LEVEL).f64s(t::BLACK_LEVEL).unwrap_or_default().into_iter().map(level).collect(); + let declared_black = levels(t::BLACK_LEVEL).f64s(t::BLACK_LEVEL).unwrap_or_default(); + let black_source = if !declared_black.is_empty() && declared_black.iter().all(|value| (*value as f32).is_finite()) { + LevelSource::Metadata + } else { + LevelSource::Fallback + }; + let mut values: Vec<f32> = declared_black.into_iter().map(level).collect(); // A TIFF that is not a DNG may state four black levels without `BlackLevelRepeatDim`: one per site of its 2 × 2 // CFA, row-major (PhotoCraft's reading of Hasselblad files). In a DNG the count has to match the repeat. let (br, bc) = if format != RawFormat::Dng && cpp == 1 && values.len() == 4 && !levels(t::BLACK_LEVEL).contains(t::BLACK_LEVEL_REPEAT_DIM) { @@ -364,7 +384,7 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f } _ => Rect::new(0, 0, full_w, full_h), }; - let crop = default_crop(raw, active_area); + let (crop, default_crop_adjusted) = default_crop(raw, active_area, full_w, full_h); let (active_area, crop) = if (full_w, full_h) == (w, h) { (active_area, crop) } else { @@ -378,6 +398,7 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f (area, scale(crop).clipped(area.width, area.height)) }; + let mut assumed_cfa = false; let cfa = if info.photometric == photometric::CFA { if raw.u16(t::CFA_LAYOUT).unwrap_or(1) != 1 { return Err(RawError::Unsupported("non-rectangular CFA layout".into())); @@ -391,7 +412,10 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f let assumed = [0u8, 1, 1, 2]; let pat = match raw.bytes(t::CFA_PATTERN_EP) { Some(p) => p, - None if format != RawFormat::Dng && (rows, cols) == (2, 2) => &assumed, + None if format != RawFormat::Dng && (rows, cols) == (2, 2) => { + assumed_cfa = true; + &assumed + } None => return Err(RawError::Corrupt("missing CFAPattern".into())), }; if pat.len() != rows * cols { @@ -422,6 +446,9 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f let opcodes = crate::OpcodeLists { list1: opcode_list(t::OPCODE_LIST_1), list2: opcode_list(t::OPCODE_LIST_2), list3: opcode_list(t::OPCODE_LIST_3) }; + let color = color_data(ifd0, raw, tiff.order); + let gain_table_omitted = [raw, ifd0].iter().any(|ifd| ifd.contains(t::PROFILE_GAIN_TABLE_MAP) || ifd.contains(t::PROFILE_GAIN_TABLE_MAP_2)) + && color.profile.gain_table_map.is_none(); let img = RawImage { format, width: w, @@ -435,7 +462,7 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f active_area, crop, orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), - color: color_data(ifd0, raw, tiff.order), + color, wb_multipliers: None, linearized, pixel_aspect: default_scale_aspect(raw.f64s(t::DEFAULT_SCALE).as_deref()), @@ -443,7 +470,8 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f camera: Camera::from_ifd0(ifd0), cinema: cinema_tags(ifd0, raw), lens_metadata: Default::default(), - level_sources: Default::default(), + level_sources: LevelSources { black: black_source, white: white_source }, + notices: RawNotices { default_crop_adjusted, gain_table_omitted, assumed_cfa }, }; img.validate_for(mode)?; Ok(img) @@ -472,33 +500,45 @@ fn cinema_tags(ifd0: &Ifd, raw: &Ifd) -> CinemaTags { } } -/// The default crop, relative to the active area. Each tag has its own default (DNG 1.7.1, `DefaultCropOrigin` -/// and `DefaultCropSize`): the origin (0, 0), the size the whole area, so a file with only a size crops from the -/// area's corner. A tag that is present must hold two finite, non-negative values, and the crop must start inside -/// the area and be at least one pixel each way; otherwise the crop is the whole active area. -fn default_crop(raw: &Ifd, active_area: Rect) -> Rect { +/// The default crop is relative to ActiveArea. DNG 1.7.1 defines independent +/// defaults: origin (0, 0), size ImageWidth/ImageLength. An unusable optional crop +/// preserves the entire active image. Valid partly overlapping rectangles retain the +/// existing clipped-crop policy, with an explicit notice rather than silent adjustment. +fn default_crop(raw: &Ifd, active_area: Rect, full_width: usize, full_height: usize) -> (Rect, bool) { let whole = Rect::new(0, 0, active_area.width, active_area.height); - let pair = |tag: u16, default: [f64; 2]| -> Option<[f64; 2]> { - if !raw.contains(tag) { - return Some(default); - } - match raw.f64s(tag).as_deref() { - Some([a, b]) if a.is_finite() && b.is_finite() && *a >= 0.0 && *b >= 0.0 => Some([*a, *b]), - _ => None, - } - }; - let (Some([x, y]), Some([cw, ch])) = - (pair(t::DEFAULT_CROP_ORIGIN, [0.0, 0.0]), pair(t::DEFAULT_CROP_SIZE, [active_area.width as f64, active_area.height as f64])) - else { - return whole; - }; - if cw < 1.0 || ch < 1.0 { - return whole; + if !raw.contains(t::DEFAULT_CROP_ORIGIN) && !raw.contains(t::DEFAULT_CROP_SIZE) { + return (whole, false); } - // (`as usize` saturates, and `clipped` holds the origin to the area) - let crop = - Rect::new(x.round() as usize, y.round() as usize, cw.round() as usize, ch.round() as usize).clipped(active_area.width, active_area.height); - if crop.width == 0 || crop.height == 0 { whole } else { crop } + let pair = |tag: u16, default: [f64; 2]| -> Option<[usize; 2]> { + let values = if raw.contains(tag) { + match raw.f64s(tag).as_deref() { + Some([a, b]) => [*a, *b], + _ => return None, + } + } else { + default + }; + // Float-to-integer casts saturate. Refuse nonfinite/unrepresentable numbers before + // casting so a hostile origin cannot become a seemingly valid clipped rectangle. + if values.iter().any(|value| !value.is_finite() || value.round() >= usize::MAX as f64) { + return None; + } + if values.iter().any(|value| *value < 0.0) { + return None; + } + Some(values.map(|value| value.round() as usize)) + }; + let (Some([x, y]), Some([width, height])) = + (pair(t::DEFAULT_CROP_ORIGIN, [0.0, 0.0]), pair(t::DEFAULT_CROP_SIZE, [full_width as f64, full_height as f64])) + else { + return (whole, true); + }; + let requested = Rect::new(x, y, width, height); + let crop = requested.clipped(active_area.width, active_area.height); + if crop.width == 0 || crop.height == 0 { + return (whole, true); + } + (crop, crop != requested) } /// Pixel height over width from `DefaultScale` (horizontal, vertical): only a clear 1.5 to 4 ratio counts (the rows stretch; a wider-than-tall pixel is left alone). @@ -509,6 +549,9 @@ fn default_scale_aspect(scale: Option<&[f64]>) -> f32 { } } +#[cfg(test)] +mod compat_review_tests; + #[cfg(test)] mod tests { #[test] @@ -621,3 +664,7 @@ mod tests { assert!(deinterleave(&mut hostile, 8, 6, 1, 1 << 20, 1).is_err()); } } + +#[cfg(all(test, feature = "hasselblad"))] +#[path = "dng/probe_review_tests.rs"] +mod probe_review_tests; diff --git a/crates/raw/src/dng/compat_review_tests.rs b/crates/raw/src/dng/compat_review_tests.rs new file mode 100644 index 000000000..48300cbf7 --- /dev/null +++ b/crates/raw/src/dng/compat_review_tests.rs @@ -0,0 +1,120 @@ +use super::*; +use craft_tiff::{Entry, IfdBuilder, ImageData, TiffWriter}; + +fn ifd(tags: Vec<(u16, Value)>) -> Ifd { + let mut entries: Vec<_> = tags.into_iter().map(|(tag, value)| Entry { tag, value, offset: 0 }).collect(); + entries.sort_by_key(|entry| entry.tag); + Ifd { entries, ..Default::default() } +} + +#[test] +fn optional_crop_adjustments_are_explicit_and_valid_clipping_is_preserved() { + let active = Rect::new(3, 2, 11, 8); + let whole = Rect::new(0, 0, 11, 8); + let clipped = ifd(vec![(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![10, 0])), (t::DEFAULT_CROP_SIZE, Value::Long(vec![5, 4]))]); + assert_eq!(default_crop(&clipped, active, 16, 12), (Rect::new(10, 0, 1, 4), true)); + assert_eq!(default_crop(&ifd(vec![(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![1, 1]))]), active, 16, 12), (Rect::new(1, 1, 10, 7), true)); + for fields in [ + vec![(t::DEFAULT_CROP_SIZE, Value::Long(vec![4]))], + vec![(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![0, 0])), (t::DEFAULT_CROP_SIZE, Value::Long(vec![0, 4]))], + ] { + assert_eq!(default_crop(&ifd(fields), active, 16, 12), (whole, true)); + } + assert_eq!(default_crop(&Ifd::default(), active, 16, 12), (whole, false)); + assert_eq!(default_crop(&ifd(vec![(t::DEFAULT_CROP_SIZE, Value::Long(vec![5, 4]))]), active, 16, 12), (Rect::new(0, 0, 5, 4), false)); + assert_eq!( + default_crop(&ifd(vec![(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![2, 1])), (t::DEFAULT_CROP_SIZE, Value::Long(vec![5, 4]))]), active, 16, 12), + (Rect::new(2, 1, 5, 4), false) + ); +} + +#[test] +fn hostile_crop_coordinates_fall_back_explicitly_before_saturating_casts() { + for bad in [1e300, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + for tag in [t::DEFAULT_CROP_ORIGIN, t::DEFAULT_CROP_SIZE] { + let raw = ifd(vec![(tag, Value::Double(vec![bad, 1.]))]); + assert_eq!(default_crop(&raw, Rect::new(0, 0, 16, 12), 16, 12), (Rect::new(0, 0, 16, 12), true)); + } + } +} + +fn linear(extra: &[(u16, Value)]) -> Vec<u8> { + let mut raw = IfdBuilder::new(); + for (tag, value) in [ + (t::IMAGE_WIDTH, Value::Long(vec![8])), + (t::IMAGE_LENGTH, Value::Long(vec![6])), + (t::BITS_PER_SAMPLE, Value::Short(vec![16])), + (t::SAMPLES_PER_PIXEL, Value::Short(vec![1])), + (t::PHOTOMETRIC, Value::Short(vec![photometric::LINEAR_RAW])), + (t::COMPRESSION, Value::Short(vec![1])), + ] { + raw.set(tag, value); + } + for (tag, value) in extra { + raw.set(*tag, value.clone()); + } + raw.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![(0u16..48).flat_map(u16::to_le_bytes).collect()] }); + TiffWriter::new(ByteOrder::Little, false).write(&[raw]).unwrap() +} + +#[test] +fn dng_and_generic_cfa_tiff_report_actual_level_sources_instead_of_unknown() { + for format in [RawFormat::Dng, RawFormat::CfaTiff] { + let missing = decode_as(&linear(&[]), Mode::Full, format, &Limits::default()).unwrap(); + assert_eq!(missing.level_sources, LevelSources { black: LevelSource::Fallback, white: LevelSource::Fallback }); + let declared = decode_as( + &linear(&[(t::BLACK_LEVEL, Value::Short(vec![17])), (t::WHITE_LEVEL, Value::Short(vec![1000]))]), + Mode::Full, + format, + &Limits::default(), + ) + .unwrap(); + assert_eq!(declared.level_sources, LevelSources { black: LevelSource::Metadata, white: LevelSource::Metadata }); + assert_eq!(declared.black.values, vec![17.]); + assert_eq!(declared.white, vec![1000.]); + let invalid = decode_as( + &linear(&[(t::BLACK_LEVEL, Value::Double(vec![f64::NAN])), (t::WHITE_LEVEL, Value::Double(vec![f64::INFINITY]))]), + Mode::Full, + format, + &Limits::default(), + ) + .unwrap(); + assert_eq!(invalid.level_sources, LevelSources { black: LevelSource::Fallback, white: LevelSource::Fallback }); + } + let table = decode_as(&linear(&[(t::LINEARIZATION_TABLE, Value::Short(vec![0, 1000]))]), Mode::Full, RawFormat::Dng, &Limits::default()).unwrap(); + assert_eq!(table.white, vec![1000.]); + assert_eq!(table.level_sources.white, LevelSource::Metadata); +} + +#[test] +fn decoded_notices_record_actual_crop_gain_table_and_cfa_decisions() { + let plain = decode_as(&linear(&[]), Mode::Full, RawFormat::Dng, &Limits::default()).unwrap(); + assert_eq!(plain.notices, RawNotices::default()); + let adjusted = decode_as( + &linear(&[(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![7, 0])), (t::DEFAULT_CROP_SIZE, Value::Long(vec![5, 4]))]), + Mode::Full, + RawFormat::Dng, + &Limits::default(), + ) + .unwrap(); + assert_eq!(adjusted.crop, Rect::new(7, 0, 1, 4)); + assert!(adjusted.notices.default_crop_adjusted); + let invalid_gain = + decode_as(&linear(&[(t::PROFILE_GAIN_TABLE_MAP, Value::Undefined(vec![0; 16]))]), Mode::Full, RawFormat::Dng, &Limits::default()).unwrap(); + assert!(invalid_gain.notices.gain_table_omitted); + assert!(invalid_gain.color.profile.gain_table_map.is_none()); + let assumed = + decode_as(&linear(&[(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA]))]), Mode::Full, RawFormat::CfaTiff, &Limits::default()).unwrap(); + assert!(assumed.notices.assumed_cfa); + assert_eq!(assumed.cfa.as_ref().unwrap().pattern, vec![0, 1, 1, 2]); + let tagged = decode_as( + &linear(&[(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])), (t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2]))]), + Mode::Full, + RawFormat::Dng, + &Limits::default(), + ) + .unwrap(); + assert!(!tagged.notices.assumed_cfa); + let limits = Limits { max_samples: 47, ..Default::default() }; + assert!(matches!(decode_as(&linear(&[]), Mode::Full, RawFormat::Dng, &limits), Err(RawError::Limit(_)))); +} diff --git a/crates/raw/src/dng/probe_review_tests.rs b/crates/raw/src/dng/probe_review_tests.rs new file mode 100644 index 000000000..8e54e8db6 --- /dev/null +++ b/crates/raw/src/dng/probe_review_tests.rs @@ -0,0 +1,64 @@ +use super::*; +use craft_tiff::{IfdBuilder, ImageData, TiffWriter}; + +#[allow(clippy::unwrap_used)] // Test fixture construction must fail the test if its independent writer fails. +fn plain() -> Vec<u8> { + let mut raw = IfdBuilder::new(); + for (tag, value) in [ + (t::IMAGE_WIDTH, Value::Long(vec![2])), + (t::IMAGE_LENGTH, Value::Long(vec![2])), + (t::BITS_PER_SAMPLE, Value::Short(vec![16])), + (t::SAMPLES_PER_PIXEL, Value::Short(vec![1])), + (t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])), + (t::COMPRESSION, Value::Short(vec![1])), + (t::AS_SHOT_NEUTRAL, Value::Rational(vec![(1, 2), (1, 1), (2, 3)])), + ] { + raw.set(tag, value); + } + raw.set_image(ImageData::Strips { rows_per_strip: 2, strips: vec![[17u16, 31, 53, 79].into_iter().flat_map(u16::to_le_bytes).collect()] }); + TiffWriter::new(ByteOrder::Little, false).write(&[raw]).unwrap() +} + +#[allow(clippy::unwrap_used)] // Only known tags in this module's synthetic TIFF are inspected. +fn entry(bytes: &[u8], tag: u16) -> usize { + let at = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize; + let count = u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap()) as usize; + (0..count).map(|i| at + 2 + i * 12).find(|&i| u16::from_le_bytes(bytes[i..i + 2].try_into().unwrap()) == tag).unwrap() +} + +#[test] +fn plain_cfa_probe_keeps_malformed_geometry_and_tables_in_the_supported_decoder() { + let valid = plain(); + assert_eq!(crate::probe(&valid), Some(RawFormat::CfaTiff)); + let decoded = crate::decode(&valid).unwrap(); + assert_eq!(decoded.data, RawData::U16(vec![17, 31, 53, 79])); + for tag in [t::IMAGE_WIDTH, t::IMAGE_LENGTH] { + let mut damaged = valid.clone(); + let at = entry(&damaged, tag); + damaged[at + 8..at + 12].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(crate::probe(&damaged), Some(RawFormat::CfaTiff)); + assert!(matches!(crate::probe_info(&damaged), Err(RawError::Tiff(_))), "zero geometry remains malformed before pixel decode"); + assert!(matches!(crate::decode(&damaged), Err(RawError::Tiff(_)))); + } + let mut missing = valid.clone(); + let at = entry(&missing, t::STRIP_OFFSETS); + missing[at..at + 2].copy_from_slice(&0xf123u16.to_le_bytes()); + assert_eq!(crate::probe(&missing), Some(RawFormat::CfaTiff)); + assert!(matches!(crate::probe_info(&missing), Err(RawError::Tiff(_)))); + assert!(matches!(crate::decode(&missing), Err(RawError::Tiff(_)))); +} + +#[test] +fn plain_cfa_probe_does_not_claim_unknown_tiff_codings_or_missing_color_contracts() { + for tag in [t::AS_SHOT_NEUTRAL, t::COMPRESSION] { + let mut unknown = plain(); + let at = entry(&unknown, tag); + if tag == t::COMPRESSION { + unknown[at + 8..at + 10].copy_from_slice(&65000u16.to_le_bytes()); + } else { + unknown[at..at + 2].copy_from_slice(&0xf123u16.to_le_bytes()); + } + assert_eq!(crate::probe(&unknown), Some(RawFormat::OtherTiff)); + assert!(matches!(crate::decode(&unknown), Err(RawError::Unsupported(_)))); + } +} diff --git a/crates/raw/src/dngwrite.rs b/crates/raw/src/dngwrite.rs index d7f6cdedd..8953f94ea 100644 --- a/crates/raw/src/dngwrite.rs +++ b/crates/raw/src/dngwrite.rs @@ -462,6 +462,7 @@ mod tests { cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: crate::RawNotices::default(), }; let opts = |tile: u32| DngWriteOptions { compression: DngCompression::Deflate { tile, half: false }, ..DngWriteOptions::default() }; let hostile = write_dng(&raw, &opts(u32::MAX)).expect("the clamped tile writes"); diff --git a/crates/raw/src/erf.rs b/crates/raw/src/erf.rs index 40190ca20..fcdfa43cd 100644 --- a/crates/raw/src/erf.rs +++ b/crates/raw/src/erf.rs @@ -128,6 +128,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma cinema: Default::default(), lens_metadata: Default::default(), level_sources: crate::LevelSources { black: black_source, white: white_source }, + notices: crate::RawNotices::default(), pixel_aspect: 1.0, }; img.validate_for(mode)?; diff --git a/crates/raw/src/kodak.rs b/crates/raw/src/kodak.rs index bd517225c..0af4404f1 100644 --- a/crates/raw/src/kodak.rs +++ b/crates/raw/src/kodak.rs @@ -121,6 +121,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: crate::RawNotices::default(), }; img.validate_for(mode)?; Ok(img) diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index dbcf6f953..602ec29b4 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -997,6 +997,20 @@ pub struct ColorData { pub kelvin_presets: Option<kelvin::KelvinPresets>, } +/// Bounded diagnostics for decisions actually made by a raw decoder. An absent optional tag +/// does not itself set a notice; hosts can translate these flags into their own warning text +/// without inferring a fallback from missing metadata or retaining source-controlled strings. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct RawNotices { + /// Explicit default-crop metadata needed correction or a fallback to the active area. + pub default_crop_adjusted: bool, + /// A source profile gain table could not be used and was omitted from the decoded image. + pub gain_table_omitted: bool, + /// The CFA layout was selected by a decoder fallback instead of usable source metadata. + pub assumed_cfa: bool, +} + /// A decoded raw image. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RawImage { @@ -1041,6 +1055,9 @@ pub struct RawImage { /// measured levels are placeholders. #[serde(default)] pub level_sources: LevelSources, + /// Fixed-size decoder decisions, separate from ordinary missing optional metadata. + #[serde(default)] + pub notices: RawNotices, } impl RawImage { @@ -1173,3 +1190,21 @@ mod checked_arithmetic_tests { assert_eq!(Orientation::from_exif(9), Orientation::Normal); } } + +#[cfg(test)] +mod raw_notices_tests { + use super::*; + + #[test] + fn missing_notices_default_to_no_claims_and_explicit_flags_are_independent() { + type Error = serde::de::value::Error; + let empty = serde::de::value::MapDeserializer::<_, Error>::new(std::iter::empty::<(&str, bool)>()); + assert_eq!(RawNotices::deserialize(empty).unwrap(), RawNotices::default()); + let one = serde::de::value::MapDeserializer::<_, Error>::new([("assumed_cfa", true)].into_iter()); + let notices = RawNotices::deserialize(one).unwrap(); + let copied = notices; + assert_eq!(notices, copied); + assert_eq!(notices, RawNotices { assumed_cfa: true, default_crop_adjusted: false, gain_table_omitted: false }); + assert!(!std::mem::needs_drop::<RawNotices>(), "decoder notices own no allocated strings"); + } +} diff --git a/crates/raw/src/mef.rs b/crates/raw/src/mef.rs index 5cd1fb705..36ba18e0f 100644 --- a/crates/raw/src/mef.rs +++ b/crates/raw/src/mef.rs @@ -128,6 +128,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma cinema: Default::default(), lens_metadata: Default::default(), level_sources: crate::LevelSources { black: crate::LevelSource::Fallback, white: white_source }, + notices: crate::RawNotices::default(), pixel_aspect: 1.0, }; img.validate_for(mode)?; diff --git a/crates/raw/src/mrw.rs b/crates/raw/src/mrw.rs index 7fcea21b7..8296b066a 100644 --- a/crates/raw/src/mrw.rs +++ b/crates/raw/src/mrw.rs @@ -170,6 +170,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma cinema: Default::default(), lens_metadata: Default::default(), level_sources: crate::LevelSources { black: crate::LevelSource::Fallback, white: white_source }, + notices: crate::RawNotices::default(), pixel_aspect: 1.0, }; img.validate_for(mode)?; diff --git a/crates/raw/src/nef.rs b/crates/raw/src/nef.rs index bd880ebb8..83c3e0b21 100644 --- a/crates/raw/src/nef.rs +++ b/crates/raw/src/nef.rs @@ -13,7 +13,7 @@ //! refused. use crate::nefc; -use crate::shared::white_from_data; +use crate::shared::white_from_data_sourced; use crate::tiffraw::{Packing, check_image, read_image}; use crate::{BlackLevel, Camera, Cfa, ColorData, Limits, Mode, OpcodeLists, Orientation, RawData, RawError, RawFormat, RawImage, Rect, Result}; use craft_tiff::image::ImageInfo; @@ -266,35 +266,44 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma // D7500 and Z 50 store 600 / 1008 / 400 / 400 / 1008 while their darkest samples are 150 / ~252 / 99 / 99 / ~250 // (our measurements on CC0 raw.pixls.us samples; the same bodies' 14-bit files match the tag as is). let black_scale = if bits == 12 { 0.25 } else { 1.0 }; - let black = match mn.as_ref().and_then(|m| m.ifd.f64s(BLACK_LEVEL)).as_deref() { - Some([a, b, c, d]) if [a, b, c, d].iter().all(|v| **v < 16384.0) => BlackLevel { - repeat_rows: 2, - repeat_cols: 2, - values: [a, b, c, d].iter().map(|v| (**v * black_scale) as f32).collect(), - ..Default::default() + let (black, black_source) = match mn.as_ref().and_then(|m| m.ifd.f64s(BLACK_LEVEL)).as_deref() { + Some([a, b, c, d]) if [a, b, c, d].iter().all(|v| **v < 16384.0) => ( + BlackLevel { + repeat_rows: 2, + repeat_cols: 2, + values: [a, b, c, d].iter().map(|v| (**v * black_scale) as f32).collect(), + ..Default::default() + }, + crate::LevelSource::Metadata, + ), + _ => match nrw_black(mn.as_ref(), bits) { + Some(value) => (BlackLevel::uniform(value), crate::LevelSource::Metadata), + None => { + let (value, source) = be16_black(&info, bytes.len() as u64, mn.as_ref(), samples); + (BlackLevel::uniform(value), source) + } }, - _ => BlackLevel::uniform(nrw_black(mn.as_ref(), bits).unwrap_or_else(|| be16_black(&info, bytes.len() as u64, mn.as_ref(), samples))), }; let wb = mn .as_ref() .and_then(|m| m.ifd.f64s(WB_RB_LEVELS)) .filter(|v| v.len() >= 2 && v[0] > 0.1 && v[1] > 0.1 && v[0] < 10.0 && v[1] < 10.0) .map(|v| [v[0] as f32, 1.0, v[1] as f32]); - let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { + let (cfa, assumed_cfa) = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => { - Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: 0 } + (Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: 0 }, false) } - _ => Cfa::bayer_static("RGGB"), + _ => (Cfa::bayer_static("RGGB"), true), }; let model = ifd0.string(t::MODEL).unwrap_or_default(); let body = measured_body(&model, w, h, bits); let active_w = trailing_masked_columns(samples, w, bits); // the white level is measured from the whole image (or known for a measured body); the probe (no samples in its // result) takes the nominal one - let white = match (body.and_then(|b| b.white), mode) { - (Some(white), _) => white, - (None, Mode::Full) => white_from_data(samples, bits), - (None, Mode::Header) => ((1u32 << bits.clamp(1, 16)) - 1) as f32, + let (white, white_source) = match (body.and_then(|b| b.white), mode) { + (Some(white), _) => (white, crate::LevelSource::Fallback), + (None, Mode::Full) => white_from_data_sourced(samples, bits), + (None, Mode::Header) => (((1u32 << bits.clamp(1, 16)) - 1) as f32, crate::LevelSource::Fallback), }; let crop = match body { Some(&MeasuredBody { crop: (x, y, cw, ch), .. }) if x + cw <= active_w && y + ch <= h => Rect::new(x, y, cw, ch), @@ -329,7 +338,8 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma camera: tiff.ifds.first().map(Camera::from_ifd0).unwrap_or_default(), cinema: Default::default(), lens_metadata: Default::default(), - level_sources: Default::default(), + level_sources: crate::LevelSources { black: black_source, white: white_source }, + notices: crate::RawNotices { assumed_cfa, ..Default::default() }, }; img.validate_for(mode)?; Ok(img) @@ -378,8 +388,8 @@ fn uncompressed( #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum PackedLayout { /// LSB-first bit stream of `bits` per sample (12: 3 bytes per 2 samples, 14: 7 bytes per 4), rows byte aligned. - /// 12-bit rows are `3w/2` bytes (older bodies) or padded to 16 bytes (Z 6, D6); 14-bit rows are `7w/4` bytes - /// padded to 16 bytes. + /// Rows use `ceil(bits * width / 8)` bytes, optionally padded to 16 bytes. Without an explicit packed maker + /// mode, recognition requires complete sample groups and 14-bit rows padded to 16 bytes. Lsb { stride: usize }, /// D100: 16-byte chunks of fifteen data bytes holding ten MSB-first 12-bit samples, plus one zero pad byte. The /// rows carry more samples than the IFD width (3040 against 3034); the extra columns are not image. @@ -399,7 +409,11 @@ fn packed_layout(w: usize, h: usize, bits: u32, strip: u64, stated: bool) -> Opt } let stride = strip / h; let tight = w.checked_mul(bits as usize)?.div_ceil(8); - let tight = if bits == 12 && w.is_multiple_of(2) || bits == 14 && w.is_multiple_of(4) { tight } else { return None }; + // Unmarked data must still match a measured complete-group layout: do not guess a packing for compressed + // data. An explicit packed maker mode permits a final partial group, byte-aligned independently on each row. + if !stated && !(bits == 12 && w.is_multiple_of(2) || bits == 14 && w.is_multiple_of(4)) { + return None; + } let padded = tight.checked_next_multiple_of(16)?; let lsb_ok = match bits { 12 => stride == tight || stride == padded, @@ -436,14 +450,14 @@ fn be16_layout(w: usize, h: usize, bits: u32, strip: u64) -> Option<PackedLayout /// 223), and the other 12-bit Coolpix NRWs state 200 in their NRW block; so 200, never above the darkest sample. const BE16_BLACK: f32 = 200.0; -fn be16_black(info: &ImageInfo, file_len: u64, mn: Option<&makernote::MakerNote>, samples: &[u16]) -> f32 { +fn be16_black(info: &ImageInfo, file_len: u64, mn: Option<&makernote::MakerNote>, samples: &[u16]) -> (f32, crate::LevelSource) { let has_table = mn.is_some_and(|m| m.ifd.bytes(LINEARIZATION_TABLE).is_some()); let single = matches!(info.chunks(file_len).as_slice(), [c] if be16_layout(info.width as usize, info.height as usize, info.bits() as u32, c.len).is_some()); if info.compression != t::compression::NIKON || has_table || info.samples_per_pixel != 1 || !single { - return 0.0; + return (0.0, crate::LevelSource::Fallback); } let darkest = samples.iter().copied().min().unwrap_or(0); - BE16_BLACK.min(f32::from(darkest)) + (BE16_BLACK.min(f32::from(darkest)), crate::LevelSource::Inferred) } /// Unpack a [`PackedLayout`] strip into `w * h` samples. Short input leaves the missing samples zero. @@ -524,7 +538,7 @@ fn compressed(bytes: &[u8], info: &ImageInfo, mn: Option<&makernote::MakerNote>, } /// A "compressed" strip of packed samples: the strip size must match a measured layout exactly. `stated` is set -/// when the maker note names the packed mode, which also allows 14-bit rows without padding. +/// when the maker note names the packed mode, which also allows partial groups and 14-bit rows without padding. fn packed(bytes: &[u8], info: &ImageInfo, rows: usize, stated: bool, limits: &Limits) -> Result<RawData> { let (w, h) = (info.width as usize, info.height as usize); let bits = info.bits() as u32; @@ -663,6 +677,7 @@ fn small_raw(bytes: &[u8], tiff: &Tiff, info: &ImageInfo, strip: craft_tiff::ima cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: Default::default(), }; img.validate_for(mode)?; Ok(img) @@ -725,36 +740,53 @@ mod tests { TiffWriter::new(order, false).write(&[ifd0]).unwrap() } + #[test] + fn level_provenance_distinguishes_missing_black_from_recorded_black() { + let strip: Vec<u8> = [1000u16; 16].into_iter().flat_map(u16::to_be_bytes).collect(); + let fallback = nef(1, 12, vec![strip.clone()], 4, 4, 4); + let mut note = IfdBuilder::new(); + note.set(BLACK_LEVEL, Value::Short(vec![400; 4])); + let recorded = nef_with_note(1, 12, vec![strip], 4, 4, 4, Some(note)); + for mode in [Mode::Header, Mode::Full] { + let missing = decode(&fallback, mode, &Limits::default()).unwrap(); + assert_eq!((missing.black.mean(), missing.level_sources.black), (0.0, crate::LevelSource::Fallback)); + let stated = decode(&recorded, mode, &Limits::default()).unwrap(); + assert_eq!((stated.black.mean(), stated.level_sources.black), (100.0, crate::LevelSource::Metadata)); + } + } + + /// A small uncompressed NEF with a real NikonNEFInfo TIFF block, without binary fixtures. + fn nikon_distortion_file(model: &str, mode: u8) -> Vec<u8> { + use crate::nef_lens::tests::{distortion_block, nef_info_blob, offset_block}; + let (w, h) = (48u32, 32u32); + let words: Vec<u8> = (0..w * h).flat_map(|i| (600 + (i % 97) as u16 * 50).to_be_bytes()).collect(); + let mut raw = IfdBuilder::new(); + raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![14])); + raw.set(t::COMPRESSION, Value::Short(vec![1])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + let info = nef_info_blob(&[ + (0x0005, distortion_block(mode, 21.6, 4, [0.039895, 0.019211, -0.127218], -0.025043)), + (0x0008, offset_block(1.5, -0.75)), + ]); + raw.set(0xc7d5, Value::Undefined(info)); + raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![words] }); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("NIKON CORPORATION".into())); + ifd0.set(t::MODEL, Value::Ascii(model.into())); + ifd0.add_sub_ifd(raw); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() + } + /// A Z 6II NEF carrying NikonNEFInfo gets Nikon's distortion correction as one warp, in the header probe and /// the full decode alike, and keeps it through DNG export; another body with the same data gets none. #[test] fn nikon_in_file_distortion_becomes_a_warp() { - use crate::nef_lens::tests::{distortion_block, nef_info_blob, offset_block}; - let (w, h) = (48u32, 32u32); - let file = |model: &str| { - let words: Vec<u8> = (0..w * h).flat_map(|i| (600 + (i % 97) as u16 * 50).to_be_bytes()).collect(); - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); - raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![14])); - raw.set(t::COMPRESSION, Value::Short(vec![1])); - raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); - raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); - raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); - let info = nef_info_blob(&[ - (0x0005, distortion_block(3, 21.6, 4, [0.039895, 0.019211, -0.127218], -0.025043)), - (0x0008, offset_block(1.5, -0.75)), - ]); - raw.set(0xc7d5, Value::Undefined(info)); - raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![words] }); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("NIKON CORPORATION".into())); - ifd0.set(t::MODEL, Value::Ascii(model.into())); - ifd0.add_sub_ifd(raw); - TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() - }; - let bytes = file("NIKON Z 6_2"); + let bytes = nikon_distortion_file("NIKON Z 6_2", 3); let header = decode(&bytes, Mode::Header, &Limits::default()).unwrap(); let full = decode(&bytes, Mode::Full, &Limits::default()).unwrap(); assert_eq!(header.info(), full.info()); @@ -767,7 +799,19 @@ mod tests { let dng = crate::write_dng(&full, &Default::default()).unwrap(); assert_eq!(crate::decode(&dng).unwrap().opcodes.list3, full.opcodes.list3); } - assert!(decode(&file("NIKON D850"), Mode::Full, &Limits::default()).unwrap().opcodes.list3.is_empty()); + assert!(decode(&nikon_distortion_file("NIKON D850", 3), Mode::Full, &Limits::default()).unwrap().opcodes.list3.is_empty()); + } + + /// Off, no-lens and unrecognized modes must not create a source correction through either public path. + #[test] + fn nikon_distortion_modes_are_respected_by_probe_and_full_decode() { + for mode in [0, 1, 2, 3, 4, 128, 255] { + let bytes = nikon_distortion_file("NIKON Z 6_2", mode); + let header = crate::probe_info(&bytes).unwrap(); + let full = crate::decode(&bytes).unwrap(); + assert_eq!(header, full.info(), "mode {mode}: header/full agreement"); + assert_eq!(!header.opcodes.list3.is_empty(), matches!(mode, 1 | 3), "mode {mode}"); + } } #[test] @@ -1513,4 +1557,95 @@ mod tests { } } } + + mod partial_row_tests { + use super::*; + + // Independent wire oracle: place each sample bit directly, leaving nonzero tail bits and padding. + fn image(data: &[u16], w: usize, bits: u32, padded: bool) -> Vec<u8> { + let tight = (w * bits as usize).div_ceil(8); + let stride = if padded { tight.next_multiple_of(16) } else { tight }; + let mut bytes = vec![0xA5; stride * (data.len() / w)]; + for (i, &sample) in data.iter().enumerate() { + for bit in 0..bits as usize { + let at = (i % w) * bits as usize + bit; + let byte = &mut bytes[(i / w) * stride + at / 8]; + *byte = (*byte & !(1 << (at % 8))) | (((sample >> bit) as u8 & 1) << (at % 8)); + } + } + bytes + } + + fn note(order: ByteOrder, modern: bool, mode: u16) -> IfdBuilder { + let mut n = IfdBuilder::new(); + if modern { + let mut record = b"01000400\0\0".to_vec(); + record.extend(if order == ByteOrder::Big { mode.to_be_bytes() } else { mode.to_le_bytes() }); + n.set(NEF_COMPRESSION_RECORD, Value::Undefined(record)); + } else { + n.set(NEF_COMPRESSION, Value::Short(vec![mode])); + } + n + } + + #[test] + fn declared_packed_partial_rows_preserve_every_sample() { + let h = 5; + for (bits, mode) in [(12u32, 6), (14, 10)] { + for w in [1, 3, 5, 22, 23] { + let data = samples(w * h, bits); + for padded in [false, true] { + let wire = image(&data, w, bits, padded); + if w == 22 && bits == 14 { + assert_eq!(wire.len() / h, if padded { 48 } else { 39 }); + } + for order in [ByteOrder::Big, ByteOrder::Little] { + for modern in [false, true] { + let file = nef_in( + order, + 34713, + bits as u16, + vec![wire.clone()], + w as u32, + h as u32, + h as u32, + Some(note(order, modern, mode)), + ); + let raw = crate::decode(&file).unwrap(); + assert_eq!((raw.width, raw.height, raw.cpp), (w, h, 1)); + assert!(!raw.notices.assumed_cfa, "valid CFA tag is retained"); + let RawData::U16(got) = raw.data else { panic!("integer samples") }; + assert_eq!(got, data, "{bits}-bit width {w}, padded {padded}, {order:?}, modern {modern}"); + } + } + } + } + } + } + + #[test] + fn partial_rows_keep_mode_depth_and_strip_guards() { + let (w, h) = (22, 5); + let data = samples(w * h, 14); + for padded in [false, true] { + let wire = image(&data, w, 14, padded); + let file = |bytes, mode: Option<u16>| { + nef_with_note(34713, 14, vec![bytes], w as u32, h as u32, h as u32, mode.map(|m| note(ByteOrder::Big, false, m))) + }; + for mode in [None, Some(0), Some(6), Some(13), Some(14)] { + assert!(matches!(crate::decode(&file(wire.clone(), mode)), Err(RawError::Unsupported(_))), "mode {mode:?}"); + } + let good = file(wire.clone(), Some(10)); + assert!(crate::decode(&good).is_ok()); + let short = truncated_tail_strip(good, wire.len() - 1); + assert!(matches!(crate::decode(&short), Err(RawError::Corrupt(_)))); + for len in [wire.len() - 1, wire.len() + 1] { + assert!(matches!(crate::decode(&file(vec![0; len], Some(10))), Err(RawError::Unsupported(_)))); + } + } + for (w, h, bits) in [(0, 5, 14), (22, 0, 14), (22, 5, 13), (usize::MAX, 5, 14)] { + assert!(packed_layout(w, h, bits, u64::MAX, true).is_none()); + } + } + } } diff --git a/crates/raw/src/nef_lens.rs b/crates/raw/src/nef_lens.rs index 9f8dafb0e..a6c667324 100644 --- a/crates/raw/src/nef_lens.rs +++ b/crates/raw/src/nef_lens.rs @@ -15,7 +15,7 @@ const DISTORTION_INFO: u16 = 0x0005; const CENTRE_OFFSET: u16 = 0x0008; /// Bodies whose files were checked against the camera's JPEG (docs/nikon-lens-corrections.md). Matching tags on /// another body do not establish its pixel pitch or image area; add a body only after checking its files. -const VALIDATED: &[&str] = &["NIKON Z 6_2", "NIKON Z 8", "NIKON Z f"]; +const VALIDATED: &[&str] = &["NIKON Z 6", "NIKON Z 7", "NIKON Z 6_2", "NIKON Z 8", "NIKON Z f"]; /// The normalisation radius every checked file stores: the FX half-diagonal in millimetres. const FX_HALF_DIAGONAL_MM: f64 = 21.6; const SAMPLES: usize = 256; @@ -45,10 +45,10 @@ fn nef_info(raw: &Ifd) -> Option<(Ifd, ByteOrder)> { Some((ifd, order)) } -/// DistortionInfo: `"0100"`, the correction mode (0 none), the normalisation radius (mm) at 8, the term count (4) -/// at 16, the coefficients at 20 / 28 / 36 and the zoom at 64, each a signed rational. +/// DistortionInfo: `"0100"`, mode (1 optional on, 3 required on; 0 no lens, 2 off), radius (mm) at 8, +/// term count (4) at 16, coefficients at 20 / 28 / 36 and zoom at 64, each a signed rational. fn distortion_info(b: &[u8], order: ByteOrder) -> Option<Distortion> { - if b.get(0..4)? != b"0100" || *b.get(4)? == 0 { + if b.get(0..4)? != b"0100" || !matches!(*b.get(4)?, 1 | 3) { return None; } let norm = rational(b, 8, order)?; @@ -222,15 +222,20 @@ pub(crate) mod tests { #[test] fn refuses_unvalidated_bodies_and_unknown_layouts() { let good = distortion_block(3, 21.6, 4, WIDE.0, WIDE.1); - assert!(warp("NIKON Z 6_2", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); + for model in ["NIKON Z 6", "NIKON Z 7", "NIKON Z 6_2"] { + assert!(warp(model, &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some(), "{model}"); + } assert!(warp("NIKON Z f", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); assert!(warp("NIKON Z 8", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); - for model in ["", "NIKON Z 6", "NIKON Z 6_3", "NIKON Z 9", "NIKON D850", "NIKON Z 6_2 x"] { + for model in ["", "NIKON Z 7_2", "NIKON Z 6_3", "NIKON Z 9", "NIKON D850", "NIKON Z 6_2 x"] { assert!(warp(model, &raw_with(&[(DISTORTION_INFO, good.clone())])).is_none(), "{model}"); } // correction off, a DX radius, another term count, a wild coefficient or zoom, no NEFInfo at all for bad in [ distortion_block(0, 21.6, 4, WIDE.0, WIDE.1), + distortion_block(2, 21.6, 4, WIDE.0, WIDE.1), + distortion_block(4, 21.6, 4, WIDE.0, WIDE.1), + distortion_block(255, 21.6, 4, WIDE.0, WIDE.1), distortion_block(3, 14.2, 4, WIDE.0, WIDE.1), distortion_block(3, 21.6, 3, WIDE.0, WIDE.1), distortion_block(3, 21.6, 4, [0.0, 0.0, 1.5], 0.0), diff --git a/crates/raw/src/orf.rs b/crates/raw/src/orf.rs index ebfa28eb2..566e56fed 100644 --- a/crates/raw/src/orf.rs +++ b/crates/raw/src/orf.rs @@ -207,6 +207,19 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma let info = ifd0.image()?; let (w, h) = (info.width as usize, info.height as usize); let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= limits.samples()).ok_or(RawError::Limit("image too large"))?; + // A partial TIFF directory is damage, not evidence of an unsupported compressed layout. + // Do not infer packing from an absent strip table or from clipped sensor bytes. + if info.compression == 1 + && (info.offsets.is_empty() + || info.offsets.len() != info.byte_counts.len() + || info + .offsets + .iter() + .zip(&info.byte_counts) + .any(|(&at, &len)| len == 0 || at.checked_add(len).is_none_or(|end| end > bytes.len() as u64))) + { + return Err(RawError::Corrupt("ORF strip table is missing or outside file".into())); + } let chunks = info.chunks(bytes.len() as u64); let total = chunks.iter().fold(0u64, |a, c| a.saturating_add(c.len)); let stated = cfa_from_exif(&tiff); @@ -302,6 +315,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma } _ => Rect::new(0, 0, w, h), }; + let assumed_cfa = stated.is_none(); let cfa = stated.unwrap_or_else(|| cfa_from_data(samples, w, active)); let (black, black_source) = match ip.as_ref().and_then(|i| i.f64s(BLACK)).as_deref() { Some(v @ [_, _, _, _]) => { @@ -348,6 +362,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma camera: tiff.ifds.first().map(Camera::from_ifd0).unwrap_or_default(), cinema: Default::default(), lens_metadata: Default::default(), + notices: crate::RawNotices { assumed_cfa, ..Default::default() }, level_sources: crate::LevelSources { black: black_source, white: white_source }, }; img.validate_for(mode)?; @@ -416,6 +431,34 @@ mod tests { } } + #[test] + fn truncated_uncompressed_directory_and_strip_are_corrupt_not_compressed() { + let mut bytes = orf_with(4, 4, 16, vec![0; 32], Some(&[2, 0, 2, 0, 0, 1, 1, 2])); + // TiffWriter puts image chunks before its directory/metadata, so EOF is not a + // required sensor byte. Relocate the declared strip to EOF without changing it. + let directory = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize; + let count = u16::from_le_bytes(bytes[directory..directory + 2].try_into().unwrap()) as usize; + let entry = (0..count) + .map(|i| directory + 2 + i * 12) + .find(|&at| u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap()) == t::STRIP_OFFSETS) + .unwrap(); + let old_offset = u32::from_le_bytes(bytes[entry + 8..entry + 12].try_into().unwrap()) as usize; + let pixels = bytes[old_offset..old_offset + 32].to_vec(); + let offset = bytes.len(); + bytes.extend(pixels); + bytes[entry + 8..entry + 12].copy_from_slice(&(offset as u32).to_le_bytes()); + assert!(crate::decode(&bytes).is_ok()); + for cut in 0..bytes.len() { + for result in [crate::decode(&bytes[..cut]).map(|_| ()), crate::probe_info(&bytes[..cut]).map(|_| ())] { + assert!(!matches!(result, Err(RawError::Unsupported(ref why)) if why.contains("compressed")), "cut {cut}: {result:?}"); + } + } + let result = crate::decode(&bytes[..bytes.len() - 1]); + assert!(matches!(result, Err(RawError::Corrupt(_))), "required final strip byte missing: {result:?}"); + let result = crate::probe_info(&bytes[..bytes.len() - 1]); + assert!(matches!(result, Err(RawError::Corrupt(_))), "required final strip byte missing during probe: {result:?}"); + } + /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow. #[test] fn strip_byte_counts_past_u64_max_do_not_overflow() { @@ -627,6 +670,28 @@ mod tests { } } + #[test] + fn cfa_notice_distinguishes_missing_and_unusable_exif_from_stated_patterns() { + let (w, h) = (160usize, 144usize); + let strip = mosaic(w, h, |cx, cy| [600, 1000, 1000, 300].map(|value| value + shade(cx, cy))); + let expected: Vec<u16> = strip.as_chunks::<2>().0.iter().map(|word| u16::from_le_bytes(*word)).collect(); + for (tag, assumed, pattern) in [ + (None, true, "RGGB"), + (Some(&[2, 0, 2, 0, 0, 1][..]), true, "RGGB"), + (Some(&[2, 0, 2, 0, 0, 1, 1, 3][..]), true, "RGGB"), + (Some(BGGR), false, "BGGR"), + (Some(GRBG), false, "GRBG"), + ] { + let bytes = orf_with(w as u32, h as u32, 16, strip.clone(), tag); + for mode in [Mode::Header, Mode::Full] { + let image = decode(&bytes, mode, &Limits::default()).unwrap(); + assert_eq!(image.cfa, Some(Cfa::bayer_static(pattern))); + assert_eq!(image.data, RawData::U16(expected.clone()), "word16 samples remain unchanged"); + assert_eq!(image.notices, crate::RawNotices { assumed_cfa: assumed, ..Default::default() }); + } + } + } + #[test] fn packed_12_bit_probe_agrees_with_decode() { let (w, h) = (16usize, 4usize); diff --git a/crates/raw/src/pef.rs b/crates/raw/src/pef.rs index a33750db5..9dc3a89f1 100644 --- a/crates/raw/src/pef.rs +++ b/crates/raw/src/pef.rs @@ -194,6 +194,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma Some(r) => r, None => dark_trimmed(samples, w, hgt, black_point.as_deref().map(|v| v.iter().sum::<f64>() / 4.0), white), }; + let mut assumed_cfa = false; let cfa = match (ifd0.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), ifd0.bytes(t::CFA_PATTERN_EP)) { (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => { Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: 0 } @@ -202,7 +203,10 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma // of the image area: the *ist D (origin 19, 11) and the 645D (80, 59) only fit unshifted. The 12-bit 10 MP // bodies and everything from the K-3 on say RGGB; the K-7 / K-5 / 645D generation says BGGR. Files without the // tag keep BGGR. - _ => cfa_from_exif(&tiff).unwrap_or_else(|| Cfa::bayer_static("BGGR")), + _ => cfa_from_exif(&tiff).unwrap_or_else(|| { + assumed_cfa = true; + Cfa::bayer_static("BGGR") + }), }; let black = match black_point.as_deref() { Some(v @ [_, _, _, _]) => { @@ -240,6 +244,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: crate::RawNotices { assumed_cfa, ..Default::default() }, }; img.validate_for(mode)?; Ok(img) @@ -487,6 +492,47 @@ mod tests { assert_eq!(img.cfa, Some(Cfa::bayer_static("BGGR"))); } + #[test] + fn fixed_cfa_fallback_is_noticed_but_either_usable_metadata_form_is_not_assumed() { + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + let expected: Vec<u16> = (0..16).map(|i| 100 + i * 7).collect(); + let valid_exif = &[2, 0, 2, 0, 1, 0, 2, 1][..]; + let invalid_exif = &[2, 0, 2, 0, 1, 0][..]; + for (primary, exif, assumed, pattern) in [ + (None, None, true, "BGGR"), + (Some([0, 1, 1, 3]), None, true, "BGGR"), + (None, Some(invalid_exif), true, "BGGR"), + (Some([0, 1, 1, 3]), Some(invalid_exif), true, "BGGR"), + (Some([0, 1, 1, 3]), Some(valid_exif), false, "GRBG"), + (None, Some(valid_exif), false, "GRBG"), + (Some([0, 1, 1, 2]), None, false, "RGGB"), + (Some([0, 1, 1, 2]), Some(valid_exif), false, "RGGB"), + ] { + let mut raw = IfdBuilder::new(); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![4])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![4])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![16])); + raw.set(t::COMPRESSION, Value::Short(vec![1])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![32803])); + raw.set(t::MAKE, Value::Ascii("PENTAX Corporation".into())); + if let Some(pattern) = primary { + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(pattern.to_vec())); + } + if let Some(pattern) = exif { + raw.set_child(t::EXIF_IFD, IfdBuilder::new().with(crate::EXIF_CFA_PATTERN, Value::Undefined(pattern.to_vec()))); + } + raw.set_image(ImageData::Strips { rows_per_strip: 4, strips: vec![expected.iter().flat_map(|value| value.to_be_bytes()).collect()] }); + let bytes = TiffWriter::new(ByteOrder::Big, false).write(&[raw]).unwrap(); + for mode in [Mode::Header, Mode::Full] { + let image = decode(&bytes, mode, &Limits::default()).unwrap(); + assert_eq!(image.cfa, Some(Cfa::bayer_static(pattern))); + assert_eq!(image.data, RawData::U16(expected.clone())); + assert_eq!(image.notices, crate::RawNotices { assumed_cfa: assumed, ..Default::default() }); + } + } + } + /// A `w x h` big-endian 14-bit PEF of plain 16-bit words without area tags, whose maker note has only a /// BlackPoint of `black`, with `px(x, y)` as the samples. fn pef_with_black_point(w: usize, h: usize, black: u16, px: impl Fn(usize, usize) -> u16) -> Vec<u8> { diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index 48fa4e4b1..bd66f58c8 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -643,9 +643,15 @@ fn cr3_preview(bytes: &[u8]) -> Option<&[u8]> { /// A CR3's full-size JPEG track, when it holds a DCT JPEG. #[cfg(feature = "cr3")] fn cr3_full_jpeg(bytes: &[u8]) -> Option<&[u8]> { - let full = craft_metadata::cr3::parse_cr3(bytes) - .and_then(|c| c.tracks.iter().find(|t| t.kind == craft_metadata::cr3::Cr3TrackKind::Jpeg).and_then(|t| t.data)); - full.and_then(|(at, len)| bytes.get(at..at.checked_add(len)?)).filter(|j| is_dct_jpeg(j)) + let cr3 = craft_metadata::cr3::parse_cr3(bytes)?; + // An unusable preview track must not hide a later usable one. Share the marker budget + // across candidates so overlapping hostile track ranges cannot cause quadratic walks. + let mut work = CR3_MAX_WALK; + cr3.tracks.iter().filter(|t| t.kind == craft_metadata::cr3::Cr3TrackKind::Jpeg).find_map(|t| { + let (at, len) = t.data?; + let jpeg = bytes.get(at..at.checked_add(len)?)?; + first_frame_within(jpeg, &mut work).filter(|(m, _)| matches!(m, 0xc0..=0xc2)).map(|_| jpeg) + }) } /// Marker-walk budget of the CR3 fallback: candidates can overlap (each claiming the rest of the file) and diff --git a/crates/raw/src/preview/tests.rs b/crates/raw/src/preview/tests.rs index 19018d9b1..e04c8574f 100644 --- a/crates/raw/src/preview/tests.rs +++ b/crates/raw/src/preview/tests.rs @@ -582,7 +582,19 @@ fn cr3_prefers_the_full_size_jpeg_track() { let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); - let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + let trak = bx( + b"trak", + &bx( + b"mdia", + &bx( + b"minf", + &bx( + b"stbl", + &[stsd, full(b"stsc", &[1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>()), stsz, co64].concat(), + ), + ), + ), + ); file.extend(bx(b"moov", &trak)); file.resize(at as usize, 0); file.extend_from_slice(&big); @@ -592,6 +604,48 @@ fn cr3_prefers_the_full_size_jpeg_track() { assert_eq!(embedded_preview(&file).unwrap(), small); } +#[cfg(feature = "cr3")] +#[test] +fn cr3_skips_bad_preview_tracks_but_never_uses_sensor_tracks_as_jpeg() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat()); + let track = |jpeg: bool, at: u64, len: u32| { + let mut entry = vec![0u8; 82]; + if jpeg { + entry.extend(bx(b"JPEG", &[0; 4])); + } + let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &entry)].concat()); + let stsz = full(b"stsz", &[len.to_be_bytes(), 1u32.to_be_bytes()].concat()); + let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); + bx( + b"trak", + &bx( + b"mdia", + &bx( + b"minf", + &bx( + b"stbl", + &[stsd, full(b"stsc", &[1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>()), stsz, co64].concat(), + ), + ), + ), + ) + }; + let good = fake_jpeg(100); + for first in [track(true, u64::MAX, 32), track(true, 4096, 32)] { + let mut bytes = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + bytes.extend(bx(b"moov", &[first, track(true, 4128, good.len() as u32)].concat())); + bytes.resize(4128, 0); + bytes.extend(&good); + assert_eq!(embedded_preview(&bytes).as_deref(), Some(good.as_slice())); + } + let mut bytes = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + bytes.extend(bx(b"moov", &track(false, 4096, good.len() as u32))); + bytes.resize(4096, 0); + bytes.extend(&good); + assert_eq!(embedded_preview(&bytes), None, "a sensor sample is not a rendered preview even if its bytes look like JPEG"); +} + #[cfg(feature = "cr3")] /// A CR3 whose `PRVW` box holds `prvw` and whose JPEG track holds `big`. fn cr3_with(prvw_jpeg: &[u8], big: &[u8]) -> Vec<u8> { @@ -608,7 +662,19 @@ fn cr3_with(prvw_jpeg: &[u8], big: &[u8]) -> Vec<u8> { let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); - let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + let trak = bx( + b"trak", + &bx( + b"mdia", + &bx( + b"minf", + &bx( + b"stbl", + &[stsd, full(b"stsc", &[1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>()), stsz, co64].concat(), + ), + ), + ), + ); file.extend(bx(b"moov", &trak)); file.resize(at as usize, 0); file.extend_from_slice(big); @@ -656,7 +722,19 @@ fn the_smallest_preview_covering_the_size_is_chosen() { let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); - let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + let trak = bx( + b"trak", + &bx( + b"mdia", + &bx( + b"minf", + &bx( + b"stbl", + &[stsd, full(b"stsc", &[1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>()), stsz, co64].concat(), + ), + ), + ), + ); file.extend(bx(b"moov", &trak)); file.resize(at as usize, 0); file.extend_from_slice(&big); @@ -769,7 +847,19 @@ fn a_cr3_with_two_prvw_boxes_offers_both() { let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); - let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + let trak = bx( + b"trak", + &bx( + b"mdia", + &bx( + b"minf", + &bx( + b"stbl", + &[stsd, full(b"stsc", &[1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>()), stsz, co64].concat(), + ), + ), + ), + ); file.extend(bx(b"moov", &trak)); // (the track in the media data, as a camera writes it, after a `free` box up to it) let pad = at as usize - 16 - file.len(); diff --git a/crates/raw/src/raf.rs b/crates/raw/src/raf.rs index f75fa160b..a3e407454 100644 --- a/crates/raw/src/raf.rs +++ b/crates/raw/src/raf.rs @@ -18,7 +18,10 @@ //! - CFA: the X-Trans layout record (36 bytes, 0 = R, 1 = G, 2 = B) is stored in reverse order and, reversed, //! is anchored at raw pixel (0, 0) — verified on X-Trans I and III samples by minimising the difference //! between horizontally / vertically adjacent "green" samples over all 72 orientations/phases, and by colour -//! renders. Bayer bodies (X-A series) use RGGB at (0, 0), verified by colour renders. +//! renders. Bayer FujiLayout (`0x0130`) gives the reversed 2×2 pattern in its low two bits +//! (0 = R, 1/3 = G, 2 = B); absent layout records retain the assumed RGGB fallback. +//! - RawExposureBias (`0x9650`) is a signed big-endian 16-bit fraction; its negative is the +//! baseline exposure used to restore the camera's dynamic-range exposure reduction. //! - Striped predictive compression is decoded by `rafc`; see `docs/raf-compression.md`. use crate::shared::white_from_data_sourced; @@ -87,7 +90,7 @@ fn pair(h: &Header, tag: u16) -> Option<(usize, usize)> { pub(crate) fn raw_ifd(raw: &[u8]) -> Result<Ifd> { let tiff = Tiff::parse(raw).map_err(|_| RawError::Unsupported("RAF without a raw IFD (older FinePix layout)".into()))?; let off = tiff.ifds.first().and_then(|i| i.u64(0xf000)).ok_or_else(|| RawError::Unsupported("RAF without a raw IFD".into()))?; - let (ifd, _) = craft_tiff::parse_ifd_at(raw, off, ByteOrder::Little, 0, false, &Default::default())?; + let (ifd, _) = craft_tiff::parse_ifd_at(raw, off, tiff.order, 0, false, &Default::default())?; Ok(ifd) } @@ -122,14 +125,42 @@ fn camera_name(b: &[u8]) -> String { String::from_utf8_lossy(name.get(..end).unwrap_or_default()).trim().to_string() } -/// The CFA: X-Trans from the (reversed) layout record, else RGGB. -fn cfa(h: &Header) -> Cfa { - match record(h, XTRANS_LAYOUT) { - Some(l) if l.len() == 36 && l.iter().all(|&c| c <= 2) => { - Cfa { width: 6, height: 6, pattern: l.iter().rev().copied().collect(), origin_x: 0, origin_y: 0 } +/// Layout records are reversed and anchored at sensor (0, 0). FujiLayout's low +/// two bits encode Bayer colour; both 1 and 3 denote green. +fn cfa(h: &Header) -> Result<Cfa> { + if let Some(l) = record(h, XTRANS_LAYOUT) { + if l.len() != 36 || l.iter().any(|&c| c > 2) { + return Err(RawError::Unsupported("Fujifilm RAF with an unknown X-Trans layout".into())); } - _ => Cfa::bayer_static("RGGB"), + return Ok(Cfa { width: 6, height: 6, pattern: l.iter().rev().copied().collect(), origin_x: 0, origin_y: 0 }); } + let Some(l) = record(h, 0x0130) else { return Ok(Cfa::bayer_static("RGGB")) }; + let cfa = Cfa { width: 2, height: 2, pattern: l.iter().rev().map(|&c| if c & 3 == 3 { 1 } else { c & 3 }).collect(), origin_x: 0, origin_y: 0 }; + // Colour counts alone also accept adjacent green sites; the two greens + // must occupy opposite corners of the 2x2 Bayer repeat. + if l.len() != 4 || !matches!(cfa.pattern.as_slice(), [0, 1, 1, 2] | [2, 1, 1, 0] | [1, 0, 2, 1] | [1, 2, 0, 1]) { + return Err(RawError::Unsupported("Fujifilm RAF with an unknown Bayer layout".into())); + } + Ok(cfa) +} + +/// Fuji RawExposureBias is a signed big-endian 16-bit fraction, undone like +/// DNG BaselineExposure. Invalid or implausible metadata does not alter exposure. +fn baseline_exposure(h: &Header) -> f64 { + record(h, 0x9650) + .and_then(|d| { + let num = i16::from_be_bytes(d.get(..2)?.try_into().ok()?); + let den = i16::from_be_bytes(d.get(2..4)?.try_into().ok()?); + (den != 0).then(|| -f64::from(num) / f64::from(den)) + }) + .filter(|v| v.is_finite() && v.abs() <= 8.0) + .unwrap_or(0.0) +} + +/// The codec fixes the green-site geometry; exchanging the two non-green +/// planes only exchanges their colour labels, so RGGB and BGGR are both valid. +fn compressed_layout_supported(cfa: &Cfa) -> bool { + *cfa == Cfa::xtrans() || *cfa == Cfa::bayer_static("RGGB") || *cfa == Cfa::bayer_static("BGGR") } /// Unpack one row of `bits`-bit samples in Fujifilm's packing. `words32`: the raw IFD's `0xf006` flag is set, the @@ -137,7 +168,7 @@ fn cfa(h: &Header) -> Cfa { /// LSB-first bit stream, or (other depths) the same 32-bit words. pub(crate) fn unpack_row(src: &[u8], bits: u32, words32: bool, out: &mut [u16]) { match bits { - 16 => out.iter_mut().zip(src.as_chunks::<2>().0).for_each(|(o, c)| *o = u16::from_le_bytes([c[0], c[1]])), + 16 if !words32 => out.iter_mut().zip(src.as_chunks::<2>().0).for_each(|(o, c)| *o = u16::from_le_bytes([c[0], c[1]])), 12 if !words32 => unpack_lsb(src, 12, out), _ => unpack_words32_msb(src, ByteOrder::Little, bits, out), } @@ -171,7 +202,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma let src = raw .get(off..off.checked_add(len).ok_or_else(|| RawError::Corrupt("RAF strip size overflow".into()))?) .ok_or_else(|| RawError::Corrupt("RAF strip outside file".into()))?; - let cfa = cfa(&h); + let cfa = cfa(&h)?; let compression = be32(bytes, 108).unwrap_or(0); let compressed = match compression { 0 => false, @@ -180,8 +211,13 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma }; let mut data = Vec::new(); if compressed { - if cfa.width == 6 && cfa != Cfa::xtrans() { - return Err(RawError::Unsupported("Fujifilm compressed RAF with an unknown X-Trans layout".into())); + if !compressed_layout_supported(&cfa) { + return Err(RawError::Unsupported("Fujifilm compressed RAF with an unsupported CFA layout".into())); + } + if !src.starts_with(b"IS") { + // A recognized RAF compression mode can wrap an unknown packing. Do not + // feed it to the IS codec; damage inside an identified IS stream stays Corrupt. + return Err(RawError::Unsupported("Fujifilm compressed RAF without a supported IS signature".into())); } let flag = if compression == 2 { 1 } else { 0 }; if src.get(2) != Some(&flag) { @@ -190,9 +226,18 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma data = crate::rafc::decode(src, w, hgt, bits, cfa.width == 6, mode, limits)?; } else { let words32 = ifd.u64(PACKED_WORDS).is_some_and(|v| v != 0); - // Samples may use 16-bit words (e.g. 14-bit X-T20); otherwise they are packed at `bits`. - let store = if len as u64 >= (n as u64) * 2 { 16 } else { bits }; - let packed_row = w.checked_mul(store as usize).map(|n| n.div_ceil(8)).ok_or(RawError::Limit("RAF row too large"))?; + // An explicit packed-word flag wins over the size heuristic: padding in short + // packed rows can occupy as many bytes as unpacked 16-bit samples. + // Unflagged samples may use 16-bit words (e.g. 14-bit X-T20). + let store = if !words32 && len as u64 >= (n as u64) * 2 { 16 } else { bits }; + let row_bits = w.checked_mul(store as usize).ok_or(RawError::Limit("RAF row too large"))?; + // Word-packed rows store the high bits in the last little-endian word's final bytes. + // Reading only ceil(bits / 8) bytes would lose those samples, not just padding. + let packed_row = if words32 || (store != 16 && store != 12) { + row_bits.div_ceil(32).checked_mul(4).ok_or(RawError::Limit("RAF row too large"))? + } else { + row_bits.div_ceil(8) + }; let stride = match get(0xf005)?.unwrap_or(0) { 0 => packed_row, words => words.checked_mul(4).ok_or(RawError::Limit("RAF stride too large"))?.max(packed_row), @@ -206,7 +251,11 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { // `required <= src.len()` proves these row offsets fit, including the final row. let s = src.get(y * stride..y * stride + packed_row).unwrap_or(&[]); - unpack_row(s, store, words32, row); + if !words32 && store == 16 && raw.starts_with(b"MM") { + crate::unpack::read_u16s(s, ByteOrder::Big, row); + } else { + unpack_row(s, store, words32, row); + } }); } } @@ -246,7 +295,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma active_area: active, crop: Rect::new(0, 0, active.width, active.height), orientation, - color: ColorData { kelvin_presets, ..Default::default() }, + color: ColorData { kelvin_presets, baseline_exposure: baseline_exposure(&h), ..Default::default() }, wb_multipliers: wb, linearized: false, pixel_aspect: 1.0, @@ -256,6 +305,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma .unwrap_or_else(|| Camera { model: Some(camera_name(bytes)).filter(|n| !n.is_empty()), ..Default::default() }), cinema: Default::default(), lens_metadata: Default::default(), + notices: crate::RawNotices { assumed_cfa: record(&h, XTRANS_LAYOUT).is_none() && record(&h, 0x0130).is_none(), ..Default::default() }, level_sources: crate::LevelSources { black: black_source, white: white_source }, }; img.validate_for(mode)?; @@ -480,6 +530,181 @@ pub(super) mod tests { assert!(matches!(crate::decode(&bytes), Err(RawError::Unsupported(_)))); } + #[test] + fn word_packed_rows_keep_the_final_partial_word_and_reject_truncation() { + for (w, bits, flag) in [(30u32, 14u32, 0u32), (22, 12, 1), (6, 12, 1), (5, 16, 1)] { + let h = 6u32; + let px: Vec<u16> = (0..w * h).map(|i| ((i * 977 + 101) % (1 << bits)) as u16).collect(); + // Independently place each sample bit into whole little-endian 32-bit row words. + let strip: Vec<u8> = px + .chunks(w as usize) + .flat_map(|row| { + let mut words = vec![0u32; (row.len() * bits as usize).div_ceil(32)]; + for (i, &sample) in row.iter().enumerate() { + for bit in 0..bits as usize { + let at = i * bits as usize + bit; + words[at / 32] |= u32::from((sample >> (bits as usize - 1 - bit)) & 1) << (31 - at % 32); + } + } + words.into_iter().flat_map(u32::to_le_bytes).collect::<Vec<_>>() + }) + .collect(); + let bytes = raf_flagged(w, h, bits, strip, None, &[], flag); + assert_eq!(crate::decode(&bytes).unwrap().data, RawData::U16(px)); + assert!(crate::decode(&bytes[..bytes.len() - 1]).is_err()); + } + } + + #[test] + fn big_endian_words_and_bayer_layout_preserve_exact_sensor_values() { + use craft_tiff::{IfdBuilder, TiffWriter, Value}; + let (w, h) = (6u32, 4u32); + let px: Vec<u16> = (0..w * h).map(|i| (i * 977 + 123) as u16).collect(); + for order in [ByteOrder::Little, ByteOrder::Big] { + let build = |at| { + let mut sensor = IfdBuilder::new(); + for (tag, value) in [(0xf001, w), (0xf002, h), (0xf003, 16), (0xf007, at), (0xf008, w * h * 2)] { + sensor.set(tag, Value::Long(vec![value])); + } + let mut root = IfdBuilder::new(); + root.set_child(0xf000, sensor); + TiffWriter::new(order, false).write(&[root]).unwrap() + }; + let mut raw = build(build(0).len() as u32); + raw.extend(px.iter().flat_map(|v| if order == ByteOrder::Big { v.to_be_bytes() } else { v.to_le_bytes() })); + let mut bytes = raf(w, h, 16, vec![0; (w * h * 2) as usize], None, &[]); + let raw_at = be32(&bytes, 100).unwrap(); + bytes.truncate(raw_at); + bytes[104..108].copy_from_slice(&(raw.len() as u32).to_be_bytes()); + bytes.extend(raw); + // A four-site Bayer record is reversed in storage, just like the X-Trans record. + let dir_at = be32(&bytes, 92).unwrap(); + let mut records = bytes[dir_at..raw_at].to_vec(); + let n = u32::from_be_bytes(records[..4].try_into().unwrap()) + 1; + records[..4].copy_from_slice(&n.to_be_bytes()); + records.extend_from_slice(&[0x01, 0x30, 0, 4, 0x08, 0x09, 0x0b, 0x0a]); + bytes.splice(dir_at..raw_at, records.clone()); + bytes[96..100].copy_from_slice(&(records.len() as u32).to_be_bytes()); + bytes[100..104].copy_from_slice(&((raw_at + 8) as u32).to_be_bytes()); + let image = crate::decode(&bytes).unwrap(); + assert_eq!(image.data, RawData::U16(px.clone())); + assert_eq!(image.cfa.unwrap().name(), "BGGR"); + } + } + + #[test] + fn raw_exposure_bias_is_preserved_as_baseline_exposure_and_invalid_values_are_ignored() { + for (num, den, expected) in [(-72i16, 100i16, 0.72f64), (1, 0, 0.0), (32767, 1, 0.0)] { + let mut bytes = raf(6, 4, 16, pack(&[1000; 24], 16), None, &[]); + let (dir_at, raw_at) = (be32(&bytes, 92).unwrap(), be32(&bytes, 100).unwrap()); + let mut records = bytes[dir_at..raw_at].to_vec(); + let n = u32::from_be_bytes(records[..4].try_into().unwrap()) + 1; + records[..4].copy_from_slice(&n.to_be_bytes()); + records.extend_from_slice(&[0x96, 0x50, 0, 4]); + records.extend(num.to_be_bytes()); + records.extend(den.to_be_bytes()); + bytes.splice(dir_at..raw_at, records.clone()); + bytes[96..100].copy_from_slice(&(records.len() as u32).to_be_bytes()); + bytes[100..104].copy_from_slice(&((raw_at + 8) as u32).to_be_bytes()); + for mode in [Mode::Header, Mode::Full] { + assert!((decode(&bytes, mode, &Limits::default()).unwrap().color.baseline_exposure - expected).abs() < 1e-9); + } + } + } + + #[test] + fn invalid_declared_cfa_layouts_are_not_silently_replaced() { + for (tag, data) in [(0x0130, vec![8, 8, 10, 10]), (0x0130, vec![1, 2, 1, 0]), (0x0131, vec![3; 36])] { + let header = Header { jpeg: None, records: vec![(tag, data.as_slice())], raw: None }; + assert!(matches!(cfa(&header), Err(RawError::Unsupported(_)))); + } + } + + fn with_bayer_record(mut bytes: Vec<u8>, pattern: [u8; 4]) -> Vec<u8> { + let (dir_at, raw_at) = (be32(&bytes, 92).unwrap(), be32(&bytes, 100).unwrap()); + let mut records = bytes[dir_at..raw_at].to_vec(); + let count = u32::from_be_bytes(records[..4].try_into().unwrap()) + 1; + records[..4].copy_from_slice(&count.to_be_bytes()); + records.extend_from_slice(&[0x01, 0x30, 0, 4]); + records.extend_from_slice(&pattern); + bytes.splice(dir_at..raw_at, records.clone()); + bytes[96..100].copy_from_slice(&(records.len() as u32).to_be_bytes()); + bytes[100..104].copy_from_slice(&((raw_at + 8) as u32).to_be_bytes()); + bytes + } + + #[test] + fn non_bayer_geometry_is_rejected_in_header_and_full_modes() { + // Reversal gives RGBG: correct colour counts, but both greens in one column. + let bytes = with_bayer_record(raf(6, 4, 16, pack(&[1000; 24], 16), None, &[]), [1, 2, 1, 0]); + for mode in [Mode::Header, Mode::Full] { + assert!(matches!(decode(&bytes, mode, &Limits::default()), Err(RawError::Unsupported(why)) if why.contains("Bayer layout"))); + } + } + + #[test] + fn all_four_bayer_geometries_preserve_the_stored_samples() { + let pixels: Vec<u16> = (0..24).map(|i| 123 + i * 977).collect(); + for (stored, expected) in [([2, 1, 1, 0], "RGGB"), ([0, 1, 1, 2], "BGGR"), ([1, 2, 0, 1], "GRBG"), ([1, 0, 2, 1], "GBRG")] { + let bytes = with_bayer_record(raf(6, 4, 16, pack(&pixels, 16), None, &[]), stored); + for mode in [Mode::Header, Mode::Full] { + let image = decode(&bytes, mode, &Limits::default()).unwrap(); + assert_eq!((image.width, image.height), (6, 4)); + assert_eq!(image.cfa.as_ref().unwrap().name(), expected); + assert_eq!(image.data, RawData::U16(if mode == Mode::Full { pixels.clone() } else { Vec::new() })); + } + } + } + + #[test] + fn compressed_bayer_requires_the_layout_assumed_by_its_predictor() { + let strip = b"IS\x01\x00\x0e\0\x12\x06\0\x03\x0c\x03\0\x02\0\x03".to_vec(); + let mut bytes = raf(780, 18, 14, strip, None, &[]); + let (dir_at, raw_at) = (be32(&bytes, 92).unwrap(), be32(&bytes, 100).unwrap()); + let mut records = bytes[dir_at..raw_at].to_vec(); + let n = u32::from_be_bytes(records[..4].try_into().unwrap()) + 1; + records[..4].copy_from_slice(&n.to_be_bytes()); + // Reversed GRBG: a valid Bayer pattern, but not the RGGB order of this codec. + records.extend_from_slice(&[0x01, 0x30, 0, 4, 0x0b, 0x0a, 0x08, 0x09]); + bytes.splice(dir_at..raw_at, records.clone()); + bytes[96..100].copy_from_slice(&(records.len() as u32).to_be_bytes()); + bytes[100..104].copy_from_slice(&((raw_at + 8) as u32).to_be_bytes()); + for mode in [Mode::Header, Mode::Full] { + assert!(matches!(decode(&bytes, mode, &Limits::default()), Err(RawError::Unsupported(why)) if why.contains("layout"))); + } + } + + #[test] + fn compressed_layout_accepts_both_red_blue_orders_without_accepting_wrong_green_phase() { + for name in ["RGGB", "BGGR"] { + assert!(compressed_layout_supported(&Cfa::bayer_static(name)), "{name}"); + } + for name in ["GRBG", "GBRG"] { + assert!(!compressed_layout_supported(&Cfa::bayer_static(name)), "{name}"); + } + let mut other = Cfa::xtrans(); + assert!(compressed_layout_supported(&other)); + other.pattern.swap(0, 2); + assert!(!compressed_layout_supported(&other)); + } + + #[test] + fn unknown_compressed_signature_is_unsupported_but_identified_stream_damage_is_corrupt() { + let header = b"IS\x01\x00\x0e\0\x12\x06\0\x03\x0c\x03\0\x02\0\x03".to_vec(); + let known = raf(780, 18, 14, header, None, &[]); + let raw_at = be32(&known, 100).unwrap(); + let strip_at = raw_at + raw_ifd(&known[raw_at..]).unwrap().u64(0xf007).unwrap() as usize; + let mut unknown = known.clone(); + unknown[strip_at..strip_at + 2].copy_from_slice(b"XX"); + for mode in [Mode::Header, Mode::Full] { + assert!(matches!(decode(&unknown, mode, &Limits::default()), Err(RawError::Unsupported(why)) if why.contains("signature"))); + assert!( + matches!(decode(&known, mode, &Limits::default()), Err(RawError::Corrupt(_))), + "identified but truncated IS stream must remain corrupt" + ); + } + } + /// Raw IFD flag `0xf006` selects the 32-bit-word packing at 12 bits; without it 12 bits are an LSB-first stream. #[test] fn flag_selects_word_packed_12_bit() { diff --git a/crates/raw/src/rw2.rs b/crates/raw/src/rw2.rs index 9984ed987..1dc1a885e 100644 --- a/crates/raw/src/rw2.rs +++ b/crates/raw/src/rw2.rs @@ -615,11 +615,18 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma } _ => Rect::new(0, 0, active.width, active.height), }; - if !data.is_empty() { + // Packed formats 2/5/7 are lossless sample containers: zero is an ordinary + // code, not evidence of a mapped-out photosite. The documented zero repair + // applies to the predictive format 4 and older word containers only. + if !data.is_empty() && matches!(encoding, Encoding::Words | Encoding::Blocks { kind: Block::Format4, .. }) { fill_defects(&mut data, w, active); } - let cfa = cfa(ifd0.u16(CFA_PATTERN).unwrap_or(1)); + let cfa_code = ifd0.u16(CFA_PATTERN); + // RGGB is still usable when metadata is absent or unknown, but callers + // must be able to distinguish that fallback from a recorded sensor phase. + let assumed_cfa = !matches!(cfa_code, Some(1..=4)); + let cfa = cfa(cfa_code.unwrap_or(1)); let read = BLACK_RGB.map(|tag| ifd0.f64(tag).filter(|v| v.is_finite() && *v >= 0.0)); let tags = read.map(|v| v.unwrap_or(0.0) as f32); let offset = match encoding { @@ -671,6 +678,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma cinema: Default::default(), lens_metadata: Default::default(), level_sources: crate::LevelSources { black: black_source, white: white_source }, + notices: crate::RawNotices { assumed_cfa, ..Default::default() }, }; img.validate_for(mode)?; Ok(img) @@ -1069,18 +1077,62 @@ mod tests { } } + #[test] + fn cfa_fallback_provenance_preserves_pixels_in_header_and_full_modes() { + let pixels: Vec<u16> = (0..72).map(|i| 17 + i * 113).collect(); + let payload = pack(&pixels, 14); + for (code, expected, assumed) in [ + (None, "RGGB", true), + (Some(0), "RGGB", true), + (Some(5), "RGGB", true), + (Some(u16::MAX), "RGGB", true), + (Some(1), "RGGB", false), + (Some(2), "GRBG", false), + (Some(3), "GBRG", false), + (Some(4), "BGGR", false), + ] { + let mut tags = vec![short(BITS, 14), short(RAW_FORMAT, 7)]; + if let Some(code) = code { + tags.push(short(CFA_PATTERN, code)); + } + let bytes = file(18, 4, &tags, &payload, &|off| vec![(RAW_OFFSET, Value::Long(vec![off]))]); + for mode in [Mode::Header, Mode::Full] { + let image = decode(&bytes, mode, &Limits::default()).unwrap(); + assert_eq!((image.width, image.height), (18, 4)); + assert_eq!(image.cfa.as_ref().unwrap().name(), expected, "code {code:?}"); + assert_eq!(image.notices, crate::RawNotices { assumed_cfa: assumed, ..Default::default() }, "code {code:?}, {mode:?}"); + assert_eq!(samples(&image), if mode == Mode::Full { pixels.as_slice() } else { &[] }); + } + } + } + + #[test] + fn lossless_packed_formats_preserve_zero_codes_inside_the_active_area() { + let (w, h) = (90usize, 12usize); + for (format, bits, rotated) in [(5u16, 12u32, true), (5, 14, true), (7, 14, false), (2, 12, false)] { + let mut px = vec![1000u16; w * h]; + px[5 * w + 20] = 0; + let payload = pack(&px, bits); + let bytes = rw2(w as u16, h as u16, bits as u16, format, 100, &if rotated { rotate(payload) } else { payload }); + assert_eq!(samples(&crate::decode(&bytes).unwrap()), px, "format {format}/{bits}"); + } + } + #[test] fn levels_crop_defects_and_cfa() { let (w, h) = (90usize, 60usize); let mut px: Vec<u16> = (0..w * h).map(|i| 300 + (i % 7) as u16).collect(); - // a saturation plateau sets the white level; zeros inside the active area are defects + // A saturation plateau sets the white level. In the older word container, + // isolated zeros inside the active area are documented mapped-out defects. px[10 * w..20 * w].fill(3900); px[30 * w + 40] = 0; px[1] = 0; // in the border: left alone - let mut tags = vec![short(CFA_PATTERN, 2), short(BITS, 12), short(RAW_FORMAT, 5)]; + let mut tags = vec![short(CFA_PATTERN, 2), short(BITS, 12), short(COMPRESSION, 34828)]; tags.extend([0x002f, 0x0030, 0x0031, 0x0032].iter().zip([12u16, 10, 52, 80]).map(|(&tag, v)| short(tag, v))); tags.extend(LINEARITY_LIMIT.map(|tag| short(tag, 2000))); // recorded limits are not used - let bytes = file(w as u16, h as u16, &tags, &rotate(pack(&px, 12)), &|off| vec![(RAW_OFFSET, Value::Long(vec![off]))]); + // Compression 34828 stores left-justified samples in little-endian u16 words. + let words: Vec<u8> = px.iter().flat_map(|&v| (v << 4).to_le_bytes()).collect(); + let bytes = file(w as u16, h as u16, &tags, &words, &|off| vec![(t::STRIP_OFFSETS, Value::Long(vec![off]))]); let r = crate::decode(&bytes).unwrap(); let d = samples(&r); assert_eq!(d[30 * w + 40], ((px[30 * w + 38] as u32 + px[30 * w + 42] as u32 + px[28 * w + 40] as u32 + px[32 * w + 40] as u32) / 4) as u16); diff --git a/crates/raw/src/srw.rs b/crates/raw/src/srw.rs index c78ef1f6f..c9f9a0ce6 100644 --- a/crates/raw/src/srw.rs +++ b/crates/raw/src/srw.rs @@ -192,6 +192,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma cinema: Default::default(), lens_metadata: Default::default(), level_sources: crate::LevelSources { black: black_source, white: white_source }, + notices: crate::RawNotices::default(), }; img.validate_for(mode)?; Ok(img) diff --git a/crates/raw/src/tests.rs b/crates/raw/src/tests.rs index aaa62f00c..65c4aae9c 100644 --- a/crates/raw/src/tests.rs +++ b/crates/raw/src/tests.rs @@ -49,6 +49,7 @@ fn an_active_area_that_wraps_past_the_image_is_corrupt() { cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: crate::RawNotices::default(), pixel_aspect: 1.0, }; assert!(raw.validate().is_err(), "`x + width` wrapped: the area is outside the image"); diff --git a/crates/raw/src/tiffraw.rs b/crates/raw/src/tiffraw.rs index 57dc83a6c..9a5649364 100644 --- a/crates/raw/src/tiffraw.rs +++ b/crates/raw/src/tiffraw.rs @@ -115,6 +115,7 @@ pub(crate) fn read_image_in( crate::Mode::Full => read_image(data, info, order, packing, limits), crate::Mode::Header => { check_image(data, info, limits)?; + check_uncompressed_chunks(data, info, &info.chunks(data.len() as u64), packing)?; // a lossless-JPEG layout the decoder rejects (subsampled components, e.g. Sony's // lossless M/S sizes) must fail here too, as the full decode will; likewise a JPEG XL // chunk whose headers don't match the IFD @@ -151,6 +152,7 @@ pub(crate) fn read_image(data: &[u8], info: &ImageInfo, order: ByteOrder, packin let bits = info.bits() as u32; let float = info.sample_format == 3; let chunks = info.chunks(data.len() as u64); + check_uncompressed_chunks(data, info, &chunks, packing)?; let planar = info.planar == 2 && cpp > 1; let ccpp = if planar { 1 } else { cpp }; // The chunks are decoded and copied into the output in groups whose combined nominal size stays within @@ -222,6 +224,26 @@ pub(crate) fn read_image(data: &[u8], info: &ImageInfo, order: ByteOrder, packin Ok(if float { RawData::F32(out_f32) } else { RawData::U16(out_u16) }) } +/// Framing precedes allocation even in header-only probes: missing source rows may not +/// be reported as a decodable image and later silently filled with zero samples. +fn check_uncompressed_chunks(data: &[u8], info: &ImageInfo, chunks: &[Chunk], packing: Packing) -> Result<()> { + if info.compression != comp::NONE { + return Ok(()); + } + let cpp = if info.planar == 2 { 1 } else { info.samples_per_pixel as usize }; + for chunk in chunks { + let src = chunk_bytes(data, chunk).ok_or_else(|| RawError::Corrupt("uncompressed chunk is outside the file".into()))?; + let (cw, _, vw, vh) = chunk_dims(info, chunk); + let row = packed_row_bytes(cw as u64 * cpp as u64, info.bits() as u32, packing, info.sample_format == 3); + let last = packed_row_bytes(vw as u64 * cpp as u64, info.bits() as u32, packing, info.sample_format == 3); + let need = row.saturating_mul(vh.saturating_sub(1) as u64).saturating_add(last); + if (src.len() as u64) < need { + return Err(RawError::Corrupt(format!("an uncompressed chunk has {} bytes, expected at least {need}", src.len()))); + } + } + Ok(()) +} + /// Bytes that `n` samples take in a row of an uncompressed or inflated chunk, laid out as /// [`unpack_chunk`] reads them: whole bytes or 16-bit words, or 32-bit words for `Words32Msb`. fn packed_row_bytes(n: u64, bits: u32, packing: Packing, float: bool) -> u64 { @@ -285,10 +307,12 @@ fn decode_chunk( } match info.compression { comp::NONE => { - // uncompressed: missing rows are filled with zeros, but a chunk holding a small fraction of what its - // samples need is no picture: refused before the nominal chunk is allocated (storytold/lightcraft#1512) - let need = (n as u64).saturating_mul(u64::from(bits)) / 8; - if (src.len() as u64).saturating_mul(64) < need { + // Require every visible sample. Nominal edge-tile padding may be absent, but + // missing image rows must not turn a truncated file into a zero-filled success. + let row_bytes = packed_row_bytes(cw as u64 * cpp as u64, bits, packing, float); + let last_row = packed_row_bytes(vw as u64 * cpp as u64, bits, packing, float); + let need = row_bytes.saturating_mul(vh.saturating_sub(1) as u64).saturating_add(last_row); + if (src.len() as u64) < need { return Err(RawError::Corrupt(format!("an uncompressed chunk of {n} samples has only {} bytes", src.len()))); } unpack_chunk(src, order, packing, cw, ch, cpp, bits, float, 1) @@ -314,13 +338,7 @@ fn decode_chunk( let mcu = |v: usize| v.div_ceil(32).saturating_mul(32); let tile_budget = mcu(cw).saturating_mul(mcu(ch)).saturating_mul(if cpp == 1 { 1 } else { 3 }).clamp(1, limits.max_lossy_tile_samples.max(1)); - let (px, jw, jh, jc) = lossy_jpeg(src, cpp, tile_budget)?; - // An edge tile's JPEG may be smaller than the nominal tile, but it has to cover the part of the tile - // inside the image: one that doesn't would leave a black region in a picture reported as decoded - // (PhotoCraft's and FilmCraft's readers refuse a JPEG smaller than its tile; this keeps the edge case). - if jw < vw || jh < vh { - return Err(RawError::Corrupt(format!("a lossy JPEG of {jw} × {jh} does not cover the {vw} × {vh} of its tile inside the image"))); - } + let (px, jw, jh, jc) = lossy_jpeg_with_tile(src, cpp, tile_budget, Some((cw, ch, vw, vh)))?; // the buffer holds the rows the decoded JPEG covers (the caller zero-fills the tile's // remainder and reads only rows it fills): a tile-many-larger decoded JPEG does not // get the nominal tile's full buffer (storytold/lightcraft#1517) @@ -408,9 +426,21 @@ const MAX_PADDING_FACTOR: usize = 32; #[cfg(feature = "dng")] const MAX_WRITER_TILE_SAMPLES: usize = 2048 * 2048; -#[cfg(feature = "dng")] +#[cfg(all(test, feature = "dng"))] /// Decode one baseline JPEG chunk to 8-bit samples: (samples, width, height, channels). pub(crate) fn lossy_jpeg(src: &[u8], cpp: usize, max_samples: usize) -> Result<(Vec<u8>, usize, usize, usize)> { + lossy_jpeg_with_tile(src, cpp, max_samples, None) +} + +/// Validate the actual frame before decode allocates its output. Edge tiles may store +/// a smaller frame covering all visible samples or bounded whole-MCU padding. +#[cfg(feature = "dng")] +fn lossy_jpeg_with_tile( + src: &[u8], + cpp: usize, + max_samples: usize, + tile: Option<(usize, usize, usize, usize)>, +) -> Result<(Vec<u8>, usize, usize, usize)> { use zune_core::bytestream::ZCursor; use zune_core::colorspace::ColorSpace; use zune_core::options::DecoderOptions; @@ -422,7 +452,27 @@ pub(crate) fn lossy_jpeg(src: &[u8], cpp: usize, max_samples: usize) -> Result<( d.decode_headers().map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?; let info = d.info().ok_or_else(|| RawError::Corrupt("lossy JPEG tile without a header".into()))?; let (w, h) = (info.width as usize, info.height as usize); - let c = if cpp == 1 { 1 } else { 3 }; + if !matches!(cpp, 1 | 3) { + return Err(RawError::Unsupported(format!("lossy JPEG with {cpp} samples per pixel"))); + } + if usize::from(info.components) != cpp { + return Err(RawError::Corrupt(format!("lossy JPEG has {} components, expected {cpp}", info.components))); + } + if let Some((cw, ch, vw, vh)) = tile { + if w < vw || h < vh { + return Err(RawError::Corrupt(format!("a lossy JPEG of {w} x {h} does not cover the {vw} x {vh} of its tile inside the image"))); + } + // Writers can store a whole MCU around an edge tile. Keep the documented + // 32-pixel padding allowance without letting one tiny tile decode an arbitrary frame. + let mcu_extent = |value: usize| value.checked_add(31).map(|rounded| rounded / 32).and_then(|blocks| blocks.checked_mul(32)); + let (Some(max_w), Some(max_h)) = (mcu_extent(cw), mcu_extent(ch)) else { + return Err(RawError::Corrupt("lossy JPEG tile dimensions overflow MCU padding".into())); + }; + if w > max_w || h > max_h { + return Err(RawError::Corrupt(format!("a lossy JPEG of {w} x {h} exceeds its {max_w} x {max_h} MCU-padded tile dimensions"))); + } + } + let c = cpp; let out = w as u64 * h as u64 * c as u64; if w == 0 || h == 0 || out > max_samples as u64 { return Err(RawError::Corrupt(format!("a lossy JPEG of {w} × {h} × {c} would exceed the {max_samples} output samples allowed"))); @@ -519,6 +569,12 @@ fn unpack_chunk( } } else { undo_diff_u16(row, cpp * factor); + // Horizontal differences wrap in the declared sample precision, not in + // the u16 container used by the unpacker (TIFF 6.0 Predictor 2). + if bits < 16 { + let mask = ((1u32 << bits) - 1) as u16; + row.iter_mut().for_each(|sample| *sample &= mask); + } } } } @@ -982,3 +1038,6 @@ mod budget_tests { assert_eq!(decode_groups(&big.chunks(64), 1, 1 << 20), vec![0..1]); } } + +#[cfg(all(test, feature = "dng"))] +mod compat_review_tests; diff --git a/crates/raw/src/tiffraw/compat_review_tests.rs b/crates/raw/src/tiffraw/compat_review_tests.rs new file mode 100644 index 000000000..ae5da8f2f --- /dev/null +++ b/crates/raw/src/tiffraw/compat_review_tests.rs @@ -0,0 +1,115 @@ +use super::*; +use craft_tiff::image::Layout; + +fn image(width: u32, height: u32, bits: u16, cpp: u16, compression: u16, len: usize) -> ImageInfo { + ImageInfo { + width, + height, + bits_per_sample: vec![bits; cpp as usize], + samples_per_pixel: cpp, + compression, + photometric: 34892, + planar: 1, + predictor: 1, + sample_format: 1, + new_subfile_type: 0, + layout: Layout::Strips { rows_per_strip: height }, + offsets: vec![0], + byte_counts: vec![len as u64], + } +} + +#[test] +fn truncated_uncompressed_rows_are_rejected_in_full_and_header_modes() { + for (bits, packing, float, bytes) in [ + (8, Packing::Msb, false, 8), + (12, Packing::Msb, false, 12), + (12, Packing::Word16, false, 16), + (16, Packing::Msb, false, 16), + (32, Packing::Msb, true, 32), + ] { + let data = vec![0u8; bytes]; + let mut info = image(4, 2, bits, 1, comp::NONE, bytes); + info.sample_format = if float { 3 } else { 1 }; + assert!(read_image_in(crate::Mode::Full, &data, &info, ByteOrder::Little, packing, &Limits::default()).is_ok()); + info.byte_counts[0] -= 1; + for mode in [crate::Mode::Full, crate::Mode::Header] { + assert!( + matches!(read_image_in(mode, &data[..bytes - 1], &info, ByteOrder::Little, packing, &Limits::default()), Err(RawError::Corrupt(message)) if message.contains("uncompressed chunk")), + "{bits}/{float}/{mode:?}" + ); + } + } +} + +#[test] +fn edge_padding_may_be_absent_but_visible_uncompressed_samples_must_all_exist() { + let data = vec![31u8; 16 * 7 + 8]; + let mut info = image(8, 8, 8, 1, comp::NONE, data.len()); + info.layout = Layout::Tiles { tile_width: 16, tile_height: 16 }; + let RawData::U16(values) = read_image(&data, &info, ByteOrder::Little, Packing::Msb, &Limits::default()).unwrap() else { panic!("integer") }; + assert_eq!(values, vec![31; 64]); + info.byte_counts[0] -= 1; + assert!(read_image(&data[..data.len() - 1], &info, ByteOrder::Little, Packing::Msb, &Limits::default()).is_err()); +} + +#[test] +fn packed_predictor_two_wraps_at_declared_twelve_bits() { + // Samples [250, 10, 4090, 20]; differences modulo4096 are 0FA,F10,FF0,01A. + let packed = [0x0f, 0xaf, 0x10, 0xff, 0x00, 0x1a]; + let ChunkPx::U16(values) = unpack_chunk(&packed, ByteOrder::Little, Packing::Msb, 4, 1, 1, 12, false, 2).unwrap() else { panic!("integer") }; + assert_eq!(values, vec![250, 10, 4090, 20]); +} + +#[allow(clippy::unwrap_used)] // Test-only fixture encoder; failed construction must fail the test. +fn jpeg(cpp: usize, width: u16, height: u16) -> Vec<u8> { + let mut data = Vec::new(); + let color = if cpp == 1 { jpeg_encoder::ColorType::Luma } else { jpeg_encoder::ColorType::Rgb }; + jpeg_encoder::Encoder::new(&mut data, 100).encode(&vec![90; width as usize * height as usize * cpp], width, height, color).unwrap(); + data +} + +#[test] +fn baseline_jpeg_components_are_checked_before_forced_colorspace_conversion() { + for (actual, expected) in [(3, 1), (1, 3)] { + let data = jpeg(actual, 8, 8); + let error = lossy_jpeg(&data, expected, 1024).unwrap_err(); + assert!(matches!(error, RawError::Corrupt(message) if message.contains(&format!("{actual} components")))); + } + assert!(matches!(lossy_jpeg(&jpeg(3, 8, 8), 4, 1024), Err(RawError::Unsupported(message)) if message.contains("4 samples"))); + for cpp in [1, 3] { + assert_eq!(lossy_jpeg(&jpeg(cpp, 8, 8), cpp, 1024).unwrap().3, cpp); + } +} + +#[test] +fn jpeg_tile_geometry_and_limits_are_checked_at_the_header_with_valid_edge_controls() { + let data = jpeg(3, 8, 8); + assert!(lossy_jpeg_with_tile(&data, 3, 1024, Some((16, 16, 8, 8))).is_ok()); + assert!( + matches!(lossy_jpeg_with_tile(&data, 3, 1024, Some((16, 16, 9, 8))), Err(RawError::Corrupt(message)) if message.contains("does not cover")) + ); + assert!(matches!(lossy_jpeg_with_tile(&data, 3, 32, Some((16, 16, 8, 8))), Err(RawError::Corrupt(message)) if message.contains("would exceed"))); + // Mutate only SOF dimensions, retaining a valid header but no entropy for the claimed frame. + // The geometry error proves refusal precedes decode's short/corrupt entropy failure. + for (width, height) in [(33u16, 8u16), (8, 33), (256, 256)] { + let mut oversized = data.clone(); + let sof = oversized.windows(2).position(|bytes| bytes == [0xff, 0xc0]).unwrap(); + oversized[sof + 5..sof + 7].copy_from_slice(&height.to_be_bytes()); + oversized[sof + 7..sof + 9].copy_from_slice(&width.to_be_bytes()); + assert!( + matches!(lossy_jpeg_with_tile(&oversized, 3, 1 << 20, Some((16, 16, 8, 8))), Err(RawError::Corrupt(message)) if message.contains("exceeds its")) + ); + } + // A genuine full MCU remains valid even when only a 4x4 part of the nominal16 tile is visible. + let padded = jpeg(3, 32, 32); + assert!(lossy_jpeg_with_tile(&padded, 3, 32 * 32 * 3, Some((16, 16, 4, 4))).is_ok()); + assert!( + matches!(lossy_jpeg_with_tile(&data, 3, 1 << 20, Some((usize::MAX, 16, 8, 8))), Err(RawError::Corrupt(message)) if message.contains("overflow MCU padding")) + ); + let mut info = image(8, 8, 8, 3, comp::LOSSY_JPEG, data.len()); + info.layout = Layout::Tiles { tile_width: 16, tile_height: 16 }; + let RawData::U16(values) = read_image(&data, &info, ByteOrder::Little, Packing::Msb, &Limits::default()).unwrap() else { panic!("integer") }; + assert_eq!(values.len(), 8 * 8 * 3); + assert!(values.iter().all(|sample| (i32::from(*sample) - 90).abs() <= 3)); +} diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index 3b7f4bc0a..216937862 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -64,6 +64,7 @@ fn synthetic(w: usize, h: usize, cfa: Option<Cfa>, cpp: usize) -> RawImage { cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: craft_raw::RawNotices::default(), } } @@ -948,18 +949,31 @@ fn malformed_semantic_masks_are_skipped() { let mut zero = mask_ifd(2, 2, "zero size", vec![0; 4]); zero.set(t::IMAGE_WIDTH, Value::Long(vec![0])); ifd0.add_sub_ifd(zero); + // A 4x4 8-bit mask needs 16 visible samples; three bytes must not be + // accepted as a synthetic mask with thirteen zero-filled samples. let mut short = mask_ifd(4, 4, "short strip", vec![200; 3]); short.set(t::MASK_SUB_AREA, Value::Long(vec![u32::MAX, u32::MAX, u32::MAX, u32::MAX])); ifd0.add_sub_ifd(short); + let mut valid = mask_ifd(4, 2, "valid crop", vec![10, 20, 30, 40, 50, 60, 70, 255]); + valid.set(t::MASK_SUB_AREA, Value::Long(vec![1, 2, 8, 4])); + ifd0.add_sub_ifd(valid); let mut outside = mask_ifd(2, 2, "sub area too small", vec![255; 4]); outside.set(t::MASK_SUB_AREA, Value::Long(vec![3, 0, 2, 4])); ifd0.add_sub_ifd(outside); }); - assert_eq!(decode(&bytes).unwrap().cpp, 3); + let raw = decode(&bytes).unwrap(); + let baseline = decode(&profile_dng(ByteOrder::Little, |_| {})).unwrap(); + assert_eq!((raw.width, raw.height, raw.cpp), (8, 6, 3)); + assert_eq!(raw.data, baseline.data, "optional damaged masks must not change base image samples"); let masks = craft_raw::semantic_masks(&bytes); let names: Vec<&str> = masks.iter().map(|m| m.name.as_str()).collect(); - assert_eq!(names, ["short strip", "sub area too small"]); - assert!(masks.iter().all(|m| m.sub_area.is_none()), "sub areas the mask doesn't fit are ignored"); + assert_eq!(names, ["valid crop", "sub area too small"], "the truncated mask is omitted, and later usable masks survive"); + assert_eq!(masks[0].data, [10u16, 20, 30, 40, 50, 60, 70, 255].map(|sample| sample * 257)); + assert_eq!(masks[0].sub_area, Some(craft_raw::semantic::MaskSubArea { top: 1, left: 2, full_width: 8, full_height: 4 })); + assert!((masks[0].value_at(2.5, 1.5) - 10. / 255.).abs() < 1e-4); + assert_eq!(masks[0].value_at(1.5, 1.5), 0.); + assert!(masks[1].sub_area.is_none(), "the complete mask survives while a sub area it doesn't fit is ignored"); + assert_eq!(masks[1].data, vec![65535; 4]); for m in &masks { assert_eq!(m.data.len(), m.width * m.height); } diff --git a/crates/raw/tests/it/robust.rs b/crates/raw/tests/it/robust.rs index b2adb26e0..5ad1d1b32 100644 --- a/crates/raw/tests/it/robust.rs +++ b/crates/raw/tests/it/robust.rs @@ -28,6 +28,7 @@ fn sample(comp: DngCompression) -> Vec<u8> { cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: craft_raw::RawNotices::default(), }; craft_raw::write_dng(&raw, &DngWriteOptions { compression: comp, ..Default::default() }).unwrap() } diff --git a/crates/rtf/src/doc/export.rs b/crates/rtf/src/doc/export.rs index 69fab3d76..daa3afbda 100644 --- a/crates/rtf/src/doc/export.rs +++ b/crates/rtf/src/doc/export.rs @@ -8,32 +8,27 @@ use crate::date::{date_words as rtf_date, iso_to_dttm}; // --------------------------------------------------------------------------------------------- // Export +use crate::write::{Interned, font_key}; pub use crate::{esc, esc_font}; pub(super) struct Tables { - pub(super) fonts: Vec<String>, - pub(super) colors: Vec<Rgb>, + pub(super) fonts: Interned<String, String>, + pub(super) colors: Interned<Rgb, Rgb>, } impl Tables { + /// Tables whose font 0 is `base_font`, with no colours yet. + pub(super) fn new(base_font: String) -> Tables { + let mut t = Tables { fonts: Interned::new(), colors: Interned::new() }; + t.fonts.insert(font_key(&base_font), || base_font); + t + } pub(super) fn font(&mut self, name: &str) -> usize { - match self.fonts.iter().position(|f| f.eq_ignore_ascii_case(name)) { - Some(i) => i, - None => { - self.fonts.push(name.to_string()); - self.fonts.len() - 1 - } - } + self.fonts.insert(font_key(name), || name.to_string()) } /// Colour table index (1-based; 0 is "auto"). fn color(&mut self, c: Rgb) -> usize { - match self.colors.iter().position(|x| *x == c) { - Some(i) => i + 1, - None => { - self.colors.push(c); - self.colors.len() - } - } + self.colors.insert(c, || c) + 1 } } @@ -65,7 +60,7 @@ pub(super) struct Writer { /// List definitions: per list, the ordered flag per level. pub(super) lists: Vec<[bool; 9]>, /// Authors of tracked changes (`\revtbl` entries after "Unknown"), when the text has any. - pub(super) authors: Option<Vec<String>>, + pub(super) authors: Option<Interned<String, String>>, /// The character formatting the current paragraph's style gives its runs (heading bold and /// size, code font…): what a run's formatting without a direct value resolves to. pub(super) base: Fmt, @@ -306,18 +301,18 @@ impl Writer { /// `\revtbl` index of a tracked change's author (0 = "Unknown"). fn author(&mut self, a: &str) -> usize { - let authors = self.authors.get_or_insert_with(Vec::new); + let authors = self.authors.get_or_insert_with(Interned::new); let a = a.trim(); if a.is_empty() { return 0; } - match authors.iter().position(|x| x == a) { - Some(i) => i + 1, - None => { - authors.push(a.to_string()); - authors.len() - } - } + // A borrowed lookup first: most calls name an author already in the table, and need no + // `String` for the key. + let i = match authors.get(a) { + Some(i) => i, + None => authors.insert(a.to_string(), || a.to_string()), + }; + i + 1 } /// Control words of a tracked insertion and deletion (`\revised`, `\deleted`). @@ -858,15 +853,7 @@ pub fn export(doc: &Document) -> String { let doc = marked.as_ref().unwrap_or(doc); let flow = model::from_doc_tracked(doc); let base_font = doc.styles.default_chr.font.clone().unwrap_or_else(|| craft_wordmodel::styles::BODY_FONT.to_string()); - let mut w = Writer { - marks, - t: Tables { fonts: vec![base_font], colors: Vec::new() }, - lists: Vec::new(), - authors: None, - base: Fmt::default(), - sections: Vec::new(), - sect_i: 0, - }; + let mut w = Writer { marks, t: Tables::new(base_font), lists: Vec::new(), authors: None, base: Fmt::default(), sections: Vec::new(), sect_i: 0 }; let mut body = String::new(); // Every section starts with its own `\sectd`; `\sect` breaks only where there are several. let secs: Vec<craft_wordmodel::SectionProps> = doc.sections().into_iter().map(|(_, s)| s.clone()).collect(); @@ -882,12 +869,12 @@ pub fn export(doc: &Document) -> String { fn export_with(m: &Meta, w: &Writer, body: &str, sec: &craft_wordmodel::SectionProps) -> String { let mut out = String::from("{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033\\uc1\n{\\fonttbl"); - for (i, f) in w.t.fonts.iter().enumerate() { + for (i, f) in w.t.fonts.items.iter().enumerate() { let fam = if model::is_mono(f) { "\\fmodern" } else { "\\fswiss" }; out.push_str(&format!("{{\\f{i}{fam}\\fcharset0 {};}}", esc_font(f))); } out.push_str("}\n{\\colortbl;"); - for c in &w.t.colors { + for c in &w.t.colors.items { out.push_str(&format!("\\red{}\\green{}\\blue{};", c.0, c.1, c.2)); } out.push_str("}\n{\\*\\generator WordCraft;}\n{\\stylesheet{\\s0\\snext0 Normal;}"); @@ -916,7 +903,7 @@ fn export_with(m: &Meta, w: &Writer, body: &str, sec: &craft_wordmodel::SectionP } if let Some(authors) = &w.authors { out.push_str("{\\*\\revtbl {Unknown;}"); - for a in authors { + for a in &authors.items { out.push_str(&format!("{{{};}}", esc(&a.replace(';', ",")))); } out.push_str("}\n"); diff --git a/crates/rtf/src/doc/tests.rs b/crates/rtf/src/doc/tests.rs index 7c1075a86..003b32872 100644 --- a/crates/rtf/src/doc/tests.rs +++ b/crates/rtf/src/doc/tests.rs @@ -1168,7 +1168,7 @@ fn old_formatting_in_a_code_paragraph_has_the_code_font() { p.push_text("x", &Fmt { font: Some("Arial".into()), fmt_change: Some(Box::new(FmtChange { mark, old: Fmt::default() })), ..Default::default() }); let mut w = Writer { marks: Vec::new(), - t: Tables { fonts: vec!["Aptos".into()], colors: Vec::new() }, + t: Tables::new("Aptos".into()), lists: Vec::new(), authors: None, base: Fmt::default(), @@ -1181,6 +1181,39 @@ fn old_formatting_in_a_code_paragraph_has_the_code_font() { assert!(out.contains(&format!("{{\\*\\oldcprops \\f{mono}\\crauth1}}")), "{out}"); } +#[test] +fn many_distinct_fonts_colours_and_authors_take_constant_steps_each() { + use model::FmtChange; + // Each run has its own font, colour and tracked-change author. + let n = 3000; + let mut p = Para::default(); + for i in 0..n { + let mark = RevMark { author: format!("Author {i}"), date: String::new(), id: None }; + let color = Rgb((i >> 16) as u8, (i >> 8) as u8, i as u8); + let font: Arc<str> = format!("Font {i}").into(); + p.push_text( + "x", + &Fmt { font: Some(font), color: Some(color), fmt_change: Some(Box::new(FmtChange { mark, old: Fmt::default() })), ..Default::default() }, + ); + } + let mut w = Writer { + marks: Vec::new(), + t: Tables::new("Aptos".into()), + lists: Vec::new(), + authors: None, + base: Fmt::default(), + sections: Vec::new(), + sect_i: 0, + }; + let mut out = String::new(); + let steps = crate::write::lookup_steps(|| w.para(&p, false, None, "\\par", &mut out)); + // One lookup each for the font and the colour, and two for a new author: the borrowed + // lookup, then the insert. + assert!(steps <= 4 * n, "{steps} steps for {n} runs"); + assert!(out.contains(&format!("\\f{n}\\cf{n}")), "the last run names the last font and colour"); + assert!(out.contains(&format!("\\crauth{n}")), "the last run names the last author"); +} + /// The text runs of `rtf`'s paragraphs, in order, with their formatting. fn text_runs(rtf: &[u8]) -> Vec<(String, Fmt)> { let f = parse(rtf).unwrap(); diff --git a/crates/rtf/src/text.rs b/crates/rtf/src/text.rs index b1411842e..7cca12d8e 100644 --- a/crates/rtf/src/text.rs +++ b/crates/rtf/src/text.rs @@ -12,8 +12,9 @@ fn multibyte(code_page: u16) -> Option<&'static encoding_rs::Encoding> { /// else the default font's, else the document's) and how many fallback characters follow a /// `\uN` (`\ucN`, 1 when not set). /// -/// - `\uN` is one UTF-16 code unit. A high surrogate pairs only with a low surrogate in the -/// very next `\u`; every surrogate that does not pair reads as U+FFFD, as in Word. +/// - `\uN` is one UTF-16 code unit in the signed/unsigned 16-bit range. A high surrogate pairs +/// only with a low surrogate in the very next `\u`; unmatched surrogates and out-of-range +/// values are dropped, matching the historical DesignCraft reader. /// - After a `\uN`, the next `\ucN` characters are its fallback and are skipped: a text byte, /// a `\'hh`, a control word and a control symbol each count as one ([`TextDecoder::skip`]). /// The skipping ends with the group ([`TextDecoder::group`]). @@ -36,27 +37,34 @@ impl TextDecoder { } /// A held high surrogate that nothing paired with. - fn flush_high(&mut self, out: &mut String) { - if self.high.take().is_some() { - out.push('\u{FFFD}'); - } + fn flush_high(&mut self) { + self.high = None; } /// `\uN` with `uc` fallback characters to skip after it. pub fn unicode(&mut self, param: i32, uc: usize, out: &mut String) { self.finish_multibyte(out); + if !(-32_768..=65_535).contains(&param) { + self.skip = uc; + return; + } let u = i64::from(param).rem_euclid(65_536) as u16; if (0xD800..0xDC00).contains(&u) { - self.flush_high(out); + self.flush_high(); self.high = Some(u); } else { match self.high.take() { - Some(h) if (0xDC00..0xE000).contains(&u) => out.push(char::decode_utf16([h, u]).next().and_then(Result::ok).unwrap_or('\u{FFFD}')), - Some(_) => { - out.push('\u{FFFD}'); - out.push(char::from_u32(u32::from(u)).unwrap_or('\u{FFFD}')); + Some(h) if (0xDC00..0xE000).contains(&u) => { + if let Some(c) = char::decode_utf16([h, u]).next().and_then(Result::ok) { + out.push(c); + } + } + Some(_) | None if (0xDC00..0xE000).contains(&u) => {} + Some(_) | None => { + if let Some(c) = char::from_u32(u32::from(u)) { + out.push(c); + } } - None => out.push(char::from_u32(u32::from(u)).unwrap_or('\u{FFFD}')), } } self.skip = uc; @@ -73,7 +81,7 @@ impl TextDecoder { /// A character a control word or symbol stands for (`\emdash`, `\~`). pub fn char(&mut self, c: char, out: &mut String) { self.finish_multibyte(out); - self.flush_high(out); + self.flush_high(); out.push(c); } @@ -95,7 +103,7 @@ impl TextDecoder { } fn decode(&mut self, chunk: &[u8], cp: u16, out: &mut String) { - self.flush_high(out); + self.flush_high(); if self.mb.is_none() && chunk.is_ascii() { // ASCII is itself in every code page here; with no lead byte pending, as it is. out.push_str(std::str::from_utf8(chunk).unwrap_or_default()); @@ -143,7 +151,7 @@ impl TextDecoder { /// for a partner any longer. pub fn finish(&mut self, out: &mut String) { self.finish_multibyte(out); - self.flush_high(out); + self.flush_high(); } } @@ -165,12 +173,13 @@ mod tests { assert_eq!(units(&[-10179, -8704], 0), "\u{1F600}"); assert_eq!(units(&[0xD83D, 0xDE00], 0), "\u{1F600}", "written unsigned"); assert_eq!(units(&[8364], 0), "€"); - assert_eq!(units(&[-10179], 0), "\u{FFFD}", "a lone high surrogate at the end"); - assert_eq!(units(&[-8704], 0), "\u{FFFD}", "a lone low surrogate"); - assert_eq!(units(&[-8704, -10179], 0), "\u{FFFD}\u{FFFD}", "low then high"); - assert_eq!(units(&[-10179, -10179, -8704], 0), "\u{FFFD}\u{1F600}", "a high surrogate before a pair"); - assert_eq!(units(&[-10179, 65, -8704], 0), "\u{FFFD}A\u{FFFD}"); - assert_eq!(units(&[65536 + 65, -65536 + 66], 0), "AB", "taken modulo 65536"); + assert_eq!(units(&[-10179], 0), "", "a lone high surrogate is dropped"); + assert_eq!(units(&[-8704], 0), "", "a lone low surrogate is dropped"); + assert_eq!(units(&[-8704, -10179], 0), "", "low then high are dropped"); + assert_eq!(units(&[-10179, -10179, -8704], 0), "\u{1F600}", "an unpaired high is dropped before a pair"); + assert_eq!(units(&[-10179, 65, -8704], 0), "A"); + assert_eq!(units(&[65_536 + 65, -65_536 + 66], 0), "", "out-of-range units are dropped"); + assert_eq!(units(&[i32::MAX, 65, i32::MIN], 0), "A", "extreme units are dropped"); } #[test] @@ -187,7 +196,7 @@ mod tests { d.group(&mut out); d.unicode(-8704, 1, &mut out); d.finish(&mut out); - assert_eq!(out, "\u{FFFD}x\u{FFFD}\u{FFFD}\u{2014}\u{1F600}"); + assert_eq!(out, "x\u{2014}\u{1F600}"); } #[test] diff --git a/crates/rtf/src/write.rs b/crates/rtf/src/write.rs index 0b8f1dc8d..9bd6c7b0c 100644 --- a/crates/rtf/src/write.rs +++ b/crates/rtf/src/write.rs @@ -1,6 +1,10 @@ //! The model as RTF, and the escaping every RTF writer needs. +use std::borrow::Borrow; +use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::fmt::Write; +use std::hash::Hash; use crate::model::{Align, Block, COLUMN_BREAK, CharFmt, Document, LINE_BREAK, PAGE_BREAK, Para, VertAlign}; @@ -48,31 +52,94 @@ pub fn esc_font(name: &str) -> String { esc(&name.replace(char::is_control, "")).replace(';', "\\'3b") } +#[cfg(test)] +thread_local! { + /// Lookups the writers make in their font, colour and author tables, counted in tests: each + /// must take one step however long the table is, so a document with thousands of fonts or + /// colours is written in linear time. + static STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +/// The lookup steps `f` takes (see [`STEPS`]). +#[cfg(test)] +pub(crate) fn lookup_steps(f: impl FnOnce()) -> usize { + STEPS.with(|s| s.set(0)); + f(); + STEPS.with(|s| s.get()) +} + +/// A table written in the order its entries were first used (`\fonttbl`, `\colortbl`, +/// `\revtbl`), with an index from each entry's key to its place, so that a lookup doesn't scan +/// the table: a document can use thousands of fonts or colours. +pub(crate) struct Interned<T, K> { + pub(crate) items: Vec<T>, + index: HashMap<K, usize>, +} + +impl<T, K: Eq + Hash> Interned<T, K> { + pub(crate) fn new() -> Self { + Interned { items: Vec::new(), index: HashMap::new() } + } + + /// The place of the entry with `key`. + pub(crate) fn get<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> Option<usize> + where + K: Borrow<Q>, + { + #[cfg(test)] + STEPS.with(|s| s.set(s.get() + 1)); + self.index.get(key).copied() + } + + /// The place of the entry with `key`, adding `item()` at the end when there is none: one + /// lookup in the index either way. + pub(crate) fn insert(&mut self, key: K, item: impl FnOnce() -> T) -> usize { + #[cfg(test)] + STEPS.with(|s| s.set(s.get() + 1)); + match self.index.entry(key) { + Entry::Occupied(e) => *e.get(), + Entry::Vacant(e) => { + self.items.push(item()); + let i = self.items.len() - 1; + e.insert(i); + i + } + } + } +} + +/// A font table's key for `name`: RTF writers match font names without regard to ASCII case, +/// and the table keeps the first spelling. +pub(crate) fn font_key(name: &str) -> String { + name.to_ascii_lowercase() +} + /// The fonts and colours a document uses, in the order of their tables. Font 0 is the default /// font; colour 0 is the default (auto) colour, so the first real colour is `\cf1`. struct Tables { - fonts: Vec<String>, - colors: Vec<[u8; 3]>, + fonts: Interned<String, String>, + colors: Interned<[u8; 3], [u8; 3]>, } impl Tables { fn of(doc: &Document, default_font: &str) -> Tables { - let mut t = Tables { fonts: vec![default_font.to_string()], colors: Vec::new() }; + let mut t = Tables { fonts: Interned::new(), colors: Interned::new() }; + t.fonts.insert(font_key(default_font), || default_font.to_string()); for fmt in doc.paras().flat_map(|p| &p.runs).map(|r| &r.fmt) { - if let Some(f) = fmt.font.as_deref().filter(|f| t.font(f).is_none()) { - t.fonts.push(f.to_string()); + if let Some(f) = fmt.font.as_deref() { + t.fonts.insert(font_key(f), || f.to_string()); } - if let Some(c) = fmt.color.filter(|c| t.color(*c).is_none()) { - t.colors.push(c); + if let Some(c) = fmt.color { + t.colors.insert(c, || c); } } t } fn font(&self, name: &str) -> Option<usize> { - self.fonts.iter().position(|f| f.eq_ignore_ascii_case(name)) + self.fonts.get(font_key(name).as_str()) } fn color(&self, c: [u8; 3]) -> Option<usize> { - self.colors.iter().position(|k| *k == c).map(|i| i + 1) + self.colors.get(&c).map(|i| i + 1) } fn fmt_words(&self, f: &CharFmt) -> String { @@ -148,13 +215,13 @@ impl Tables { pub fn write(doc: &Document, default_font: &str) -> String { let t = Tables::of(doc, default_font); let mut o = String::from("{\\rtf1\\ansi\\ansicpg1252\\deff0\\uc1{\\fonttbl"); - for (i, f) in t.fonts.iter().enumerate() { + for (i, f) in t.fonts.items.iter().enumerate() { let _ = write!(o, "{{\\f{i}\\fnil {};}}", esc_font(f)); } o.push_str("}\n"); - if !t.colors.is_empty() { + if !t.colors.items.is_empty() { o.push_str("{\\colortbl;"); - for [r, g, b] in &t.colors { + for [r, g, b] in &t.colors.items { let _ = write!(o, "\\red{r}\\green{g}\\blue{b};"); } o.push_str("}\n"); @@ -196,3 +263,7 @@ pub fn write(doc: &Document, default_font: &str) -> String { o.push('}'); o } + +#[cfg(test)] +#[path = "write_tests.rs"] +mod tests; diff --git a/crates/rtf/src/write_tests.rs b/crates/rtf/src/write_tests.rs new file mode 100644 index 000000000..ff208c88d --- /dev/null +++ b/crates/rtf/src/write_tests.rs @@ -0,0 +1,38 @@ +use super::*; +use crate::model::Run; + +/// A paragraph of `n` runs, each in its own font and colour. +fn varied(n: usize) -> Document { + let runs = (0..n) + .map(|i| Run { + text: "x".into(), + fmt: CharFmt { font: Some(format!("Font {i}")), color: Some([(i >> 16) as u8, (i >> 8) as u8, i as u8]), ..CharFmt::default() }, + }) + .collect(); + Document { blocks: vec![Block::Para(Para { runs, ..Para::default() })], pictures_left_out: 0 } +} + +#[test] +fn many_distinct_fonts_and_colours_take_constant_steps_each() { + let n = 3000; + let doc = varied(n); + let mut out = String::new(); + let steps = lookup_steps(|| out = write(&doc, "Helvetica")); + // The default font, then two lookups per run to build the tables and two to write it. + assert!(steps <= 4 * n + 1, "{steps} steps for {n} runs"); + assert!(out.contains(&format!("{{\\f{n}\\fnil Font {};}}", n - 1)), "the last font has the last slot"); + assert!(out.contains(&format!("\\f{n}\\cf{n} x")), "the last run names the last font and colour"); +} + +#[test] +fn fonts_match_without_regard_to_ascii_case() { + let run = |font: &str| Run { text: "x".into(), fmt: CharFmt { font: Some(font.into()), ..CharFmt::default() } }; + let doc = Document { + blocks: vec![Block::Para(Para { runs: vec![run("Arial"), run("ARIAL"), run("helvetica")], ..Para::default() })], + pictures_left_out: 0, + }; + let out = write(&doc, "Helvetica"); + assert!(out.contains("{\\fonttbl{\\f0\\fnil Helvetica;}{\\f1\\fnil Arial;}}"), "{out}"); + // Both spellings of Arial are font 1; the default font's run names no font. + assert!(out.contains("{\\f1 x}{\\f1 x}x\\par"), "{out}"); +} diff --git a/crates/rtf/tests/read_write.rs b/crates/rtf/tests/read_write.rs index 9ef8fbfb7..32209b992 100644 --- a/crates/rtf/tests/read_write.rs +++ b/crates/rtf/tests/read_write.rs @@ -103,8 +103,8 @@ fn pictures_and_objects_are_counted_not_read() { } #[test] -fn out_of_range_unicode_wraps_and_hyphens_are_text() { - assert_eq!(text(br"{\rtf1 a\u4294967361?b}"), "a\u{FFFF}b", "clamped to i32, then modulo 65536"); +fn invalid_unicode_and_hyphens_are_compatible() { + assert_eq!(text(br"{\rtf1 a\u4294967361?b}"), "ab", "out-of-range signed parameters are dropped"); assert_eq!(text(br"{\rtf1\ansi Rock\emdash-roll, x\tab-y, a\li-720 b}"), "Rock\u{2014}-roll, x\t-y, ab"); assert_eq!(text(br"{\rtf1 {\b A\'4}B}"), "AB"); assert_eq!(text(br"{\rtf1 a\'+fb}"), "a+fb"); @@ -132,9 +132,15 @@ fn nul_is_not_text() { #[test] fn surrogate_pairs() { assert_eq!(text(br"{\rtf1\ansi\uc1 A\u-10179?\u-8704?B \u-10174?\u-8265?\u30000?}"), "A\u{1F600}B \u{20BB7}\u{7530}"); - assert_eq!(text(br"{\rtf1 A\u-10179?B\u-8704?C}"), "A\u{FFFD}B\u{FFFD}C", "half a pair is U+FFFD, as in Word"); - assert_eq!(text(br"{\rtf1 A\u-10179?\par\u-8704?C}"), "A\u{FFFD}\n\u{FFFD}C", "a pair does not span a paragraph end"); - assert_eq!(text(br"{\rtf1 A\u-10179?}"), "A\u{FFFD}"); + assert_eq!(text(br"{\rtf1 A\u-10179?B\u-8704?C}"), "ABC", "unpaired surrogates are dropped, as in the previous DesignCraft reader"); + assert_eq!(text(br"{\rtf1 A\u-10179?\par\u-8704?C}"), "A\nC", "a pair does not span a paragraph end"); + assert_eq!(text(br"{\rtf1 A\u-10179?}"), "A"); +} + +#[test] +fn out_of_range_unicode_escapes_are_dropped() { + assert_eq!(text(br"{\rtf1 a\u4294967361?b}"), "ab"); + assert_eq!(text(br"{\rtf1 a\u-4294967231?b}"), "ab"); } #[test] diff --git a/crates/smime/Cargo.toml b/crates/smime/Cargo.toml new file mode 100644 index 000000000..d2b53cabb --- /dev/null +++ b/crates/smime/Cargo.toml @@ -0,0 +1,44 @@ +[package] +name = "craft-smime" +description = "S/MIME (RFC 8551): Digital signatures checked from CMS (RFC 5652) and X.509 (RFC 5280), no I/O" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-ber = { workspace = true } +serde = { workspace = true } +base64 = "0.23" +# RustCrypto: CMS, X.509, DER, SPKI, OID, RSA, P256, P384, SHA2. +cms = { version = "=0.3.0-rc.2", default-features = false } +x509-cert = { version = "0.3", default-features = false } +der = { version = "0.8", default-features = false, features = ["alloc", "oid"] } +spki = { version = "0.8", default-features = false, features = ["alloc"] } +const-oid = { version = "0.10", default-features = false, features = ["db"] } +# Match craft-pkcs7's RSA pin; parse PKCS #1 separately to avoid incompatible RC encoding APIs. +rsa = { version = "=0.10.0-rc.18", default-features = false } +pkcs1 = { version = "0.8", default-features = false, features = ["alloc"] } +p256 = { version = "0.14", default-features = false, features = ["ecdsa", "alloc"] } +p384 = { version = "0.14", default-features = false, features = ["ecdsa", "alloc"] } +sha2 = { version = "0.11", default-features = false, features = ["oid"] } +# PKCS #12 file handling (RFC 7292 Appendix B): PBES2, triple-DES key derivation. +pkcs12 = { version = "=0.2.0-rc.0", default-features = false, features = ["kdf"] } +pbkdf2 = { version = "0.13", default-features = false, features = ["hmac"] } +hmac = { version = "0.13", default-features = false } +sha1 = { version = "0.11", default-features = false } +aes = { version = "0.9", default-features = false } +des = { version = "0.9", default-features = false } +cbc = { version = "0.2", default-features = false, features = ["block-padding"] } +zeroize = { version = "1", default-features = false, features = ["alloc"] } +# Error handling. +thiserror = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } +rcgen = { version = "0.14.10", default-features = false, features = ["crypto", "ring"] } +ring = "0.17" diff --git a/crates/smime/src/algorithms.rs b/crates/smime/src/algorithms.rs new file mode 100644 index 000000000..ba9837acd --- /dev/null +++ b/crates/smime/src/algorithms.rs @@ -0,0 +1,283 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! The algorithms a Digital signature or a certificate is checked with (RFC 8551 §2, RFC 5754, +//! RFC 4055, RFC 5480): SHA-2 digests, RSA (PKCS #1 v1.5 and PSS, 2048 bits or more) and ECDSA +//! on P-256 and P-384. MD5, SHA-1 and shorter RSA keys are no longer safe and are refused as +//! such; anything else is unknown. The primitives are RustCrypto's; this only names them. + +use const_oid::ObjectIdentifier; +use der::{Decode, Encode}; +use sha2::Digest; +use spki::{AlgorithmIdentifierOwned, SubjectPublicKeyInfoOwned}; + +/// Why a signature didn't check out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Fault { + /// It doesn't match: what it covers was changed, or another key made it. + Invalid, + /// It uses an algorithm that's no longer safe (MD5, SHA-1, RSA under 2048 bits). + Weak, + /// It uses an algorithm that isn't known here. + Unknown, + /// The key or the signature can't be read, or they are of different kinds: nothing can be + /// said of what it covers. + Malformed, +} + +/// The least RSA modulus, in bits, that is safe enough (RFC 8551 §6). +pub const MIN_RSA_BITS: usize = 2048; +/// The largest RSA modulus checked, in bits: a longer key takes too long to be worth it. +pub const MAX_RSA_BITS: usize = 8192; + +const fn oid(s: &str) -> ObjectIdentifier { + ObjectIdentifier::new_unwrap(s) +} + +// Digests. +const MD5: ObjectIdentifier = oid("1.2.840.113549.2.5"); +const SHA1: ObjectIdentifier = oid("1.3.14.3.2.26"); +const SHA224: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.4"); +const SHA256: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.1"); +const SHA384: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.2"); +const SHA512: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.3"); + +// RSA. +const RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.1"); +const MD2_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.2"); +const MD5_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.4"); +const SHA1_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.5"); +const PSS: ObjectIdentifier = oid("1.2.840.113549.1.1.10"); +const SHA256_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.11"); +const SHA384_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.12"); +const SHA512_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.13"); +const SHA224_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.14"); +const MGF1: ObjectIdentifier = oid("1.2.840.113549.1.1.8"); + +/// The bits of an RSA modulus written big-endian. +fn modulus_bits(modulus: &[u8]) -> usize { + let mut significant = modulus.iter().skip_while(|b| **b == 0); + let top = significant.next().copied().unwrap_or(0); + significant.count().saturating_mul(8).saturating_add(8usize.saturating_sub(top.leading_zeros() as usize)) +} + +/// What kind of key `key` is: RSA of so many bits, ECDSA on P-256 or P-384, or another. +pub(crate) fn key_kind(key: &SubjectPublicKeyInfoOwned) -> crate::pkcs12::KeyKind { + use crate::pkcs12::KeyKind; + if key.algorithm.oid == RSA { + return key + .subject_public_key + .as_bytes() + .and_then(|b| pkcs1::RsaPublicKey::<der::asn1::UintRef<'_>>::from_der(b).ok()) + .map_or(KeyKind::Other, |k| KeyKind::Rsa { bits: modulus_bits(k.modulus.as_bytes()) }); + } + if key.algorithm.oid == EC_KEY { + return match key.algorithm.parameters.as_ref().and_then(|p| p.decode_as::<ObjectIdentifier>().ok()) { + Some(P256) => KeyKind::P256, + Some(P384) => KeyKind::P384, + _ => KeyKind::Other, + }; + } + KeyKind::Other +} + +/// What kind of private key a PKCS #8 `PrivateKeyInfo` holds, from its own algorithm identifier +/// (`algorithm`; for EC, its named `curve`, from the identifier's parameters or the key's own) +/// and, for RSA, its `modulus` (big-endian): never from a certificate that came with it. +pub(crate) fn private_key_kind(algorithm: ObjectIdentifier, curve: Option<ObjectIdentifier>, modulus: Option<&[u8]>) -> crate::pkcs12::KeyKind { + use crate::pkcs12::KeyKind; + match (algorithm, curve, modulus) { + (RSA, _, Some(modulus)) => KeyKind::Rsa { bits: modulus_bits(modulus) }, + (EC_KEY, Some(P256), _) => KeyKind::P256, + (EC_KEY, Some(P384), _) => KeyKind::P384, + _ => KeyKind::Other, + } +} + +// ECDSA. +const EC_KEY: ObjectIdentifier = oid("1.2.840.10045.2.1"); +const SHA1_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.1"); +const SHA224_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.1"); +const SHA256_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.2"); +const SHA384_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.3"); +const SHA512_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.4"); +const P256: ObjectIdentifier = oid("1.2.840.10045.3.1.7"); +const P384: ObjectIdentifier = oid("1.3.132.0.34"); + +/// A digest algorithm that is safe to rely on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Hash { + Sha224, + Sha256, + Sha384, + Sha512, +} + +impl Hash { + /// The digest a CMS `digestAlgorithm` names. + pub fn of(algorithm: &AlgorithmIdentifierOwned) -> Result<Hash, Fault> { + Hash::by_oid(algorithm.oid) + } + + fn by_oid(oid: ObjectIdentifier) -> Result<Hash, Fault> { + match oid { + SHA224 => Ok(Hash::Sha224), + SHA256 => Ok(Hash::Sha256), + SHA384 => Ok(Hash::Sha384), + SHA512 => Ok(Hash::Sha512), + MD5 | SHA1 => Err(Fault::Weak), + _ => Err(Fault::Unknown), + } + } + + /// The digest of `data`. + pub fn digest(self, data: &[u8]) -> Vec<u8> { + match self { + Hash::Sha224 => sha2::Sha224::digest(data).to_vec(), + Hash::Sha256 => sha2::Sha256::digest(data).to_vec(), + Hash::Sha384 => sha2::Sha384::digest(data).to_vec(), + Hash::Sha512 => sha2::Sha512::digest(data).to_vec(), + } + } +} + +/// How a signature is made. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Scheme { + Pkcs1(Hash), + Pss(Hash, usize), + Ecdsa(Hash), +} + +/// The scheme `algorithm` names; `digest` is the CMS signer's digest algorithm, for the names +/// that leave the hash to it (`rsaEncryption`, `id-ecPublicKey`), `None` for a certificate. +fn scheme(algorithm: &AlgorithmIdentifierOwned, digest: Option<Hash>) -> Result<Scheme, Fault> { + match algorithm.oid { + RSA => digest.map(Scheme::Pkcs1).ok_or(Fault::Unknown), + SHA224_RSA => Ok(Scheme::Pkcs1(Hash::Sha224)), + SHA256_RSA => Ok(Scheme::Pkcs1(Hash::Sha256)), + SHA384_RSA => Ok(Scheme::Pkcs1(Hash::Sha384)), + SHA512_RSA => Ok(Scheme::Pkcs1(Hash::Sha512)), + MD2_RSA | MD5_RSA | SHA1_RSA | SHA1_ECDSA => Err(Fault::Weak), + PSS => pss(algorithm), + EC_KEY => digest.map(Scheme::Ecdsa).ok_or(Fault::Unknown), + SHA224_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha224)), + SHA256_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha256)), + SHA384_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha384)), + SHA512_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha512)), + _ => Err(Fault::Unknown), + } +} + +/// RSASSA-PSS with its parameters (RFC 4055 §3.1): the hash, MGF1 with the same hash, and the +/// salt's length. Their defaults are SHA-1, which is no longer safe. +fn pss(algorithm: &AlgorithmIdentifierOwned) -> Result<Scheme, Fault> { + let params = algorithm.parameters.as_ref().ok_or(Fault::Weak)?; + let der = params.to_der().map_err(|_| Fault::Unknown)?; + let params = pkcs1::RsaPssParams::<der::Any>::from_der(&der).map_err(|_| Fault::Unknown)?; + let hash = Hash::by_oid(params.hash.oid)?; + if params.mask_gen.oid != MGF1 { + return Err(Fault::Unknown); + } + let mgf_hash = params.mask_gen.parameters.as_ref().map(|p| p.oid).ok_or(Fault::Weak)?; + if Hash::by_oid(mgf_hash)? != hash { + return Err(Fault::Unknown); + } + Ok(Scheme::Pss(hash, usize::from(params.salt_len))) +} + +/// Check `signature` over `data` with the key `key`, by `algorithm` (and `digest`, for a CMS +/// signer: see [`scheme`]). +pub fn verify( + key: &SubjectPublicKeyInfoOwned, + algorithm: &AlgorithmIdentifierOwned, + digest: Option<Hash>, + data: &[u8], + signature: &[u8], +) -> Result<(), Fault> { + verify_hashed(key, algorithm, digest, &mut |hash| hash.digest(data), signature) +} + +/// [`verify`], with what was signed given by its digest: `hashed` gives it by each algorithm +/// (so that a long content is hashed once per algorithm however many keys are tried). +pub fn verify_hashed( + key: &SubjectPublicKeyInfoOwned, + algorithm: &AlgorithmIdentifierOwned, + digest: Option<Hash>, + hashed: &mut dyn FnMut(Hash) -> Vec<u8>, + signature: &[u8], +) -> Result<(), Fault> { + // RFC 4055 3.3: an id-RSASSA-PSS SPKI restricts schemes and parameters. + // Those restrictions are not implemented here; do not treat it as rsaEncryption. + if key.algorithm.oid == PSS { + return Err(Fault::Unknown); + } + let scheme = scheme(algorithm, digest)?; + match scheme { + Scheme::Pkcs1(hash) | Scheme::Pss(hash, _) => { + if key.algorithm.oid != RSA { + return Err(Fault::Malformed); + } + let public = rsa_key(key)?; + let hashed = hashed(hash); + let checked = match scheme { + Scheme::Pss(_, salt) => match hash { + Hash::Sha224 => public.verify(rsa::pss::Pss::<sha2::Sha224>::new_with_salt(salt), &hashed, signature), + Hash::Sha256 => public.verify(rsa::pss::Pss::<sha2::Sha256>::new_with_salt(salt), &hashed, signature), + Hash::Sha384 => public.verify(rsa::pss::Pss::<sha2::Sha384>::new_with_salt(salt), &hashed, signature), + Hash::Sha512 => public.verify(rsa::pss::Pss::<sha2::Sha512>::new_with_salt(salt), &hashed, signature), + }, + _ => { + let padding = match hash { + Hash::Sha224 => rsa::Pkcs1v15Sign::new::<sha2::Sha224>(), + Hash::Sha256 => rsa::Pkcs1v15Sign::new::<sha2::Sha256>(), + Hash::Sha384 => rsa::Pkcs1v15Sign::new::<sha2::Sha384>(), + Hash::Sha512 => rsa::Pkcs1v15Sign::new::<sha2::Sha512>(), + }; + public.verify(padding, &hashed, signature) + } + }; + checked.map_err(|_| Fault::Invalid) + } + Scheme::Ecdsa(hash) => { + if key.algorithm.oid != EC_KEY { + return Err(Fault::Malformed); + } + let curve = key.algorithm.parameters.as_ref().and_then(|p| p.decode_as::<ObjectIdentifier>().ok()).ok_or(Fault::Unknown)?; + let point = key.subject_public_key.as_bytes().ok_or(Fault::Unknown)?; + let hashed = hashed(hash); + use p256::ecdsa::signature::hazmat::PrehashVerifier; + match curve { + P256 => { + let key = p256::ecdsa::VerifyingKey::from_sec1_bytes(point).map_err(|_| Fault::Malformed)?; + let sig = p256::ecdsa::Signature::from_der(signature).map_err(|_| Fault::Malformed)?; + key.verify_prehash(&hashed, &sig).map_err(|_| Fault::Invalid) + } + P384 => { + let key = p384::ecdsa::VerifyingKey::from_sec1_bytes(point).map_err(|_| Fault::Malformed)?; + let sig = p384::ecdsa::Signature::from_der(signature).map_err(|_| Fault::Malformed)?; + key.verify_prehash(&hashed, &sig).map_err(|_| Fault::Invalid) + } + _ => Err(Fault::Unknown), + } + } + } +} + +/// The RSA key of `key`: [`Fault::Weak`] under [`MIN_RSA_BITS`], [`Fault::Unknown`] past what +/// the library takes (8192 bits) or when it can't be read. +fn rsa_key(key: &SubjectPublicKeyInfoOwned) -> Result<rsa::RsaPublicKey, Fault> { + let bits = key.subject_public_key.as_bytes().ok_or(Fault::Unknown)?; + let pkcs1 = pkcs1::RsaPublicKey::<der::asn1::UintRef<'_>>::from_der(bits).map_err(|_| Fault::Unknown)?; + let bits = modulus_bits(pkcs1.modulus.as_bytes()); + if bits < MIN_RSA_BITS { + return Err(Fault::Weak); + } + if bits > MAX_RSA_BITS { + return Err(Fault::Unknown); + } + rsa::RsaPublicKey::new( + rsa::BoxedUint::from_be_slice_vartime(pkcs1.modulus.as_bytes()), + rsa::BoxedUint::from_be_slice_vartime(pkcs1.public_exponent.as_bytes()), + ) + .map_err(|_| Fault::Unknown) +} diff --git a/crates/smime/src/cert.rs b/crates/smime/src/cert.rs new file mode 100644 index 000000000..28968f27f --- /dev/null +++ b/crates/smime/src/cert.rs @@ -0,0 +1,448 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! An X.509 certificate (RFC 5280) as a Digital signature is checked with: its bytes, what it +//! says, and the few questions asked of it (who it names, for what, until when, who signed it). + +use crate::Timestamp; +use crate::digital_signature::{MAX_SIGNER_ADDRESSES, signer_text}; +use const_oid::ObjectIdentifier; +use der::{Decode, Encode}; +use x509_cert::Certificate; +use x509_cert::ext::pkix::constraints::name::GeneralSubtrees; +use x509_cert::ext::pkix::name::GeneralName; +use x509_cert::ext::pkix::{ + AuthorityKeyIdentifier, BasicConstraints, CertificatePolicies, ExtendedKeyUsage, KeyUsage, NameConstraints, SubjectAltName, SubjectKeyIdentifier, +}; + +use crate::algorithms::{self, Fault}; +use craft_ber as ber; + +/// The largest certificate read. +pub const MAX_CERT_BYTES: usize = 64 * 1024; + +const EMAIL_PROTECTION: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.4"); +const ANY_EXTENDED_KEY_USAGE: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.29.37.0"); +const EMAIL_ADDRESS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.1"); + +/// The extensions whose meaning is known here (RFC 5280 §4.2): a certificate with any other +/// marked critical is refused (§6.1.4 (o)). Certificate policies are taken as any policy (no +/// policy is asked for, §6.1.1 (c)); the identifiers say nothing to check. +const KNOWN: [ObjectIdentifier; 8] = [ + ObjectIdentifier::new_unwrap("2.5.29.14"), // subject key identifier + ObjectIdentifier::new_unwrap("2.5.29.15"), // key usage + ObjectIdentifier::new_unwrap("2.5.29.17"), // subject alternative name + ObjectIdentifier::new_unwrap("2.5.29.19"), // basic constraints + ObjectIdentifier::new_unwrap("2.5.29.30"), // name constraints + ObjectIdentifier::new_unwrap("2.5.29.32"), // certificate policies + ObjectIdentifier::new_unwrap("2.5.29.35"), // authority key identifier + ObjectIdentifier::new_unwrap("2.5.29.37"), // extended key usage +]; + +/// The name constraints a certification authority puts on what it vouches for (RFC 5280 +/// §4.2.1.10), for the two kinds of name a mail certificate has: mail addresses and directory +/// names. The other kinds name nothing that is checked here. +#[derive(Clone, Debug, Default)] +pub struct Constraints { + pub permitted_mail: Option<Vec<String>>, + pub excluded_mail: Vec<String>, + pub permitted_dirs: Option<Vec<Vec<Vec<u8>>>>, + pub excluded_dirs: Vec<Vec<Vec<u8>>>, +} + +/// A directory identity represented as ordered DER relative names. +pub type DirectoryName = Vec<Vec<u8>>; + +/// A certificate: its DER, the body its issuer signed, and what it says. +#[derive(Clone, Debug)] +pub struct Cert { + der: Vec<u8>, + /// Where the to-be-signed body is in `der`. + tbs: std::ops::Range<usize>, + parsed: Certificate, + subject: Vec<u8>, + issuer: Vec<u8>, +} + +impl PartialEq for Cert { + fn eq(&self, other: &Self) -> bool { + self.der == other.der + } +} + +impl Cert { + /// The certificate `der` is, when it is one. + pub fn from_der(der: &[u8]) -> Option<Cert> { + if der.len() > MAX_CERT_BYTES { + return None; + } + let (outer, rest) = ber::read(der)?; + if !rest.is_empty() { + return None; + } + let (tbs, _) = ber::read(outer.value)?; + let start = outer.whole.len().checked_sub(outer.value.len())?; + let end = start.checked_add(tbs.whole.len())?; + let parsed = Certificate::from_der(der).ok()?; + // RFC 5280 4.1.1.2: the outer and signed algorithm identifiers must agree. + if parsed.signature_algorithm() != parsed.tbs_certificate().signature() { + return None; + } + // A recognized extension that cannot be decoded is not an absent extension. + // In particular, never fall back to the subject identity after a malformed SAN. + let tbs = parsed.tbs_certificate(); + if tbs.get_extension::<SubjectAltName>().is_err() + || tbs.get_extension::<SubjectKeyIdentifier>().is_err() + || tbs.get_extension::<AuthorityKeyIdentifier>().is_err() + || tbs.get_extension::<KeyUsage>().is_err() + || tbs.get_extension::<ExtendedKeyUsage>().is_err() + || tbs.get_extension::<BasicConstraints>().is_err() + || tbs.get_extension::<NameConstraints>().is_err() + || tbs.get_extension::<CertificatePolicies>().is_err() + { + return None; + } + let subject = parsed.tbs_certificate().subject().to_der().ok()?; + let issuer = parsed.tbs_certificate().issuer().to_der().ok()?; + Some(Cert { der: der.to_vec(), tbs: start..end, parsed, subject, issuer }) + } + + pub fn der(&self) -> &[u8] { + &self.der + } + + fn tbs(&self) -> &[u8] { + self.der.get(self.tbs.clone()).unwrap_or_default() + } + + pub fn subject(&self) -> &[u8] { + &self.subject + } + + pub fn issuer(&self) -> &[u8] { + &self.issuer + } + + /// The serial number's bytes. + pub fn serial(&self) -> &[u8] { + self.parsed.tbs_certificate().serial_number().as_bytes() + } + + /// The subject key identifier, when it has one. + pub fn key_id(&self) -> Option<Vec<u8>> { + let (_, ski) = self.parsed.tbs_certificate().get_extension::<SubjectKeyIdentifier>().ok()??; + Some(ski.0.as_bytes().to_vec()) + } + + pub fn public_key(&self) -> &spki::SubjectPublicKeyInfoOwned { + self.parsed.tbs_certificate().subject_public_key_info() + } + + /// Its SHA-256 fingerprint: upper-case hexadecimal pairs with colons between. + pub fn fingerprint(&self) -> String { + algorithms::Hash::Sha256.digest(&self.der).iter().map(|b| format!("{b:02X}")).collect::<Vec<_>>().join(":") + } + + /// From and until when it is valid, in seconds since 1970. + pub fn validity(&self) -> (Timestamp, Timestamp) { + let v = self.parsed.tbs_certificate().validity(); + let secs = |t: &x509_cert::time::Time| Timestamp::try_from(t.to_unix_duration().as_secs()).unwrap_or(Timestamp::MAX); + (secs(&v.not_before), secs(&v.not_after)) + } + + /// Whether it is valid at `now`. + pub fn valid_at(&self, now: Timestamp) -> bool { + let (from, until) = self.validity(); + from <= now && now <= until + } + + /// The name it is for: its common name, else its whole name. + pub fn name(&self) -> String { + name_of(self.parsed.tbs_certificate().subject()) + } + + /// The name of who issued it. + pub fn issuer_name(&self) -> String { + name_of(self.parsed.tbs_certificate().issuer()) + } + + /// The mail addresses it is for: its subject alternative names of that kind, and an + /// `emailAddress` in its subject (RFC 8551 §3.1), at most [`MAX_SIGNER_ADDRESSES`]. + pub fn addresses(&self) -> Vec<String> { + let mut out = Vec::new(); + if let Ok(Some((_, san))) = self.parsed.tbs_certificate().get_extension::<SubjectAltName>() { + for name in san.0.iter() { + if let GeneralName::Rfc822Name(a) = name { + out.push(signer_text(a.as_str())); + } + } + } + for atv in self.parsed.tbs_certificate().subject().iter() { + if atv.oid == EMAIL_ADDRESS + && let Ok(a) = atv.value.decode_as::<der::asn1::Ia5String>() + { + out.push(signer_text(a.as_str())); + } + } + out.retain(|a| !a.is_empty()); + out.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); + out.truncate(MAX_SIGNER_ADDRESSES); + out + } + + /// The mail addresses it names, exactly as written (its alternative names of that kind and + /// the `emailAddress` in its subject), all of them: for comparing + /// and for name constraints, never for showing. The certificate byte cap bounds this list; display truncation + /// must not hide names from certification-authority constraints. + pub fn raw_addresses(&self) -> Vec<String> { + let mut out = Vec::new(); + if let Ok(Some((_, san))) = self.parsed.tbs_certificate().get_extension::<SubjectAltName>() { + out.extend(san.0.iter().filter_map(|n| match n { + GeneralName::Rfc822Name(a) => Some(a.as_str().to_string()), + _ => None, + })); + } + out.extend( + self.parsed + .tbs_certificate() + .subject() + .iter() + .filter(|atv| atv.oid == EMAIL_ADDRESS) + .filter_map(|atv| atv.value.decode_as::<der::asn1::Ia5String>().ok()) + .map(|a| a.as_str().to_string()), + ); + out + } + + /// Whether it is for `address`: one of its addresses as written is that address, letter case + /// aside in plain ASCII (RFC 5280 §4.2.1.6, §7.5). An address with a space, a control or any + /// character past ASCII on either side never is. + pub fn is_for(&self, address: &str) -> bool { + printable(address) && self.raw_addresses().iter().any(|a| printable(a) && a.eq_ignore_ascii_case(address)) + } + + /// The address of its it is for `address` by ([`Cert::is_for`]), as it shows it. + pub fn address_for(&self, address: &str) -> Option<String> { + printable(address).then(|| self.raw_addresses().into_iter().find(|a| printable(a) && a.eq_ignore_ascii_case(address))).flatten() + } + + /// Whether it carries an extension marked critical that isn't known here. + pub fn unknown_critical(&self) -> bool { + self.parsed.tbs_certificate().extensions().is_some_and(|exts| exts.iter().any(|e| e.critical && !KNOWN.contains(&e.extn_id))) + } + + /// Its path length constraint, when its basic constraints give one (unreadable: none + /// allowed below it). + pub fn path_len(&self) -> Option<u8> { + match self.parsed.tbs_certificate().get_extension::<BasicConstraints>() { + Ok(Some((_, bc))) => bc.path_len_constraint, + Ok(None) => None, + Err(_) => Some(0), + } + } + + /// Whether, as a certification authority on a path, its extended key usage (when it has + /// one) lets it vouch for mail: email protection, or any use. + pub fn may_vouch_for_mail(&self) -> bool { + match self.parsed.tbs_certificate().get_extension::<ExtendedKeyUsage>() { + Ok(Some((_, eku))) => eku.0.iter().any(|o| *o == EMAIL_PROTECTION || *o == ANY_EXTENDED_KEY_USAGE), + Ok(None) => true, + Err(_) => false, + } + } + + /// Whether it is a certification authority's by any sign (basic constraints say so, or its + /// key usage lets it sign certificates): never a mail signer's. + pub fn is_authority(&self) -> bool { + let tbs = self.parsed.tbs_certificate(); + let ca = matches!(tbs.get_extension::<BasicConstraints>(), Ok(Some((_, bc))) if bc.ca); + let signs = matches!(tbs.get_extension::<KeyUsage>(), Ok(Some((_, ku))) if ku.key_cert_sign()); + ca || signs + } + + /// The name constraints it puts on what it vouches for; `Err` when they can't be read or use + /// what RFC 5280 says mustn't be (a minimum or a maximum). + pub fn constraints(&self) -> Result<Option<Constraints>, ()> { + let Some((_, nc)) = self.parsed.tbs_certificate().get_extension::<NameConstraints>().map_err(|_| ())? else { return Ok(None) }; + let mut c = Constraints::default(); + if let Some(permitted) = &nc.permitted_subtrees { + let (mail, dirs) = subtrees(permitted)?; + c.permitted_mail = mail; + c.permitted_dirs = dirs; + } + if let Some(excluded) = &nc.excluded_subtrees { + let (mail, dirs) = subtrees(excluded)?; + c.excluded_mail = mail.unwrap_or_default(); + c.excluded_dirs = dirs.unwrap_or_default(); + } + Ok(Some(c)) + } + + /// Every directory identity: the nonempty subject and every directoryName SAN. + pub fn directory_names(&self) -> Option<Vec<DirectoryName>> { + let rdns = |name: &x509_cert::name::Name| name.iter_rdn().map(|r| r.to_der().ok()).collect::<Option<Vec<_>>>(); + let mut names = Vec::new(); + let subject = rdns(self.parsed.tbs_certificate().subject())?; + if !subject.is_empty() { + names.push(subject); + } + if let Some((_, san)) = self.parsed.tbs_certificate().get_extension::<SubjectAltName>().ok()? { + for name in &san.0 { + if let GeneralName::DirectoryName(name) = name { + names.push(rdns(name)?); + } + } + } + Some(names) + } + + /// Whether it may be a certification authority's: basic constraints say so, and its key + /// usage, when it has one, lets it sign certificates. + pub fn is_ca(&self) -> bool { + let tbs = self.parsed.tbs_certificate(); + let ca = matches!(tbs.get_extension::<BasicConstraints>(), Ok(Some((_, bc))) if bc.ca); + let signs = match tbs.get_extension::<KeyUsage>() { + Ok(Some((_, ku))) => ku.key_cert_sign(), + Ok(None) => true, + Err(_) => false, + }; + ca && signs + } + + /// Whether it is for signing mail (RFC 8551 §4.4): its key usage, when it has one, allows a + /// Digital signature or non-repudiation, and its extended key usage, when it has one, names + /// email protection (or any use). + pub fn for_email(&self) -> bool { + let tbs = self.parsed.tbs_certificate(); + let usage = match tbs.get_extension::<KeyUsage>() { + Ok(Some((_, ku))) => ku.digital_signature() || ku.non_repudiation(), + Ok(None) => true, + Err(_) => false, + }; + let extended = match tbs.get_extension::<ExtendedKeyUsage>() { + Ok(Some((_, eku))) => eku.0.iter().any(|o| *o == EMAIL_PROTECTION || *o == ANY_EXTENDED_KEY_USAGE), + Ok(None) => true, + Err(_) => false, + }; + usage && extended + } + + /// Whether it is for mail at all, to sign it or to encrypt it (RFC 8551 §4.4): its key usage, + /// when it has one, allows a Digital signature, non-repudiation, key encipherment or key + /// agreement, and its extended key usage, when it has one, names email protection (or any + /// use). What a Public key imported for an address must be. + pub fn for_mail(&self) -> bool { + let tbs = self.parsed.tbs_certificate(); + let usage = match tbs.get_extension::<KeyUsage>() { + Ok(Some((_, ku))) => ku.digital_signature() || ku.non_repudiation() || ku.key_encipherment() || ku.key_agreement(), + Ok(None) => true, + Err(_) => false, + }; + usage && self.may_vouch_for_mail() + } + + /// Whether it names itself as its issuer. + pub fn self_issued(&self) -> bool { + self.subject == self.issuer + } + + /// Whether `issuer`'s key made its signature. + pub fn signed_by(&self, issuer: &Cert) -> Result<(), Fault> { + let signature = self.parsed.signature().as_bytes().ok_or(Fault::Invalid)?; + algorithms::verify(issuer.public_key(), self.parsed.signature_algorithm(), None, self.tbs(), signature) + } +} + +/// Whether `address` has only the printable ASCII an address is compared in (and something). +pub(crate) fn printable(address: &str) -> bool { + !address.is_empty() && address.bytes().all(|b| (0x21..=0x7e).contains(&b)) +} + +/// The mail and directory names of `subtrees` (`None` of a kind: none of that kind given). +type Subtrees = (Option<Vec<String>>, Option<Vec<Vec<Vec<u8>>>>); + +fn subtrees(subtrees: &GeneralSubtrees) -> Result<Subtrees, ()> { + let (mut mail, mut dirs): Subtrees = (None, None); + for s in subtrees.iter().take(64) { + if s.minimum != 0 || s.maximum.is_some() { + return Err(()); + } + match &s.base { + GeneralName::Rfc822Name(a) => mail.get_or_insert_with(Vec::new).push(a.as_str().to_string()), + GeneralName::DirectoryName(n) => dirs.get_or_insert_with(Vec::new).push(n.iter_rdn().filter_map(|r| r.to_der().ok()).collect()), + // RFC 5280 4.2.1.10: constraints cannot be treated as processed when + // this validator does not implement their name form. Fail closed. + _ => return Err(()), + } + } + if subtrees.len() > 64 { + return Err(()); + } + Ok((mail, dirs)) +} + +/// Whether the mail address `address` is within the constraint `base` (RFC 5280 §4.2.1.10): a +/// whole address, every address at one host, or (with a leading dot) every address at any host +/// under a domain. Letter case aside. +pub fn mail_within(address: &str, base: &str) -> bool { + let address = address.to_ascii_lowercase(); + let base = base.to_ascii_lowercase(); + if base.contains('@') { + return address == base; + } + let Some((_, host)) = address.rsplit_once('@') else { return false }; + if let Some(domain) = base.strip_prefix('.') { + return host.len() > domain.len() && host.ends_with(domain) && host.as_bytes().get(host.len() - domain.len() - 1) == Some(&b'.'); + } + host == base +} + +/// Whether the name `rdns` is within the directory name `base`: it begins with all of it, each +/// relative name compared using the supported ASCII subset of RFC 5280 §7.1. +/// Unsupported string types or non-ASCII values must fail closed in the caller. +pub fn dir_within(rdns: &[Vec<u8>], base: &[Vec<u8>]) -> bool { + rdns.len() >= base.len() && rdns.iter().zip(base).all(|(a, b)| matches!((rdn_key(a), rdn_key(b)), (Some(x), Some(y)) if x == y)) +} + +/// Whether every relative name is within the supported comparison profile. +pub fn directory_supported(rdns: &[Vec<u8>]) -> bool { + rdns.iter().all(|rdn| rdn_key(rdn).is_some()) +} + +fn rdn_key(der: &[u8]) -> Option<Vec<(String, Vec<u8>)>> { + use der::Tag; + let rdn = x509_cert::name::RelativeDistinguishedName::from_der(der).ok()?; + let mut key: Vec<(String, Vec<u8>)> = rdn + .iter() + .map(|atv| { + let value = match der::Tagged::tag(&atv.value) { + Tag::PrintableString | Tag::Utf8String => { + let text = std::str::from_utf8(atv.value.value()).ok()?; + // RFC 5280 7.1 requires StringPrep for non-ASCII names. Until the + // complete profile is implemented, constrained chains fail closed. + if !text.is_ascii() { + return None; + } + let folded: Vec<String> = text.split_whitespace().map(str::to_lowercase).collect(); + let mut v = b"s".to_vec(); + v.extend_from_slice(folded.join(" ").as_bytes()); + v + } + _ => return None, + }; + Some((atv.oid.to_string(), value)) + }) + .collect::<Option<_>>()?; + key.sort(); + Some(key) +} + +/// A name for people: its common name, else the whole of it as RFC 4514 writes it. +fn name_of(name: &x509_cert::name::Name) -> String { + if let Ok(Some(cn)) = name.common_name() { + let cn = signer_text(&cn.value()); + if !cn.is_empty() { + return cn; + } + } + signer_text(&name.to_string()) +} diff --git a/crates/smime/src/chain.rs b/crates/smime/src/chain.rs new file mode 100644 index 000000000..81d52b71d --- /dev/null +++ b/crates/smime/src/chain.rs @@ -0,0 +1,232 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Whether a signer's certificate rests on a trust anchor (RFC 5280 §6, as S/MIME needs it): a +//! path from it through certification authorities' certificates that came with the message, to +//! a certificate the host trusts. Each link's signature is checked, and every certificate on the +//! path must be valid at the time of the check and keep its authorities' constraints. Bounded: a +//! path is at most [`MAX_PATH`] long, and the signatures checked come out of the message's +//! budget ([`crate::MAX_VERIFICATIONS`]). + +use std::collections::HashMap; + +use crate::Timestamp; +use crate::digital_signature::Why; + +use crate::algorithms::Fault; +use crate::cert::{Cert, Constraints, dir_within, directory_supported, mail_within}; + +/// The most certificates between a signer's and a trust anchor. +pub const MAX_PATH: usize = 6; +/// The most trust anchors kept. +pub const MAX_ANCHORS: usize = 4_000; + +/// The certificates the host trusts (the system's certification authorities, handed in: this +/// crate never reads a store of its own). +#[derive(Clone, Debug, Default)] +pub struct Anchors { + certs: Vec<Cert>, + by_subject: HashMap<Vec<u8>, Vec<usize>>, +} + +impl Anchors { + /// Anchors from certificates in DER; one that isn't a certificate is left out, as is + /// everything past [`MAX_ANCHORS`]. + pub fn new<I, B>(ders: I) -> Anchors + where + I: IntoIterator<Item = B>, + B: AsRef<[u8]>, + { + let mut anchors = Anchors::default(); + for der in ders { + if anchors.certs.len() >= MAX_ANCHORS { + break; + } + if let Some(cert) = Cert::from_der(der.as_ref()) { + anchors.by_subject.entry(cert.subject().to_vec()).or_default().push(anchors.certs.len()); + anchors.certs.push(cert); + } + } + anchors + } + + pub fn len(&self) -> usize { + self.certs.len() + } + + pub fn is_empty(&self) -> bool { + self.certs.is_empty() + } + + fn named(&self, subject: &[u8]) -> impl Iterator<Item = &Cert> { + self.by_subject.get(subject).into_iter().flatten().filter_map(|i| self.certs.get(*i)) + } + + fn holds(&self, cert: &Cert) -> bool { + self.named(cert.subject()).any(|a| a == cert) + } +} + +/// Whether `leaf` rests on one of `anchors` through the certificates of `pool`, at `now`, +/// checking at most `budget` signatures (taken from it). Every path to an anchor is tried until +/// one holds (RFC 5280 §6.1): each certificate on it valid at `now`, none with a critical +/// extension not known here, each authority's path length and name constraints kept, and every +/// authority's extended key usage, when it has one, allowing mail. +/// +/// (Validity is checked at the time of the check, not the signing time the signer gives: that is +/// the signer's own word, and a certificate that ran out or was replaced since is said.) +pub fn trust(leaf: &Cert, pool: &[Cert], anchors: &Anchors, now: Timestamp, budget: &mut usize) -> Result<(), Why> { + let mut search = Search { leaf, pool, anchors, now, budget, weak: false, refused: None, ran_out: false }; + let mut path = Vec::new(); + if search.walk(leaf, &mut path) { + return Ok(()); + } + Err(match search.refused { + // (A path left untried may hold: no answer, rather than the first refusal's.) + _ if search.ran_out => Why::TooMuch, + Some(why) => why, + None if search.weak => Why::WeakAlgorithm, + None if leaf.self_issued() => Why::SelfSigned, + None => Why::UnknownIssuer, + }) +} + +struct Search<'a, 'b> { + leaf: &'a Cert, + pool: &'a [Cert], + anchors: &'a Anchors, + now: Timestamp, + budget: &'b mut usize, + /// A link was signed with an algorithm that's no longer safe. + weak: bool, + /// Why the first path found to an anchor didn't hold. + refused: Option<Why>, + /// The budget ran out before every path was tried. + ran_out: bool, +} + +impl<'a> Search<'a, '_> { + /// Whether `cert` rests on an anchor by a path that holds; `path` has the certificates above + /// the leaf so far, the anchor last once one is reached. + fn walk(&mut self, cert: &'a Cert, path: &mut Vec<&'a Cert>) -> bool { + // A certificate the host trusts itself ends the path, whether it holds or not. + if self.anchors.holds(cert) { + return self.holds(path); + } + for anchor in self.anchors.named(cert.issuer()) { + if self.signed(cert, anchor) { + path.push(anchor); + if self.holds(path) { + return true; + } + path.pop(); + } + } + if path.len() >= MAX_PATH { + return false; + } + for issuer in self.pool.iter().filter(|c| c.subject() == cert.issuer() && *c != cert && c.is_ca()) { + // (No certificate twice on a path.) + if path.contains(&issuer) || !self.signed(cert, issuer) { + continue; + } + path.push(issuer); + if self.walk(issuer, path) { + return true; + } + path.pop(); + } + false + } + + /// Whether the path from the leaf through `above` (the anchor last) holds; why not is kept. + fn holds(&mut self, above: &[&Cert]) -> bool { + let full: Vec<&Cert> = std::iter::once(self.leaf).chain(above.iter().copied()).collect(); + match judge(&full, self.now) { + Ok(()) => true, + Err(why) => { + self.refused.get_or_insert(why); + false + } + } + } + + fn signed(&mut self, cert: &Cert, by: &Cert) -> bool { + if *self.budget == 0 { + self.ran_out = true; + return false; + } + *self.budget -= 1; + match cert.signed_by(by) { + Ok(()) => true, + Err(Fault::Weak) => { + self.weak = true; + false + } + Err(_) => false, + } + } +} + +/// Whether the path `full` (the leaf first, the anchor last) holds at `now` (RFC 5280 §6.1). +pub(crate) fn judge(full: &[&Cert], now: Timestamp) -> Result<(), Why> { + if full.iter().any(|c| !c.valid_at(now)) { + return Err(Why::Expired); + } + // (The anchor is the host's to vouch for, extensions and all.) + let last = full.len().saturating_sub(1); + if full.iter().take(last).any(|c| c.unknown_critical()) { + return Err(Why::Constrained); + } + for (k, ca) in full.iter().enumerate().skip(1) { + if !ca.may_vouch_for_mail() { + return Err(Why::Constrained); + } + // The certificates below it that count: the leaf, and every authority's not issued by + // itself (§6.1.4 (l), §6.1.3 (b)). + let below: Vec<&Cert> = full.iter().take(k).enumerate().filter(|(j, c)| *j == 0 || !c.self_issued()).map(|(_, c)| *c).collect(); + if let Some(n) = ca.path_len() + && below.len().saturating_sub(1) > usize::from(n) + { + return Err(Why::Constrained); + } + let Ok(constraints) = ca.constraints() else { return Err(Why::Constrained) }; + if let Some(c) = constraints + && !below.iter().all(|cert| within(cert, &c)) + { + return Err(Why::Constrained); + } + } + Ok(()) +} + +/// Whether the names of `cert` are within `c`. +fn within(cert: &Cert, c: &Constraints) -> bool { + let mail = cert.raw_addresses(); + if let Some(permitted) = &c.permitted_mail + && !mail.iter().all(|a| permitted.iter().any(|p| mail_within(a, p))) + { + return false; + } + if mail.iter().any(|a| c.excluded_mail.iter().any(|e| mail_within(a, e))) { + return false; + } + // Unsupported normalization must not make an excluded subtree look different. + if c.permitted_dirs.is_none() && c.excluded_dirs.is_empty() { + return true; + } + let Some(names) = cert.directory_names() else { return false }; + if !names.iter().all(|name| directory_supported(name)) + || !c.excluded_dirs.iter().all(|name| directory_supported(name)) + || c.permitted_dirs.as_ref().is_some_and(|names| !names.iter().all(|name| directory_supported(name))) + { + return false; + } + names.iter().all(|rdns| { + if let Some(permitted) = &c.permitted_dirs + && !permitted.iter().any(|p| dir_within(rdns, p)) + { + return false; + } + !c.excluded_dirs.iter().any(|e| dir_within(rdns, e)) + }) +} diff --git a/crates/smime/src/digital_signature.rs b/crates/smime/src/digital_signature.rs new file mode 100644 index 000000000..19bb572f7 --- /dev/null +++ b/crates/smime/src/digital_signature.rs @@ -0,0 +1,277 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! What checking a message's Digital signature found (#30), whichever format it is in: S/MIME +//! (`craft-smime`) or OpenPGP. One of four results ([`Verdict`]), why when it isn't the +//! first ([`Why`]), and what is known of who signed it ([`Signer`]). Worked out from the bytes the +//! message came as, in memory, and never written to the mailbox file: it is checked again when +//! the message is next looked at, against the trust and the clock of that moment. + +use serde::{Deserialize, Serialize}; + +use crate::Timestamp; + +/// The format of a Digital signature. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SignatureFormat { + /// S/MIME (RFC 8551): CMS signed data and an X.509 certificate. + Smime, + /// OpenPGP (RFC 9580), as PGP/MIME (RFC 3156) or inline. + OpenPgp, +} + +impl SignatureFormat { + pub fn as_str(self) -> &'static str { + match self { + SignatureFormat::Smime => "smime", + SignatureFormat::OpenPgp => "openpgp", + } + } +} + +/// The four results a check has, best first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Verdict { + /// The Digital signature is valid, its signer is trusted, the signer's address is the + /// message's one From address (verified is for that signer and that address together, never + /// for a key alone), and what was signed is the whole message ([`Coverage::Whole`]). + Verified, + /// The Digital signature is valid, but its signer isn't verified ([`Why`] says how): an + /// unknown issuer, a certificate out of date or not for mail, an address that isn't the From + /// address, an OpenPGP key nobody marked verified. + NotVerified, + /// The message was changed after it was signed: what is shown isn't what was signed. + Changed, + /// The Digital signature can't be checked ([`Why`] says why): an algorithm that's no longer + /// safe or isn't known, no Public key, or a signature that can't be read. + Unchecked, +} + +impl Verdict { + /// Its name for an agent and a script: `verified`, `notVerified`, `changed`, `unchecked`. + pub fn as_str(self) -> &'static str { + match self { + Verdict::Verified => "verified", + Verdict::NotVerified => "notVerified", + Verdict::Changed => "changed", + Verdict::Unchecked => "unchecked", + } + } + + /// The better of two results ([`Verdict::Verified`] best): of several signers of one + /// message, the best one stands. + pub fn best(self, other: Verdict) -> Verdict { + self.min(other) + } +} + +/// Why a check found less than [`Verdict::Verified`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Why { + // Not verified. + /// The certificate wasn't issued by a certification authority this computer trusts. + UnknownIssuer, + /// The certificate signed itself, and isn't one this computer trusts. + SelfSigned, + /// The certificate, or one of those it rests on, is out of date (or not valid yet). + Expired, + /// The certificate isn't for signing mail (its key usage or extended key usage say so). + NotForEmail, + /// The certificate is for another address than the message's From address. + AddressMismatch, + /// An authority on the way to a trusted one doesn't allow the certificate to be used this + /// way: a name outside what it may vouch for, a path too long, a use it doesn't allow, or a + /// critical extension not known here (RFC 5280 §4.2, §6.1). + Constrained, + /// No certification authorities for mail could be read on this computer, so no signer can be + /// verified here. + NoAuthorities, + /// This computer's certification authorities haven't been read yet (they are read at start): + /// the check is made again when they are. + AuthoritiesNotRead, + /// An OpenPGP key that the owner hasn't marked Verified. + KeyNotVerified, + /// Only part of the message was signed (a wrapper such as a list's footer holds it), so + /// what is outside that part could say anything. + PartlySigned, + // Changed. + /// What was signed isn't what arrived. + Altered, + // Can't be checked. + /// It uses an algorithm that's no longer safe (MD5, SHA-1, a short RSA key). + WeakAlgorithm, + /// It uses an algorithm MailCraft doesn't know. + UnknownAlgorithm, + /// The signer's Public key (certificate) isn't in the message or kept here. + NoPublicKey, + /// The signer's OpenPGP key was revoked by its owner, for when the message was signed. + KeyRevoked, + /// The signer's OpenPGP key had expired when the message was signed. + KeyExpired, + /// The OpenPGP key that made it isn't one that may sign. + NotASigningKey, + /// The Digital signature itself has expired (it said until when it holds). + SignatureExpired, + /// The Digital signature can't be read. + Unreadable, + /// The bytes the message came as aren't here (it was read before they were kept): Check + /// again downloads them. + NoOriginal, + /// There is more to check than a message is allowed (many certificates, or many ways to a + /// trusted authority): it was stopped before an answer. + TooMuch, +} + +impl Why { + /// Its name for an agent and a script. + pub fn as_str(self) -> &'static str { + match self { + Why::UnknownIssuer => "unknownIssuer", + Why::SelfSigned => "selfSigned", + Why::Expired => "expired", + Why::NotForEmail => "notForEmail", + Why::AddressMismatch => "addressMismatch", + Why::Constrained => "constrained", + Why::NoAuthorities => "noAuthorities", + Why::AuthoritiesNotRead => "authoritiesNotRead", + Why::KeyNotVerified => "keyNotVerified", + Why::PartlySigned => "partlySigned", + Why::Altered => "altered", + Why::WeakAlgorithm => "weakAlgorithm", + Why::UnknownAlgorithm => "unknownAlgorithm", + Why::NoPublicKey => "noPublicKey", + Why::KeyRevoked => "keyRevoked", + Why::KeyExpired => "keyExpired", + Why::NotASigningKey => "notASigningKey", + Why::SignatureExpired => "signatureExpired", + Why::Unreadable => "unreadable", + Why::NoOriginal => "noOriginal", + Why::TooMuch => "tooMuch", + } + } + + /// The plain English of it, for an agent, a script and the log; the window says it in its + /// own language. + pub fn english(self) -> &'static str { + match self { + Why::UnknownIssuer => "the certificate wasn't issued by a certification authority this computer trusts", + Why::SelfSigned => "the certificate signed itself and isn't one this computer trusts", + Why::Expired => "the certificate is out of date", + Why::NotForEmail => "the certificate isn't for signing mail", + Why::AddressMismatch => "the certificate is for another address than the sender's", + Why::Constrained => "an authority on the way to a trusted one doesn't allow the certificate to be used this way", + Why::NoAuthorities => "no certification authorities for mail could be read on this computer, so no signer can be verified here", + Why::AuthoritiesNotRead => "this computer's certification authorities haven't been read yet", + Why::KeyNotVerified => "the signer's key hasn't been marked verified", + Why::PartlySigned => "only part of the message was signed; the rest could say anything", + Why::Altered => "the message was changed after it was signed", + Why::WeakAlgorithm => "it uses an algorithm that's no longer safe", + Why::UnknownAlgorithm => "it uses an algorithm MailCraft doesn't know", + Why::NoPublicKey => "the signer's Public key (certificate) isn't in the message or kept on this computer", + Why::KeyRevoked => "the signer's key was revoked by its owner", + Why::KeyExpired => "the signer's key had expired when the message was signed", + Why::NotASigningKey => "the key that made it isn't one that may sign", + Why::SignatureExpired => "the Digital signature has expired", + Why::Unreadable => "the Digital signature can't be read", + Why::NoOriginal => "the bytes the message came as aren't on this computer; Check again downloads them", + Why::TooMuch => "there is too much to check in this Digital signature", + } + } +} + +/// Who signed, as the certificate or key says: the signer's own words, data and never +/// instructions. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Signer { + /// The name in the certificate (its common name) or key, if any. + pub name: String, + /// The addresses in the certificate or key, as they are written there, at most + /// [`MAX_SIGNER_ADDRESSES`]. + pub addresses: Vec<String>, + /// The SHA-256 fingerprint of the certificate (or the fingerprint of the OpenPGP key), in + /// upper-case hexadecimal pairs with colons between. + pub fingerprint: String, + /// Who issued the certificate (its common name, else its whole name). Empty for OpenPGP. + pub issuer: String, + /// From and until when the certificate is valid; 0 when it doesn't say. + pub not_before: Timestamp, + pub not_after: Timestamp, +} + +/// How much of the message the Digital signature covers. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Coverage { + /// The whole message body: the signed part is the message's top level (S/MIME's + /// `multipart/signed` or signed data, PGP/MIME's `multipart/signed`). + Whole, + /// Only a part of it: the signed part sits inside a wrapper whose other parts nobody signed + /// (or a format that can't tell). The safe default. + #[default] + Part, +} + +impl Coverage { + pub fn as_str(self) -> &'static str { + match self { + Coverage::Whole => "whole", + Coverage::Part => "part", + } + } +} + +/// The most addresses of a signer that are kept. +pub const MAX_SIGNER_ADDRESSES: usize = 16; +/// The most characters of a name, an issuer or an address that are kept. +pub const MAX_SIGNER_TEXT: usize = 256; + +/// What checking a message's Digital signature found. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DigitalSignature { + pub format: SignatureFormat, + pub verdict: Verdict, + /// Why it is less than verified; `None` when it is verified. + pub why: Option<Why>, + /// Who signed, when the signer's certificate or key was found. + pub signer: Option<Signer>, + /// When the signer says they signed it (S/MIME's signing time): the signer's word, not + /// checked by anybody. + pub signed_at: Option<Timestamp>, + /// Whether the certificate was checked against its issuer's list of revoked certificates. + /// Never yet (#30 R7): the details say "Revocation not checked". + pub revocation_checked: bool, + /// How much of the message was signed; set with [`DigitalSignature::covering`]. + #[serde(default)] + pub coverage: Coverage, +} + +impl DigitalSignature { + /// A result of `verdict` for `why`, with nothing known of the signer. + pub fn bare(format: SignatureFormat, verdict: Verdict, why: Why) -> DigitalSignature { + DigitalSignature { format, verdict, why: Some(why), signer: None, signed_at: None, revocation_checked: false, coverage: Coverage::Part } + } + + /// This result for a signature that covers `coverage` of the message: a valid signature by a + /// trusted signer over only part of it is [`Verdict::NotVerified`] ([`Why::PartlySigned`]), + /// never verified for the message. Either format's checker ends with it. + pub fn covering(mut self, coverage: Coverage) -> DigitalSignature { + self.coverage = coverage; + if coverage == Coverage::Part && self.verdict == Verdict::Verified { + self.verdict = Verdict::NotVerified; + self.why = Some(Why::PartlySigned); + } + self + } +} + +/// `text` (a name or address from a certificate) as a name coming in is kept +/// ([`crate::names::incoming`]): one line, without control or format characters (no +/// reordering by a bidirectional override, nothing hidden by a zero-width one), at most +/// [`MAX_SIGNER_TEXT`] characters. +pub fn signer_text(text: &str) -> String { + crate::names::incoming(text, MAX_SIGNER_TEXT).unwrap_or_default() +} diff --git a/crates/smime/src/import.rs b/crates/smime/src/import.rs new file mode 100644 index 000000000..216cfaa92 --- /dev/null +++ b/crates/smime/src/import.rs @@ -0,0 +1,171 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Certificates read from a file the owner imports as Public keys (#30): DER or PEM, what each +//! one is for, and whether the file holds a private key instead (which is never a Public key +//! to import, and goes through File › Options › Security in the window). No I/O; the file is +//! hostile: sizes and counts are capped, and nothing here panics on any bytes. + +use crate::Timestamp; +use base64::Engine as _; +use craft_ber as ber; + +use crate::cert::{Cert, MAX_CERT_BYTES, printable}; + +/// The most certificates read from one file. +pub const MAX_IMPORT_CERTIFICATES: usize = 16; +/// The most addresses a certificate is kept for. +const MAX_ADDRESSES: usize = 16; + +/// What a certificate to import says of itself. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CertificateInfo { + /// The certificate, in DER. + pub der: Vec<u8>, + /// Its SHA-256 fingerprint, as a Digital signature's details have it. + pub fingerprint: String, + /// The mail addresses it is for (subject alternative names, and an `emailAddress` in its + /// subject), in lower case: plain ASCII only, as a signer's address is compared. + pub addresses: Vec<String>, + /// Until when it is valid. + pub not_after: Timestamp, + /// Whether it is for mail ([`Cert::for_mail`]). + pub for_mail: bool, + /// Whether it is a certification authority's. + pub authority: bool, + /// Who it is for (its subject's common name, else its whole subject), cleaned. + pub name: String, + /// Who issued it (the issuer's common name, else its whole name), cleaned. + pub issuer: String, +} + +/// What the certificate `der` says of itself; `None` when it isn't one. +pub fn certificate_info(der: &[u8]) -> Option<CertificateInfo> { + let cert = Cert::from_der(der)?; + let mut addresses: Vec<String> = Vec::new(); + for a in cert.raw_addresses() { + let a = a.to_ascii_lowercase(); + if printable(&a) && a.contains('@') && !addresses.contains(&a) && addresses.len() < MAX_ADDRESSES { + addresses.push(a); + } + } + Some(CertificateInfo { + der: cert.der().to_vec(), + fingerprint: cert.fingerprint(), + addresses, + not_after: cert.validity().1, + for_mail: cert.for_mail(), + authority: cert.is_authority(), + name: cert.name(), + issuer: cert.issuer_name(), + }) +} + +/// The certificates in `bytes`: PEM `CERTIFICATE` blocks (as many as there are, at most +/// [`MAX_IMPORT_CERTIFICATES`]), else one certificate in DER (or BER). Empty when there is none. +pub fn certificates_in(bytes: &[u8]) -> Vec<Vec<u8>> { + let blocks = pem_blocks(bytes, "CERTIFICATE"); + if !blocks.is_empty() { + return blocks.into_iter().filter(|b| Cert::from_der(b).is_some()).take(MAX_IMPORT_CERTIFICATES).collect(); + } + if bytes.len() > MAX_CERT_BYTES { + return Vec::new(); + } + match ber::to_der(bytes) { + Some(der) if Cert::from_der(&der).is_some() => vec![der], + _ => Vec::new(), + } +} + +/// The decoded bodies of the PEM blocks labelled `label` in `bytes` (RFC 7468), each at most a +/// certificate's size, at most [`MAX_IMPORT_CERTIFICATES`]. +fn pem_blocks(bytes: &[u8], label: &str) -> Vec<Vec<u8>> { + let text = String::from_utf8_lossy(bytes); + let begin = format!("-----BEGIN {label}-----"); + let end = format!("-----END {label}-----"); + let mut out = Vec::new(); + let mut body: Option<String> = None; + for line in text.lines() { + let line = line.trim(); + match body.as_mut() { + None if line == begin => body = Some(String::new()), + None => {} + Some(b) if line == end => { + if let Ok(der) = base64::engine::general_purpose::STANDARD.decode(b.as_bytes()) + && der.len() <= MAX_CERT_BYTES + { + out.push(der); + } + body = None; + if out.len() >= MAX_IMPORT_CERTIFICATES { + break; + } + } + Some(b) => { + // (A header line of RFC 1421's kind is no base64: such a block won't decode.) + if !append_pem_line(b, line) { + body = None; + } + } + } + } + out +} + +/// Whether `bytes` hold a private key in a form S/MIME's tools write: a PEM block of any kind of +/// `PRIVATE KEY` (PKCS #8, encrypted or not, PKCS #1, SEC 1, OpenSSH, OpenPGP's armour too), a +/// PKCS #12 file, or a PKCS #8, PKCS #1 or SEC 1 key in DER. +pub fn holds_private_key(bytes: &[u8]) -> bool { + let text = String::from_utf8_lossy(bytes.get(..bytes.len().min(crate::pkcs12::MAX_P12_LEN)).unwrap_or_default()); + if text.lines().any(|l| { + let l = l.trim(); + l.starts_with("-----BEGIN ") && l.contains("PRIVATE KEY") + }) { + return true; + } + if crate::pkcs12::looks_like(bytes) { + return true; + } + let Some(der) = ber::to_der(bytes.get(..bytes.len().min(crate::pkcs12::MAX_P12_LEN)).unwrap_or_default()) else { return false }; + let Some((outer, _)) = ber::read(&der) else { return false }; + if outer.tag != 0x30 { + return false; + } + let Some(fields) = ber::children(outer.value) else { return false }; + let tags: Vec<u8> = fields.iter().map(|f| f.tag).collect(); + let first_int = |v: &[u8]| fields.first().is_some_and(|f| f.tag == 0x02 && f.value == v); + // PKCS #8 PrivateKeyInfo / OneAsymmetricKey: version, algorithm, the key in an OCTET STRING. + let pkcs8 = matches!(tags.as_slice(), [0x02, 0x30, 0x04, ..]) && (first_int(&[0]) || first_int(&[1])); + // EncryptedPrivateKeyInfo: algorithm, the encrypted key. + let encrypted = matches!(tags.as_slice(), [0x30, 0x04]); + // PKCS #1 RSAPrivateKey: version 0 and eight INTEGERs. + let rsa = tags.len() >= 9 && tags.iter().take(9).all(|t| *t == 0x02) && first_int(&[0]); + // SEC 1 ECPrivateKey: version 1, the key in an OCTET STRING. + let ec = matches!(tags.as_slice(), [0x02, 0x04, ..]) && first_int(&[1]); + pkcs8 || encrypted || rsa || ec +} + +// Check the prospective length before allocation, including a single oversized line. +fn append_pem_line(body: &mut String, line: &str) -> bool { + if body.len().checked_add(line.len()).is_none_or(|len| len > MAX_CERT_BYTES.saturating_mul(2)) { + return false; + } + body.push_str(line); + true +} + +#[cfg(test)] +mod bounded_pem_tests { + use super::*; + + #[test] + fn oversized_pem_lines_are_refused_before_accumulation() { + let cap = MAX_CERT_BYTES * 2; + let mut body = String::new(); + assert!(!append_pem_line(&mut body, &"A".repeat(cap + 1))); + assert!(body.is_empty()); + assert!(append_pem_line(&mut body, &"A".repeat(cap - 1))); + assert!(append_pem_line(&mut body, "A")); + assert!(!append_pem_line(&mut body, "A")); + assert_eq!(body.len(), cap); + } +} diff --git a/crates/smime/src/import_tests.rs b/crates/smime/src/import_tests.rs new file mode 100644 index 000000000..2865dcbf3 --- /dev/null +++ b/crates/smime/src/import_tests.rs @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Certificates read for import, and private keys told apart (#30). The certificates are those +//! of `pkcs12_tests` (synthetic `example.org` people under a test authority), and one made for a +//! web server with Bob's key. + +use base64::Engine as _; +use proptest::prelude::*; + +use crate::import::{certificate_info, certificates_in, holds_private_key}; +use crate::pkcs12_tests::{ALICE_PEM, CA_PEM, MODERN}; + +/// Bob's key, certified for `www.example.org` and for serving the web only. +pub(crate) const SERVER_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIICeTCCAWGgAwIBAgITBZjuab1kWRuw6iskHm6GfE5XsDANBgkqhkiG9w0BAQsF\nADAsMRgwFgYDVQQDDA9FeGFtcGxlIFRlc3QgQ0ExEDAOBgNVBAoMB0V4YW1wbGUw\nIBcNMjYxMTEwMjM1NzM0WhgPMjEyNjEwMTcyMzU3MzRaMBYxFDASBgNVBAMMC0Jv\nYiBFeGFtcGxlMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEVMGX6KffvBxXYqhk\nGl7wd0hrcjrtj18zbj1rN23ToDZ6d+Iy3rQQZvU5gCfqoP/scGZ9K377DvfqOzR8\n8VGPoKNzMHEwGgYDVR0RBBMwEYIPd3d3LmV4YW1wbGUub3JnMBMGA1UdJQQMMAoG\nCCsGAQUFBwMBMB0GA1UdDgQWBBQNf+WUyk2rA7Ol2+DplbqCmjDuOTAfBgNVHSME\nGDAWgBQDV2BK6ZYA5LKhPQiiQ98tSGv7JjANBgkqhkiG9w0BAQsFAAOCAQEAUlZu\nif7xv5ZXlsWt0KX458+G2vekBcqdE3UD21hTvJ9tbCrnfIuXa9pigZsYUzqV5Xwt\npaXU+7JedPYNZs0qqk2nPw+VULsxBNhaKre5V+v4tdHxq16MTsAalT6GfeOtX8+G\nZ5CwUqqe5SW9kkUi0QnaR/BDZuTKIOKKBCJ4AEOmi9cbDWUQiKkQRR4mEQH7wAJM\nfBXlNb7YHRikSE/ZHAjsLKNwSEpOsKnKav8KxPy/moR+emB9AFIHAsGjmPTMNhdG\nQ5DrRP3eAtKBGCrFGOj+JSxXW4O2eqKGuMHy7fLrCD2st7qBv4Lm7lEw1SDsXAQ/\nx1BBQKVBaJYfE2pKOA==\n-----END CERTIFICATE-----\n"; + +#[test] +fn certificates_are_read_from_pem_and_der() { + let both = format!("{ALICE_PEM}{CA_PEM}"); + let read = certificates_in(both.as_bytes()); + assert_eq!(read.len(), 2); + assert_eq!(certificates_in(&read[0]), vec![read[0].clone()], "DER"); + assert!(certificates_in(b"no certificate").is_empty()); + assert!(certificates_in(b"").is_empty()); +} + +#[test] +fn what_a_certificate_is_for_is_told() { + let alice = certificate_info(&certificates_in(ALICE_PEM.as_bytes())[0]).unwrap(); + assert_eq!(alice.addresses, vec!["alice@example.org".to_string()], "its alternative name and its subject's address, once"); + assert!(alice.for_mail); + assert!(!alice.authority); + assert_eq!(alice.fingerprint, "10:33:B4:36:A1:40:16:60:4A:21:D5:BC:F3:B1:69:38:60:22:DF:01:85:71:8D:BC:F5:BB:63:4B:09:CB:AA:FC"); + assert!(alice.not_after > 4_000_000_000); + let server = certificate_info(&certificates_in(SERVER_PEM.as_bytes())[0]).unwrap(); + assert!(!server.for_mail, "for the web only"); + assert!(server.addresses.is_empty()); + let ca = certificate_info(&certificates_in(CA_PEM.as_bytes())[0]).unwrap(); + assert!(ca.authority); + assert!(certificate_info(b"junk").is_none()); +} + +#[test] +fn a_private_key_in_any_form_is_told() { + for label in ["PRIVATE KEY", "ENCRYPTED PRIVATE KEY", "RSA PRIVATE KEY", "EC PRIVATE KEY", "OPENSSH PRIVATE KEY", "PGP PRIVATE KEY BLOCK"] { + let pem = format!("-----BEGIN {label}-----\nAAAA\n-----END {label}-----\n"); + assert!(holds_private_key(pem.as_bytes()), "{label}"); + } + assert!(holds_private_key(&base64::engine::general_purpose::STANDARD.decode(MODERN).unwrap()), "a PKCS #12 file"); + // PKCS #8: version 0, an algorithm, the key in an OCTET STRING. + let pkcs8 = [0x30, 0x0b, 0x02, 0x01, 0x00, 0x30, 0x03, 0x06, 0x01, 0x2a, 0x04, 0x01, 0x00]; + assert!(holds_private_key(&pkcs8)); + // EncryptedPrivateKeyInfo. + assert!(holds_private_key(&[0x30, 0x08, 0x30, 0x03, 0x06, 0x01, 0x2a, 0x04, 0x01, 0x00])); + // SEC 1: version 1, the key. + assert!(holds_private_key(&[0x30, 0x06, 0x02, 0x01, 0x01, 0x04, 0x01, 0x07])); + // PKCS #1: nine INTEGERs, the first 0. + let mut rsa = vec![0x30, 27]; + for _ in 0..9 { + rsa.extend_from_slice(&[0x02, 0x01, 0x00]); + } + assert!(holds_private_key(&rsa)); + for public in [ALICE_PEM.as_bytes(), &certificates_in(ALICE_PEM.as_bytes())[0], b"-----BEGIN PGP PUBLIC KEY BLOCK-----", b""] { + assert!(!holds_private_key(public)); + } +} + +proptest! { + #[test] + fn any_bytes_are_read_without_a_panic(bytes in proptest::collection::vec(any::<u8>(), 0..2048)) { + let _ = certificates_in(&bytes); + let _ = certificate_info(&bytes); + let _ = holds_private_key(&bytes); + } +} diff --git a/crates/smime/src/lib.rs b/crates/smime/src/lib.rs new file mode 100644 index 000000000..d9b534389 --- /dev/null +++ b/crates/smime/src/lib.rs @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! MailCraft's S/MIME (RFC 8551): Digital signatures checked (#30), written from the public +//! specifications (RFC 5652 for CMS, RFC 5280 for X.509, RFC 5754, RFC 4055 and RFC 5480 for +//! the algorithms). No I/O: the host hands in the certificates it trusts ([`Anchors`]), the +//! message's halves come from `mailcraft-mime`, and the result is +//! [`crate::digital_signature::DigitalSignature`], which OpenPGP shares. +//! +//! [`check`] reads the CMS SignedData of a detached or an opaque Digital signature, finds the +//! signer's certificate, compares the signer's digest with the message's, checks the signature +//! (RSA PKCS #1 v1.5 or PSS of 2048 bits or more, ECDSA on P-256 or P-384, over SHA-2), and then +//! whether the certificate rests on a trust anchor, is for signing mail and is for the From +//! address. MD5 and SHA-1 are no longer safe and are said to be. Revocation isn't checked. +//! +//! Directory-name constraints currently support ASCII PrintableString/UTF8String names. +//! Constrained chains requiring other string profiles are refused, not approximately matched. +//! Opaque CMS content is verified as exact octets; only detached transport text permits LF repair. +//! +//! Input is hostile: BER is turned into DER with nesting bounded, every length is checked +//! against what is there, the certificates, signers and the path to an anchor are capped, and +//! nothing here panics on any bytes. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![cfg_attr(not(test), deny(clippy::indexing_slicing))] + +/// Seconds since the Unix epoch, UTC. +pub type Timestamp = i64; + +mod algorithms; +mod cert; +mod chain; +pub mod digital_signature; +pub mod import; +mod names; +pub mod pkcs12; +mod verify; + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod import_tests; +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod pkcs12_tests; +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests; + +pub use chain::{Anchors, MAX_ANCHORS}; +pub use verify::{Checked, Context, MAX_CERTS, MAX_SIGNERS, MAX_VERIFICATIONS, Signed, check}; + +/// The fingerprint and addresses of a certificate in DER, as a Digital signature's details show +/// them: `None` when it isn't one. +pub fn certificate_summary(der: &[u8]) -> Option<(String, Vec<String>, crate::Timestamp)> { + let cert = cert::Cert::from_der(der)?; + Some((cert.fingerprint(), cert.addresses(), cert.validity().1)) +} diff --git a/crates/smime/src/names.rs b/crates/smime/src/names.rs new file mode 100644 index 000000000..f0ad2bad5 --- /dev/null +++ b/crates/smime/src/names.rs @@ -0,0 +1,128 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Bounded certificate display-name sanitization extracted from MailCraft. + +/// Whether `c` is one of Unicode's format characters (general category Cf, Unicode 17.0): the +/// soft hyphen, the Arabic number signs and end-of-ayah marks, the Syriac abbreviation mark, the +/// Arabic pound and piastre marks above, the Mongolian vowel separator, zero-width marks and +/// joiners, bidirectional marks, embeddings, overrides and isolates, the word joiner and +/// invisible operators, the deprecated shaping controls, the byte-order mark, interlinear +/// annotations, the Kaithi number signs, the Egyptian hieroglyph, shorthand and musical format +/// controls, and tags. +pub fn is_format(c: char) -> bool { + matches!( + c, + '\u{00ad}' + | '\u{0600}'..='\u{0605}' + | '\u{061c}' + | '\u{06dd}' + | '\u{070f}' + | '\u{0890}'..='\u{0891}' + | '\u{08e2}' + | '\u{180e}' + | '\u{200b}'..='\u{200f}' + | '\u{202a}'..='\u{202e}' + | '\u{2060}'..='\u{2064}' + | '\u{2066}'..='\u{206f}' + | '\u{feff}' + | '\u{fff9}'..='\u{fffb}' + | '\u{110bd}' + | '\u{110cd}' + | '\u{13430}'..='\u{1343f}' + | '\u{1bca0}'..='\u{1bca3}' + | '\u{1d173}'..='\u{1d17a}' + | '\u{e0001}' + | '\u{e0020}'..='\u{e007f}' + ) +} + +/// Whether `c` is the zero-width non-joiner or joiner (U+200C, U+200D): format characters that +/// are part of a word where they stand inside one. +pub fn is_joiner(c: char) -> bool { + matches!(c, '\u{200c}' | '\u{200d}') +} + +/// A name as it is kept: one line (a line break, a tab or any other white space parts words, and +/// words are parted by one space), without control characters or the characters Unicode marks as +/// showing nothing (a joiner inside a word and one variation selector after a character stay), +/// trimmed, at most `max` characters. `None` when nothing is left. +pub fn incoming(text: &str, max: usize) -> Option<String> { + let (name, _) = clean(text, max); + (!name.is_empty()).then_some(name) +} + +/// Whether `c` is one of the rest of Unicode's default-ignorable code points +/// (`Default_Ignorable_Code_Point`, Unicode 17.0, less the format characters and the variation +/// selectors): the combining grapheme joiner, the Hangul fillers, the Khmer inherent vowels, and +/// the code points Unicode keeps for more characters that show nothing. +fn is_ignorable(c: char) -> bool { + matches!( + c, + '\u{034f}' + | '\u{115f}'..='\u{1160}' + | '\u{17b4}'..='\u{17b5}' + | '\u{2065}' + | '\u{3164}' + | '\u{ffa0}' + | '\u{fff0}'..='\u{fff8}' + | '\u{e0000}' + | '\u{e0002}'..='\u{e001f}' + | '\u{e0080}'..='\u{e00ff}' + | '\u{e01f0}'..='\u{e0fff}' + ) +} + +/// Whether `c` is a variation selector (`Variation_Selector`, Unicode 17.0): it picks how the +/// character before it is drawn. +fn is_selector(c: char) -> bool { + matches!(c, '\u{180b}'..='\u{180d}' | '\u{180f}' | '\u{fe00}'..='\u{fe0f}' | '\u{e0100}'..='\u{e01ef}') +} + +/// The braille pattern blank: a symbol to Unicode, and in braille the space between words. +const BRAILLE_BLANK: char = '\u{2800}'; + +/// `text` cleaned and cut to at most `max` characters, and whether something was left out for +/// the length. Nothing past it is read. +fn clean(text: &str, max: usize) -> (String, bool) { + let mut out = String::new(); + let mut count = 0usize; + // A space between words, and a joiner inside one, come only with the character after them. + let mut space = false; + let mut joiner: Option<char> = None; + // Whether the last character written shows, so that a variation selector may follow it. + let mut selectable = false; + for c in text.chars() { + if is_joiner(c) { + if count > 0 && !space { + joiner = Some(c); + } + } else if c.is_whitespace() || c == BRAILLE_BLANK { + space = count > 0; + joiner = None; + } else if is_selector(c) { + if selectable && !space && joiner.is_none() { + if count >= max { + return (out, true); + } + out.push(c); + count = count.saturating_add(1); + selectable = false; + } + } else if !c.is_control() && !is_format(c) && !is_ignorable(c) { + let needed = 1 + usize::from(space) + usize::from(joiner.is_some()); + if count.saturating_add(needed) > max { + return (out, true); + } + if std::mem::take(&mut space) { + out.push(' '); + } + if let Some(j) = joiner.take() { + out.push(j); + } + out.push(c); + count = count.saturating_add(needed); + selectable = true; + } + } + (out, false) +} diff --git a/crates/smime/src/pkcs12.rs b/crates/smime/src/pkcs12.rs new file mode 100644 index 000000000..753a26dfb --- /dev/null +++ b/crates/smime/src/pkcs12.rs @@ -0,0 +1,794 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! A PKCS #12 file (`.p12`, `.pfx`; RFC 7292) opened with its passphrase (#30 R13): the +//! certificate and private key an owner's IT department hands out, for the window to put in the +//! system's credential store. No I/O, and nothing kept: what is opened goes back to the caller, +//! the private key in memory that is wiped when it is let go of. +//! +//! The file is believed only when its MAC checks with the passphrase (RFC 7292 §5.1, the +//! password-integrity mode, HMAC with SHA-1 or SHA-2 keyed by the PKCS #12 key derivation of +//! Appendix B): a file without one, or with a public-key integrity mode, is refused, and a MAC +//! that doesn't check is a wrong passphrase. The bags may be encrypted with PBES2 (RFC 8018: +//! PBKDF2 with HMAC-SHA-1 or SHA-2, and AES-128/192/256-CBC or 3DES-CBC) or with the old +//! pbeWithSHAAnd3-KeyTripleDES-CBC (RFC 7292 Appendix C); RC2, RC4, two-key 3DES, DES and the +//! 40-bit schemes are no longer safe and are refused. +//! +//! The file is hostile: its size, the bags, their nesting and every iteration count (and their +//! sum) are capped, lengths are checked against what is there, and nothing here panics on any +//! bytes. The cryptography is RustCrypto's (`pkcs12`'s key derivation, `pbkdf2`, `hmac`, `sha1`, +//! `sha2`, `aes`, `des`, `cbc`); only the layout is read here. + +use aes::cipher::block_padding::Pkcs7; +use aes::cipher::{BlockModeDecrypt, KeyIvInit}; +use const_oid::ObjectIdentifier; +use craft_ber::{self as ber, Tlv}; +use der::Decode; +use hmac::{KeyInit, Mac}; +use zeroize::Zeroizing; + +/// The largest file opened (the window reads at most as much). +pub const MAX_P12_LEN: usize = 1 << 20; +/// The most bags read, in all. +pub const MAX_BAGS: usize = 64; +/// The most iterations one key derivation may ask for: past it the file is refused as +/// unreasonable rather than spent time on. +pub const MAX_ITERATIONS: u64 = 1_000_000; +/// The most iterations every key derivation of one file may ask for together. +const MAX_TOTAL_ITERATIONS: u64 = 8_000_000; +/// How deep safe-contents bags may nest in each other. +const MAX_NESTING: usize = 4; +/// The most certificates kept from one file. +const MAX_CERTIFICATES: usize = 32; + +const DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1"); +const ENCRYPTED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.6"); +const KEY_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.1"); +const SHROUDED_KEY_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.2"); +const CERT_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.3"); +const SAFE_CONTENTS_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.6"); +const X509_CERTIFICATE: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.22.1"); +const LOCAL_KEY_ID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.21"); + +const SHA1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.14.3.2.26"); +const SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1"); +const SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2"); +const SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.3"); + +const PBES2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.13"); +const PBKDF2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.12"); +const HMAC_SHA1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.7"); +const HMAC_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.9"); +const HMAC_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.10"); +const HMAC_SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.11"); +const AES128_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.2"); +const AES192_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.22"); +const AES256_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.42"); +const DES_EDE3_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.3.7"); +const SHA_3DES: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3"); +/// The PKCS #12 schemes that are no longer safe (RC4, two-key 3DES, RC2), and PKCS #5 v1.5's +/// (DES and RC2 with MD2, MD5 or SHA-1). +const WEAK: [&str; 11] = [ + "1.2.840.113549.1.12.1.1", + "1.2.840.113549.1.12.1.2", + "1.2.840.113549.1.12.1.4", + "1.2.840.113549.1.12.1.5", + "1.2.840.113549.1.12.1.6", + "1.2.840.113549.1.5.1", + "1.2.840.113549.1.5.3", + "1.2.840.113549.1.5.4", + "1.2.840.113549.1.5.6", + "1.2.840.113549.1.5.10", + "1.2.840.113549.1.5.11", +]; + +/// Why a PKCS #12 file couldn't be opened. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// Larger than any such file is. + #[error("the file is larger than a certificate file can be")] + TooLarge, + /// Not a PKCS #12 file, or a damaged one. + #[error("the file isn't a certificate file (.p12 or .pfx) that can be read")] + Unreadable, + /// It has no MAC with a passphrase: nothing vouches that it is as it was made. + #[error("the file isn't protected with a passphrase, so nothing vouches for it")] + NoMac, + /// The MAC doesn't check: the passphrase is wrong (or the file was changed). + #[error("the passphrase is wrong")] + WrongPassphrase, + /// It is encrypted with a scheme that is no longer safe (RC2, RC4, DES, 40-bit keys). + #[error("the file is encrypted in a way that is no longer safe (RC2, RC4, DES or 40-bit keys); export it again with AES")] + WeakEncryption, + /// It uses an algorithm this program doesn't know. + #[error("the file uses an algorithm MailCraft doesn't know")] + UnknownAlgorithm, + /// It asks for more iterations than any file needs, or more bags or nesting than there is room for. + #[error("the file asks for more work than a certificate file needs")] + Unreasonable, + /// It holds no private key, or more than one. + #[error("the file holds no private key, or more than one")] + NoPrivateKey, + /// It holds no certificate for its private key. + #[error("the file holds no certificate for its private key")] + NoCertificate, +} + +/// What a PKCS #12 file holds, opened. +pub struct Opened { + /// The certificate of the private key, in DER: the one whose public key is the key's, else + /// the one with the key's local key id. + pub certificate: Vec<u8>, + /// The other certificates (the authorities on the way to a trusted one), in DER. + pub others: Vec<Vec<u8>>, + /// The private key as PKCS #8 `PrivateKeyInfo` in DER, wiped when let go of. + pub private_key: Zeroizing<Vec<u8>>, + /// What kind of key the private key is, read from its own PKCS #8 algorithm identifier (and + /// curve): whether it may be used here. The certificate is of the same kind. + pub key_kind: KeyKind, + /// Whether the private key was encrypted in the file (a shrouded key bag, or a bag in an + /// encrypted safe), and not merely vouched for by the MAC: a key in a plain key bag of a + /// plain safe is in the file in clear. + pub key_encrypted: bool, +} + +/// What kind of key a certificate holds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeyKind { + /// RSA, with a modulus of so many bits. + Rsa { bits: usize }, + /// ECDSA on NIST P-256. + P256, + /// ECDSA on NIST P-384. + P384, + /// Any other. + Other, +} + +impl std::fmt::Debug for Opened { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Opened") + .field("certificate", &self.certificate.len()) + .field("others", &self.others.len()) + .field("private_key", &"[redacted]") + .field("key_kind", &self.key_kind) + .field("key_encrypted", &self.key_encrypted) + .finish() + } +} + +/// Whether `bytes` look like a PKCS #12 file (a version 3 PFX), without opening it: so that a +/// private key is never taken for a Public key to import. +pub fn looks_like(bytes: &[u8]) -> bool { + let Some(der) = ber::to_der(bytes.get(..bytes.len().min(MAX_P12_LEN)).unwrap_or_default()).map(Zeroizing::new) else { return false }; + let Some((pfx, _)) = ber::read(&der) else { return false }; + let Some(fields) = ber::children(pfx.value) else { return false }; + matches!(fields.as_slice(), [version, info, ..] if version.tag == 0x02 && version.value == [3] && info.tag == 0x30) +} + +/// Open the PKCS #12 file `p12` with `passphrase`. +pub fn open(p12: &[u8], passphrase: &str) -> Result<Opened, Error> { + if p12.len() > MAX_P12_LEN { + return Err(Error::TooLarge); + } + let der = Zeroizing::new(ber::to_der(p12).ok_or(Error::Unreadable)?); + let (pfx, rest) = ber::read(&der).ok_or(Error::Unreadable)?; + if pfx.tag != 0x30 || !rest.is_empty() { + return Err(Error::Unreadable); + } + let fields = ber::children(pfx.value).ok_or(Error::Unreadable)?; + let (version, auth_safe, mac) = match fields.as_slice() { + [v, a, m] => (v, a, Some(m)), + [v, a] => (v, a, None), + _ => return Err(Error::Unreadable), + }; + if version.tag != 0x02 || version.value != [3] { + return Err(Error::Unreadable); + } + let mut work = Work { iterations: 0, bags: 0 }; + // Only the password-integrity mode: the authenticated safe is data, and the MAC is over it. + let (content_type, content) = content_info(auth_safe)?; + if content_type != DATA { + return Err(Error::NoMac); + } + let safe = Zeroizing::new(octets(content)?); + let mac = mac.ok_or(Error::NoMac)?; + let legacy_password = check_mac(mac, &safe, passphrase, &mut work)?; + let safe = Zeroizing::new(ber::to_der(&safe).ok_or(Error::Unreadable)?); + let mut found = Found::default(); + let (list, rest) = ber::read(&safe).ok_or(Error::Unreadable)?; + if list.tag != 0x30 || !rest.is_empty() { + return Err(Error::Unreadable); + } + for info in ber::children(list.value).ok_or(Error::Unreadable)? { + let (kind, content) = content_info(&info)?; + let (contents, encrypted) = if kind == DATA { + (Zeroizing::new(octets(content)?), false) + } else if kind == ENCRYPTED_DATA { + (encrypted_data(content, passphrase, &legacy_password, &mut work)?, true) + } else { + // (Enveloped data, which needs a key of the owner's to open: not a file to import.) + return Err(Error::UnknownAlgorithm); + }; + safe_contents(&contents, Safe { passphrase, legacy_password: &legacy_password, encrypted, depth: 0 }, &mut work, &mut found)?; + } + found.finish() +} + +/// What opening costs so far. +struct Work { + iterations: u64, + bags: usize, +} + +impl Work { + /// Count a key derivation of `iterations`: refused past the caps. + fn derive(&mut self, iterations: u64) -> Result<(), Error> { + if iterations == 0 || iterations > MAX_ITERATIONS { + return Err(Error::Unreasonable); + } + self.iterations = self.iterations.saturating_add(iterations); + if self.iterations > MAX_TOTAL_ITERATIONS { Err(Error::Unreasonable) } else { Ok(()) } + } +} + +/// A private-key bag and whether it was encrypted. +struct KeyBag { + key: Zeroizing<Vec<u8>>, + encrypted: bool, +} + +/// The bags found. +#[derive(Default)] +struct Found { + /// Each private key and whether it was encrypted in the file. + keys: Vec<KeyBag>, + certificates: Vec<(Vec<u8>, Option<Vec<u8>>)>, +} + +impl Found { + /// Pair only by verified public key, never by untrusted bag metadata. + fn finish(mut self) -> Result<Opened, Error> { + let KeyBag { key, encrypted: key_encrypted } = match self.keys.len() { + 1 => self.keys.pop().ok_or(Error::NoPrivateKey)?, + _ => return Err(Error::NoPrivateKey), + }; + let key_kind = private_key_kind(&key); + let kind_of = |c: &[u8]| crate::cert::Cert::from_der(c).map_or(KeyKind::Other, |c| crate::algorithms::key_kind(c.public_key())); + let public = public_of(&key); + let by_key = public.as_ref().and_then(|p| self.certificates.iter().position(|(c, _)| certificate_key(c).as_ref() == Some(p))); + // localKeyId is untrusted metadata, not proof of key ownership. + let at = by_key.ok_or(Error::NoCertificate)?; + let (certificate, _) = self.certificates.remove(at); + if kind_of(&certificate) != key_kind { + return Err(Error::NoCertificate); + } + Ok(Opened { certificate, others: self.certificates.into_iter().map(|(c, _)| c).collect(), private_key: key, key_kind, key_encrypted }) + } +} + +/// What kind of key a PKCS #8 `PrivateKeyInfo` is, by its own algorithm identifier: RSA by its +/// modulus, EC by its named curve (the identifier's parameters, else the `ECPrivateKey`'s own). +fn private_key_kind(pkcs8: &[u8]) -> KeyKind { + let read = || -> Option<KeyKind> { + let (info, _) = ber::read(pkcs8)?; + let fields = ber::children(info.value)?; + let [_, alg, key, ..] = fields.as_slice() else { return None }; + if key.tag != 0x04 { + return None; + } + let (oid, params) = algorithm(alg).ok()?; + let (inner, _) = ber::read(key.value)?; + let parts = ber::children(inner.value)?; + let curve_of = |t: &Tlv<'_>| oid_of(t).ok(); + let curve = params.as_ref().and_then(curve_of).or_else(|| { + // ECPrivateKey (RFC 5915): [0] parameters, a named curve. + let explicit = parts.iter().find(|p| p.tag == 0xa0)?; + let (named, _) = ber::read(explicit.value)?; + curve_of(&named) + }); + // RSAPrivateKey (RFC 8017 A.1.2): version, modulus, … + let modulus = parts.get(1).filter(|n| n.tag == 0x02).map(|n| n.value); + Some(crate::algorithms::private_key_kind(oid, curve, modulus)) + }; + read().unwrap_or(KeyKind::Other) +} + +/// A ContentInfo's type and content (inside its `[0] EXPLICIT`). +fn content_info<'a>(info: &Tlv<'a>) -> Result<(ObjectIdentifier, Tlv<'a>), Error> { + if info.tag != 0x30 { + return Err(Error::Unreadable); + } + let fields = ber::children(info.value).ok_or(Error::Unreadable)?; + let [oid, explicit] = fields.as_slice() else { return Err(Error::Unreadable) }; + if explicit.tag != 0xa0 { + return Err(Error::Unreadable); + } + let (content, rest) = ber::read(explicit.value).ok_or(Error::Unreadable)?; + if !rest.is_empty() { + return Err(Error::Unreadable); + } + Ok((oid_of(oid)?, content)) +} + +fn oid_of(tlv: &Tlv<'_>) -> Result<ObjectIdentifier, Error> { + if tlv.tag != 0x06 { + return Err(Error::Unreadable); + } + ObjectIdentifier::from_der(tlv.whole).map_err(|_| Error::Unreadable) +} + +/// An OCTET STRING's octets: in one piece, or (BER) in pieces under a constructed tag. +fn octets(tlv: Tlv<'_>) -> Result<Vec<u8>, Error> { + match tlv.tag { + 0x04 | 0x80 => Ok(tlv.value.to_vec()), + 0x24 | 0xa0 => { + let mut out = Vec::new(); + for piece in ber::children(tlv.value).ok_or(Error::Unreadable)? { + if piece.tag != 0x04 { + return Err(Error::Unreadable); + } + out.extend_from_slice(piece.value); + } + Ok(out) + } + _ => Err(Error::Unreadable), + } +} + +/// An INTEGER that fits, not negative. +fn uint(tlv: &Tlv<'_>) -> Result<u64, Error> { + if tlv.tag != 0x02 || tlv.value.is_empty() || tlv.value.len() > 9 || tlv.value.first().is_some_and(|b| b & 0x80 != 0) { + return Err(Error::Unreasonable); + } + let digits = tlv.value.strip_prefix(&[0]).unwrap_or(tlv.value); + if digits.len() > 8 { + return Err(Error::Unreasonable); + } + Ok(digits.iter().fold(0u64, |acc, d| (acc << 8) | u64::from(*d))) +} + +/// An AlgorithmIdentifier: its OID and its parameters, if any. +fn algorithm<'a>(tlv: &Tlv<'a>) -> Result<(ObjectIdentifier, Option<Tlv<'a>>), Error> { + if tlv.tag != 0x30 { + return Err(Error::Unreadable); + } + let fields = ber::children(tlv.value).ok_or(Error::Unreadable)?; + match fields.as_slice() { + [oid] => Ok((oid_of(oid)?, None)), + [oid, params] => Ok((oid_of(oid)?, (params.tag != 0x05).then_some(*params))), + _ => Err(Error::Unreadable), + } +} + +/// The hashes a MAC or a key derivation is made with. +#[derive(Clone, Copy)] +enum Hash { + Sha1, + Sha256, + Sha384, + Sha512, +} + +impl Hash { + fn digest(oid: ObjectIdentifier) -> Result<Hash, Error> { + Ok(match oid { + SHA1 => Hash::Sha1, + SHA256 => Hash::Sha256, + SHA384 => Hash::Sha384, + SHA512 => Hash::Sha512, + _ => return Err(Error::UnknownAlgorithm), + }) + } + + fn hmac(oid: ObjectIdentifier) -> Result<Hash, Error> { + Ok(match oid { + HMAC_SHA1 => Hash::Sha1, + HMAC_SHA256 => Hash::Sha256, + HMAC_SHA384 => Hash::Sha384, + HMAC_SHA512 => Hash::Sha512, + _ => return Err(Error::UnknownAlgorithm), + }) + } + + fn len(self) -> usize { + match self { + Hash::Sha1 => 20, + Hash::Sha256 => 32, + Hash::Sha384 => 48, + Hash::Sha512 => 64, + } + } + + /// The PKCS #12 key derivation (RFC 7292 Appendix B.2) of `len` bytes for `purpose`. + fn pkcs12_kdf(self, password: &[u8], salt: &[u8], purpose: Purpose, iterations: u64, len: usize) -> Result<Zeroizing<Vec<u8>>, Error> { + use pkcs12::kdf::{Pkcs12KeyType, derive_key}; + let id = match purpose { + Purpose::Key => Pkcs12KeyType::EncryptionKey, + Purpose::Iv => Pkcs12KeyType::Iv, + Purpose::Mac => Pkcs12KeyType::Mac, + }; + let rounds = i32::try_from(iterations).map_err(|_| Error::Unreasonable)?; + let out = match self { + Hash::Sha1 => derive_key::<sha1::Sha1>(password, salt, id, rounds, len), + Hash::Sha256 => derive_key::<sha2::Sha256>(password, salt, id, rounds, len), + Hash::Sha384 => derive_key::<sha2::Sha384>(password, salt, id, rounds, len), + Hash::Sha512 => derive_key::<sha2::Sha512>(password, salt, id, rounds, len), + }; + out.map(Zeroizing::new).map_err(|_| Error::Unreadable) + } + + /// Whether the HMAC of `data` under `key` is `tag`, in constant time. + fn hmac_checks(self, key: &[u8], data: &[u8], tag: &[u8]) -> bool { + fn check<M: Mac + KeyInit>(key: &[u8], data: &[u8], tag: &[u8]) -> bool { + match <M as KeyInit>::new_from_slice(key) { + Ok(mut mac) => { + mac.update(data); + mac.verify_slice(tag).is_ok() + } + Err(_) => false, + } + } + match self { + Hash::Sha1 => check::<hmac::Hmac<sha1::Sha1>>(key, data, tag), + Hash::Sha256 => check::<hmac::Hmac<sha2::Sha256>>(key, data, tag), + Hash::Sha384 => check::<hmac::Hmac<sha2::Sha384>>(key, data, tag), + Hash::Sha512 => check::<hmac::Hmac<sha2::Sha512>>(key, data, tag), + } + } + + fn pbkdf2(self, password: &[u8], salt: &[u8], iterations: u32, out: &mut [u8]) { + match self { + Hash::Sha1 => pbkdf2::pbkdf2_hmac::<sha1::Sha1>(password, salt, iterations, out), + Hash::Sha256 => pbkdf2::pbkdf2_hmac::<sha2::Sha256>(password, salt, iterations, out), + Hash::Sha384 => pbkdf2::pbkdf2_hmac::<sha2::Sha384>(password, salt, iterations, out), + Hash::Sha512 => pbkdf2::pbkdf2_hmac::<sha2::Sha512>(password, salt, iterations, out), + } + } +} + +#[derive(Clone, Copy)] +enum Purpose { + Key, + Iv, + Mac, +} + +/// The passphrase as the PKCS #12 key derivation takes it (RFC 7292 Appendix B.1): a BMPString, +/// two bytes to a character, ended by two zero bytes. `None` for a character outside the BMP. +fn bmp(passphrase: &str) -> Option<Zeroizing<Vec<u8>>> { + let mut out = Zeroizing::new(Vec::with_capacity(passphrase.len().saturating_mul(2).saturating_add(2))); + for c in passphrase.chars() { + let unit = u16::try_from(u32::from(c)).ok()?; + out.extend_from_slice(&unit.to_be_bytes()); + } + out.extend_from_slice(&[0, 0]); + Some(out) +} + +/// The forms of the passphrase a file may have been made with: the BMPString, and for an empty +/// one also nothing at all (which some writers use). +fn passwords(passphrase: &str) -> Vec<Zeroizing<Vec<u8>>> { + let mut out: Vec<Zeroizing<Vec<u8>>> = bmp(passphrase).into_iter().collect(); + if passphrase.is_empty() { + out.push(Zeroizing::new(Vec::new())); + } + out +} + +/// Check the file's MAC (RFC 7292 §5.1, Appendix B.4) over `safe`. +fn check_mac(mac: &Tlv<'_>, safe: &[u8], passphrase: &str, work: &mut Work) -> Result<Zeroizing<Vec<u8>>, Error> { + if mac.tag != 0x30 { + return Err(Error::Unreadable); + } + let fields = ber::children(mac.value).ok_or(Error::Unreadable)?; + let (digest_info, salt, iterations) = match fields.as_slice() { + [d, s] => (d, s, 1), + [d, s, i] => (d, s, uint(i)?), + _ => return Err(Error::Unreadable), + }; + if digest_info.tag != 0x30 || salt.tag != 0x04 { + return Err(Error::Unreadable); + } + let parts = ber::children(digest_info.value).ok_or(Error::Unreadable)?; + let [alg, digest] = parts.as_slice() else { return Err(Error::Unreadable) }; + if digest.tag != 0x04 { + return Err(Error::Unreadable); + } + let (oid, _) = algorithm(alg)?; + let hash = Hash::digest(oid)?; + if digest.value.len() != hash.len() { + return Err(Error::Unreadable); + } + for password in passwords(passphrase) { + work.derive(iterations)?; + let key = hash.pkcs12_kdf(&password, salt.value, Purpose::Mac, iterations, hash.len())?; + if hash.hmac_checks(&key, safe, digest.value) { + return Ok(password); + } + } + Err(Error::WrongPassphrase) +} + +/// The contents of an EncryptedData (RFC 5652 §8), decrypted. +fn encrypted_data(content: Tlv<'_>, passphrase: &str, legacy_password: &[u8], work: &mut Work) -> Result<Zeroizing<Vec<u8>>, Error> { + if content.tag != 0x30 { + return Err(Error::Unreadable); + } + let fields = ber::children(content.value).ok_or(Error::Unreadable)?; + let info = fields.get(1).ok_or(Error::Unreadable)?; + if info.tag != 0x30 { + return Err(Error::Unreadable); + } + let parts = ber::children(info.value).ok_or(Error::Unreadable)?; + let [kind, alg, encrypted] = parts.as_slice() else { return Err(Error::Unreadable) }; + if oid_of(kind)? != DATA { + return Err(Error::Unreadable); + } + let ciphertext = octets(*encrypted)?; + decrypt(alg, &ciphertext, passphrase, legacy_password, work) +} + +/// `ciphertext` decrypted with the passphrase as the algorithm identifier `alg` says. +fn decrypt(alg: &Tlv<'_>, ciphertext: &[u8], passphrase: &str, legacy_password: &[u8], work: &mut Work) -> Result<Zeroizing<Vec<u8>>, Error> { + let (oid, params) = algorithm(alg)?; + if WEAK.iter().any(|w| oid.to_string() == *w) { + return Err(Error::WeakEncryption); + } + let params = params.ok_or(Error::Unreadable)?; + if oid == SHA_3DES { + // RFC 7292 Appendix C: pkcs-12PbeParams, the key and IV from the PKCS #12 derivation. + let fields = ber::children(params.value).ok_or(Error::Unreadable)?; + let [salt, iterations] = fields.as_slice() else { return Err(Error::Unreadable) }; + if salt.tag != 0x04 { + return Err(Error::Unreadable); + } + let iterations = uint(iterations)?; + // Reuse the exact representation authenticated by the MAC, including empty bytes. + let password = legacy_password; + work.derive(iterations)?; + let key = Hash::Sha1.pkcs12_kdf(password, salt.value, Purpose::Key, iterations, 24)?; + work.derive(iterations)?; + let iv = Hash::Sha1.pkcs12_kdf(password, salt.value, Purpose::Iv, iterations, 8)?; + return cbc_decrypt::<des::TdesEde3>(&key, &iv, ciphertext); + } + if oid != PBES2 { + return Err(Error::UnknownAlgorithm); + } + let fields = ber::children(params.value).ok_or(Error::Unreadable)?; + let [kdf, scheme] = fields.as_slice() else { return Err(Error::Unreadable) }; + let (kdf_oid, kdf_params) = algorithm(kdf)?; + if kdf_oid != PBKDF2 { + return Err(Error::UnknownAlgorithm); + } + let kdf_fields = ber::children(kdf_params.ok_or(Error::Unreadable)?.value).ok_or(Error::Unreadable)?; + let mut kdf_fields = kdf_fields.iter(); + let salt = kdf_fields.next().filter(|s| s.tag == 0x04).ok_or(Error::UnknownAlgorithm)?; + let iterations = uint(kdf_fields.next().ok_or(Error::Unreadable)?)?; + let mut prf = Hash::Sha1; + let mut key_length: Option<u64> = None; + for field in kdf_fields { + match field.tag { + 0x02 if key_length.is_none() => key_length = Some(uint(field)?), + 0x30 => prf = Hash::hmac(algorithm(field)?.0)?, + _ => return Err(Error::Unreadable), + } + } + let (cipher, iv) = algorithm(scheme)?; + let iv = iv.filter(|v| v.tag == 0x04).ok_or(Error::Unreadable)?; + let size = match cipher { + AES128_CBC => 16, + AES192_CBC => 24, + AES256_CBC => 32, + DES_EDE3_CBC => 24, + _ => return Err(Error::UnknownAlgorithm), + }; + if key_length.is_some_and(|l| l != size as u64) { + return Err(Error::Unreadable); + } + work.derive(iterations)?; + let rounds = u32::try_from(iterations).map_err(|_| Error::Unreasonable)?; + let mut key = Zeroizing::new(vec![0u8; size]); + // (RFC 8018 takes the passphrase as octets: its UTF-8, as the writers do.) + prf.pbkdf2(passphrase.as_bytes(), salt.value, rounds, &mut key); + match cipher { + AES128_CBC => cbc_decrypt::<aes::Aes128>(&key, iv.value, ciphertext), + AES192_CBC => cbc_decrypt::<aes::Aes192>(&key, iv.value, ciphertext), + AES256_CBC => cbc_decrypt::<aes::Aes256>(&key, iv.value, ciphertext), + _ => cbc_decrypt::<des::TdesEde3>(&key, iv.value, ciphertext), + } +} + +/// `ciphertext` decrypted in CBC mode with PKCS #7 padding. A wrong key shows as bad padding, +/// which is said as a wrong passphrase (the MAC has checked by then, so it seldom is). +fn cbc_decrypt<C>(key: &[u8], iv: &[u8], ciphertext: &[u8]) -> Result<Zeroizing<Vec<u8>>, Error> +where + C: aes::cipher::BlockCipherDecrypt + aes::cipher::KeyInit, + cbc::Decryptor<C>: KeyIvInit + BlockModeDecrypt, +{ + let decryptor = cbc::Decryptor::<C>::new_from_slices(key, iv).map_err(|_| Error::Unreadable)?; + let mut buffer = Zeroizing::new(ciphertext.to_vec()); + let len = decryptor.decrypt_padded::<Pkcs7>(&mut buffer).map_err(|_| Error::WrongPassphrase)?.len(); + buffer.truncate(len); + Ok(buffer) +} + +/// Where a SafeContents is: the passphrase, whether it came out of an encrypted safe, and how +/// deep in other bags. +#[derive(Clone, Copy)] +struct Safe<'a> { + passphrase: &'a str, + legacy_password: &'a [u8], + encrypted: bool, + depth: usize, +} + +/// The bags of a SafeContents, into `found`. +fn safe_contents(bytes: &[u8], safe: Safe<'_>, work: &mut Work, found: &mut Found) -> Result<(), Error> { + let Safe { passphrase, legacy_password, encrypted, depth } = safe; + if depth > MAX_NESTING { + return Err(Error::Unreasonable); + } + let der = Zeroizing::new(ber::to_der(bytes).ok_or(Error::Unreadable)?); + let (list, rest) = ber::read(&der).ok_or(Error::Unreadable)?; + if list.tag != 0x30 || !rest.is_empty() { + return Err(Error::Unreadable); + } + for bag in ber::children(list.value).ok_or(Error::Unreadable)? { + work.bags = work.bags.saturating_add(1); + if work.bags > MAX_BAGS { + return Err(Error::Unreasonable); + } + if bag.tag != 0x30 { + return Err(Error::Unreadable); + } + let fields = ber::children(bag.value).ok_or(Error::Unreadable)?; + let (kind, value, attributes) = match fields.as_slice() { + [k, v] => (k, v, None), + [k, v, a] => (k, v, Some(a)), + _ => return Err(Error::Unreadable), + }; + if value.tag != 0xa0 { + return Err(Error::Unreadable); + } + let (value, rest) = ber::read(value.value).ok_or(Error::Unreadable)?; + if !rest.is_empty() { + return Err(Error::Unreadable); + } + let key_id = attributes.and_then(local_key_id); + match oid_of(kind)? { + KEY_BAG => found.keys.push(KeyBag { key: Zeroizing::new(value.whole.to_vec()), encrypted }), + SHROUDED_KEY_BAG => { + // EncryptedPrivateKeyInfo (RFC 5958 §3). + if value.tag != 0x30 { + return Err(Error::Unreadable); + } + let parts = ber::children(value.value).ok_or(Error::Unreadable)?; + let [alg, data] = parts.as_slice() else { return Err(Error::Unreadable) }; + let ciphertext = octets(*data)?; + let key = decrypt(alg, &ciphertext, passphrase, legacy_password, work)?; + if ber::read(&key).is_none_or(|(k, rest)| k.tag != 0x30 || !rest.is_empty()) { + return Err(Error::WrongPassphrase); + } + found.keys.push(KeyBag { key, encrypted: true }); + } + CERT_BAG => { + if value.tag != 0x30 { + return Err(Error::Unreadable); + } + let parts = ber::children(value.value).ok_or(Error::Unreadable)?; + let [cert_kind, cert] = parts.as_slice() else { return Err(Error::Unreadable) }; + // (SDSI certificates are of no use for mail: left out.) + if oid_of(cert_kind)? != X509_CERTIFICATE || cert.tag != 0xa0 { + continue; + } + let (octet, _) = ber::read(cert.value).ok_or(Error::Unreadable)?; + let der = ber::to_der(&octets(octet)?).ok_or(Error::Unreadable)?; + if found.certificates.len() < MAX_CERTIFICATES && crate::cert::Cert::from_der(&der).is_some() { + found.certificates.push((der, key_id)); + } + } + SAFE_CONTENTS_BAG => safe_contents(value.whole, Safe { depth: depth.saturating_add(1), ..safe }, work, found)?, + // CRLs and secrets: of no use here. + _ => {} + } + } + Ok(()) +} + +/// A bag's localKeyId attribute (PKCS #9), when it has one. +fn local_key_id(attributes: &Tlv<'_>) -> Option<Vec<u8>> { + for attribute in ber::children(attributes.value)? { + let parts = ber::children(attribute.value)?; + let [oid, values] = parts.as_slice() else { continue }; + if oid_of(oid).ok()? == LOCAL_KEY_ID { + let (value, _) = ber::read(values.value)?; + return (value.tag == 0x04).then(|| value.value.to_vec()); + } + } + None +} + +/// What of a private key (PKCS #8) its certificate's public key must match: an RSA key's modulus +/// and exponent as `RSAPublicKey`, an EC key's public point derived from its scalar. +fn public_of(pkcs8: &[u8]) -> Option<Vec<u8>> { + let (info, _) = ber::read(pkcs8)?; + let fields = ber::children(info.value)?; + let [_, alg, key, ..] = fields.as_slice() else { return None }; + if key.tag != 0x04 { + return None; + } + let (oid, _) = algorithm(alg).ok()?; + let (inner, _) = ber::read(key.value)?; + let parts = ber::children(inner.value)?; + if oid.to_string() == "1.2.840.113549.1.1.1" { + // RSAPrivateKey (RFC 8017 A.1.2): version, modulus, publicExponent, … + let [_, n, e, ..] = parts.as_slice() else { return None }; + let mut body = n.whole.to_vec(); + body.extend_from_slice(e.whole); + return Some(rsa_public(&body)); + } + // RFC 5915 makes the public point optional. Derive it from the private scalar, + // and refuse an inconsistent supplied point rather than trusting bag metadata. + let scalar = parts.get(1).filter(|p| p.tag == 0x04)?.value; + let supplied = parts.iter().find(|p| p.tag == 0xa1).map(|p| { + let (bits, rest) = ber::read(p.value)?; + if !rest.is_empty() || bits.tag != 0x03 || bits.value.first() != Some(&0) { + return None; + } + bits.value.get(1..) + }); + use p256::elliptic_curve::sec1::ToSec1Point; + let point = match private_key_kind(pkcs8) { + KeyKind::P256 => { + let public = p256::SecretKey::from_slice(scalar).ok()?.public_key(); + if let Some(encoded) = supplied + && p256::PublicKey::from_sec1_bytes(encoded?).ok()? != public + { + return None; + } + public.to_sec1_point(false).as_bytes().to_vec() + } + KeyKind::P384 => { + let public = p384::SecretKey::from_slice(scalar).ok()?.public_key(); + if let Some(encoded) = supplied + && p384::PublicKey::from_sec1_bytes(encoded?).ok()? != public + { + return None; + } + public.to_sec1_point(false).as_bytes().to_vec() + } + _ => return None, + }; + let mut bits = vec![0]; + bits.extend(point); + Some(bits) +} + +/// `RSAPublicKey ::= SEQUENCE { modulus, publicExponent }` around `body`. +fn rsa_public(body: &[u8]) -> Vec<u8> { + let mut out = vec![0x30]; + let len = body.len(); + if len < 0x80 { + out.push(len as u8); + } else { + let bytes: Vec<u8> = len.to_be_bytes().into_iter().skip_while(|b| *b == 0).collect(); + out.push(0x80 | bytes.len() as u8); + out.extend(bytes); + } + out.extend_from_slice(body); + out +} + +/// A certificate's public key as [`public_of`] gives it: the subjectPublicKey's bits. +fn certificate_key(der: &[u8]) -> Option<Vec<u8>> { + let cert = crate::cert::Cert::from_der(der)?; + let spki = cert.public_key(); + let bits = spki.subject_public_key.as_bytes()?; + if spki.algorithm.oid.to_string() == "1.2.840.113549.1.1.1" { + return Some(bits.to_vec()); + } + // (An EC point: the BIT STRING's octets, after its unused-bits byte, as `public_of` gives.) + let mut with_unused = vec![0u8]; + with_unused.extend_from_slice(bits); + Some(with_unused) +} diff --git a/crates/smime/src/pkcs12_tests.rs b/crates/smime/src/pkcs12_tests.rs new file mode 100644 index 000000000..1d640ecd7 --- /dev/null +++ b/crates/smime/src/pkcs12_tests.rs @@ -0,0 +1,568 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! PKCS #12 files opened (#30 R13). The files were made with OpenSSL 3 for synthetic +//! `example.org` people (an RSA key for Alice, a P-256 key for Bob, both under a test authority +//! made for these tests alone), with the passphrase `example-pass`: +//! `openssl pkcs12 -export` (PBES2, AES-256-CBC, HMAC-SHA-256), with `-keypbe PBE-SHA1-3DES +//! -certpbe PBE-SHA1-3DES -macalg sha1` (the old scheme), `-legacy` (RC2-40), `-nomac`, +//! `-keypbe AES-128-CBC -certpbe NONE -macalg sha512` (Bob's), `-passout pass:` (no passphrase) +//! and `-iter 2000000`. + +use base64::Engine as _; +use proptest::prelude::*; + +use crate::pkcs12::{Error, KeyKind, MAX_P12_LEN, looks_like, open}; + +const PASS: &str = "example-pass"; + +fn bytes(b64: &str) -> Vec<u8> { + base64::engine::general_purpose::STANDARD.decode(b64).unwrap() +} + +fn der(pem: &str) -> Vec<u8> { + crate::import::certificates_in(pem.as_bytes()).remove(0) +} + +#[test] +fn a_modern_file_opens_with_its_certificate_its_authority_and_its_key() { + let opened = open(&bytes(MODERN), PASS).unwrap(); + assert_eq!(opened.certificate, der(ALICE_PEM)); + assert_eq!(opened.others, vec![der(CA_PEM)]); + assert_eq!(opened.key_kind, KeyKind::Rsa { bits: 2048 }, "RSA keys aren't used here: the window is told"); + // PKCS #8 PrivateKeyInfo, RSA. + assert_eq!(opened.private_key.first(), Some(&0x30)); + assert!(opened.private_key.windows(9).any(|w| w == [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01])); + // Never shown, even in a log. + let shown = format!("{opened:?}"); + assert!(shown.contains("redacted"), "{shown}"); + assert!(!shown.contains("48, 130"), "{shown}"); +} + +#[test] +fn the_old_triple_des_scheme_opens() { + let opened = open(&bytes(LEGACY), PASS).unwrap(); + assert_eq!(opened.certificate, der(ALICE_PEM)); + assert_eq!(opened.others.len(), 1); +} + +#[test] +fn an_ec_key_finds_its_certificate_by_its_public_key() { + let opened = open(&bytes(EC), PASS).unwrap(); + let info = crate::import::certificate_info(&opened.certificate).unwrap(); + assert_eq!(info.addresses, vec!["bob@example.org".to_string()]); + assert_eq!(opened.key_kind, KeyKind::P256); + assert!(opened.others.is_empty()); +} + +#[test] +fn a_file_with_no_passphrase_opens_with_none() { + assert!(open(&bytes(EMPTY), "").is_ok()); + assert_eq!(open(&bytes(EMPTY), PASS).err(), Some(Error::WrongPassphrase)); +} + +#[test] +fn a_wrong_passphrase_is_said_as_one() { + for file in [MODERN, LEGACY, EC] { + assert_eq!(open(&bytes(file), "wrong").err(), Some(Error::WrongPassphrase)); + } + // A passphrase with a character past the BMP can't be one a file was made with. + assert_eq!(open(&bytes(MODERN), "\u{1F600}").err(), Some(Error::WrongPassphrase)); +} + +#[test] +fn a_changed_file_fails_its_mac() { + let mut file = bytes(MODERN); + // The MAC's digest is near the end: change its last byte, then a byte of the content. + let last = file.len() - 30; + file[last] ^= 1; + assert_eq!(open(&file, PASS).err(), Some(Error::WrongPassphrase)); + let mut file = bytes(MODERN); + file[200] ^= 0x40; + assert!(open(&file, PASS).is_err()); +} + +#[test] +fn what_is_no_longer_safe_or_unvouched_for_is_refused() { + assert_eq!(open(&bytes(RC2), PASS).err(), Some(Error::WeakEncryption)); + assert_eq!(open(&bytes(NO_MAC), PASS).err(), Some(Error::NoMac)); + assert_eq!(open(&bytes(SLOW), PASS).err(), Some(Error::Unreasonable)); + assert_eq!(open(&vec![0x30; MAX_P12_LEN + 1], PASS).err(), Some(Error::TooLarge)); + assert_eq!(open(b"not a file", PASS).err(), Some(Error::Unreadable)); + assert_eq!(open(ALICE_PEM.as_bytes(), PASS).err(), Some(Error::Unreadable)); +} + +#[test] +fn a_pkcs12_file_is_told_from_a_certificate() { + for file in [MODERN, LEGACY, RC2, NO_MAC, EC] { + assert!(looks_like(&bytes(file))); + } + assert!(!looks_like(&der(ALICE_PEM))); + assert!(!looks_like(b"")); +} + +/// A DER element of `tag` around `content`. +fn tlv(tag: u8, content: &[u8]) -> Vec<u8> { + let mut out = vec![tag]; + let len = content.len(); + if len < 0x80 { + out.push(len as u8); + } else { + let bytes: Vec<u8> = len.to_be_bytes().into_iter().skip_while(|b| *b == 0).collect(); + out.push(0x80 | bytes.len() as u8); + out.extend(bytes); + } + out.extend_from_slice(content); + out +} + +fn seq(parts: &[Vec<u8>]) -> Vec<u8> { + tlv(0x30, &parts.concat()) +} + +fn oid(dotted: &str) -> Vec<u8> { + use der::Encode; + const_oid::ObjectIdentifier::new(dotted).unwrap().to_der().unwrap() +} + +/// A bag of `kind` holding `value`, with the local key id `id`. +fn bag(kind: &str, value: Vec<u8>, id: &[u8]) -> Vec<u8> { + let local_key_id = seq(&[oid("1.2.840.113549.1.9.21"), tlv(0x31, &tlv(0x04, id))]); + seq(&[oid(kind), tlv(0xa0, &value), tlv(0x31, &local_key_id)]) +} + +/// A PKCS #12 file of one plain safe (no encryption at all) holding `key` in a plain key bag +/// and `certificate`, both with the local key id `id`, under a SHA-256 MAC with [`PASS`]: what +/// `openssl pkcs12 -export -keypbe NONE -certpbe NONE` writes, and a file that pairs any key with +/// any certificate. +fn plain_p12(key: &[u8], certificate: &[u8], id: &[u8]) -> Vec<u8> { + use hmac::{KeyInit, Mac}; + let key_bag = bag("1.2.840.113549.1.12.10.1.1", key.to_vec(), id); + let cert = seq(&[oid("1.2.840.113549.1.9.22.1"), tlv(0xa0, &tlv(0x04, certificate))]); + let cert_bag = bag("1.2.840.113549.1.12.10.1.3", cert, id); + let safe = seq(&[key_bag, cert_bag]); + let data = |content: &[u8]| seq(&[oid("1.2.840.113549.1.7.1"), tlv(0xa0, &tlv(0x04, content))]); + let auth_safe = seq(&[data(&safe)]); + let salt = b"example salt"; + let password: Vec<u8> = PASS.encode_utf16().flat_map(u16::to_be_bytes).chain([0, 0]).collect(); + let mac_key = pkcs12::kdf::derive_key::<sha2::Sha256>(&password, salt, pkcs12::kdf::Pkcs12KeyType::Mac, 2048, 32).unwrap(); + let mut mac = <hmac::Hmac<sha2::Sha256> as KeyInit>::new_from_slice(&mac_key).unwrap(); + mac.update(&auth_safe); + let digest = mac.finalize().into_bytes(); + let sha256 = seq(&[oid("2.16.840.1.101.3.4.2.1"), vec![0x05, 0x00]]); + let mac_data = seq(&[seq(&[sha256, tlv(0x04, &digest)]), tlv(0x04, salt), tlv(0x02, &[0x08, 0x00])]); + seq(&[tlv(0x02, &[3]), data(&auth_safe), mac_data]) +} + +/// The private keys of the fixtures, as PKCS #8. +fn rsa_key() -> Vec<u8> { + open(&bytes(MODERN), PASS).unwrap().private_key.to_vec() +} + +fn p256_key() -> Vec<u8> { + open(&bytes(EC), PASS).unwrap().private_key.to_vec() +} + +fn p256_certificate() -> Vec<u8> { + open(&bytes(EC), PASS).unwrap().certificate +} + +#[test] +fn the_kind_said_is_the_private_keys_own() { + // A P-256 key with its own certificate, in a plain safe: it opens, and is said to be in + // clear in the file. + let opened = open(&plain_p12(&p256_key(), &p256_certificate(), b"1"), PASS).unwrap(); + assert_eq!(opened.key_kind, KeyKind::P256); + assert!(!opened.key_encrypted, "a plain key bag in a plain safe"); + assert!(open(&bytes(EC), PASS).unwrap().key_encrypted); + assert!(open(&bytes(MODERN), PASS).unwrap().key_encrypted); + // An RSA key with a P-256 certificate sharing its local key id: no certificate is its. + assert_eq!(open(&plain_p12(&rsa_key(), &p256_certificate(), b"1"), PASS).err(), Some(Error::NoCertificate)); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn any_bytes_open_without_a_panic(junk in proptest::collection::vec(any::<u8>(), 0..1024)) { + let _ = open(&junk, PASS); + let _ = looks_like(&junk); + } + + #[test] + fn a_damaged_file_opens_without_a_panic(at in 0usize..4096, byte in any::<u8>()) { + static FILE: std::sync::LazyLock<Vec<u8>> = std::sync::LazyLock::new(|| bytes(EC)); + let mut file = FILE.clone(); + let len = file.len(); + if let Some(b) = file.get_mut(at % len) { + *b = byte; + } + let _ = open(&file, PASS); + } +} + +pub(crate) const MODERN: &str = "\ +MIIOEgIBAzCCDcAGCSqGSIb3DQEHAaCCDbEEgg2tMIINqTCCB/oGCSqGSIb3DQEHBqCCB+swggfnAgEAMIIH4AYJKoZIhvcNAQcB\ +MF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBDdm3fB+5srzOj3zg38HGApAgIIADAMBggqhkiG9w0CCQUAMB0GCWCGSAFl\ +AwQBKgQQvM0sSUpkFZIgMm8ugLNoeYCCB3DTS+ebN3ewVoyZqBEVHgql+fwsLs2Kg1+vsIpYO6KKjRTdBOZcc43YM0KcswLrG9Pn\ +Nk9h5L3j4iXV5F4pjDpsLB/myW9NveaGnVh/3fuiPbCuyGFZFnyO/R45vFcDkoyPsG/GKLWPZuHIUZ4ZypHj8YJm6hgZyzFzxjmx\ +lMogMrNxsne0FSFLS8bLT4Y6onx8ERTLqTRWjtl+HmVYOy7/st3MB50p6Gkl1JJLvPJc+y0XBqtV8KXnn1fFBPDtSjpFX2A1TRBW\ +lSDMEKm/YA2PO1daflSoJxRmyQXdyprI0jBd6oea7larA6PexvHX5en/3Vw5P02s49dxnJSGkuqhk1mKTJJTvdu/s3WBfvTBEmiV\ +sL67c31NmDsNTQ9FUQNZKSvEj3OLZ6752e/enf4dHZebvxXcYIHLndpGAVF+jvjYoZ68O+unm2jP8k94lkHgnwu+LYBBdEpfmntU\ +lfFN68RmuOyuIUQn8Xmpw5sEH4TDLTodI5BFLHb6+Rcz6tvTFZTUcaVTJfVP4O0ZaSy/vgDSBFN6X0LwHG+znHi+hkZr2gMhElRi\ +q2Ewx/iSOWVn6Iy+k1TE+qBc1tuOA1BvzaRlg712WWM5SyNTx25+1/6G1CW7xbbyz9AmQQacZ1PUXpqr9JD5e21OgYvldy9Tt38l\ +IY/Vk5aqpD4hScAv5Ncwr7aGuchhJ8AJLkBRT1SLpazhwzmbyoSYBlwEZ/WpY8hc35OsMLHI8jgR9BXBuUVrP0kM+kFBh5Cyb1F2\ +zRFDTAGKaRh7kVAd/GHPQ6t/FveBHp2ne9ADXXF3Nl1MqAXAuSBhZs2WTWTxOG2cy+4ocb1psFia3Y9abxjMksB23byqCt+ZX1mL\ +DXmfK0EUxq1K1twkJJEQnnMcp9lvEgc4uzggu8zICWsPRh/H1v0VlDp7PextlWotnf1TnTI8WgjcqT6JsDUmLEtwEufsSQtbHm26\ +vXbLBLdW0ZTG57FmqjkPXptnrxk+X9athIxcMaphL0HZIIId5zUqDBzw5hTCf9SUd6lNjkmK5h1qTBkOF3oUWCmxZc9kcCt54nKk\ +YvKjq602dWGxI9WQ41symceExKYXqfrsKKVLEofNPr6ObYyc6dgeM9Tq0D21XMr3L4Z0rpFUj7jPbS+0vJGtXFnOCfdkEBmR/00U\ +chFTsOEHQZ2lbsaZt0MSiN1kvfvOh22mdiM6Q6VPG5HCBTIpvgOoC5RvjRxVZzDl1HDgUuPG0cM8B+tnn2IVuyflnygwoTpHZtLQ\ +qfA6ZVFnJTfMFuXwzhRDk9yJafE33gyYCLpfewQ31ljE3x/CmXdA5kzSiwRizb+Z0LJZMGI6zh/iA5tKa4xWL7IpOXPex/xe9Lhh\ +cpVLk+ylN6GUeOOcHt1bYujRQuM4BmWnNVJ46Uf2ozUd72x3jystLTYDd9+JnNLfFrKMdkyIkm4/Hihyu0GMPm5YSfgFG2qQPY2l\ +GqPV8Xs09CrZM/X10Td+a4nBFVU9HwVzWX1H4cAJXwsjanojxX1J75LAbrRQBWozWgtpBavsG+1G55ygnG+4z5+P+JYnspzTxxG1\ +NgpE6ngq9aMjZ6AsiZM5rzX78LKjuWSzA9xfawnOukt2irF/j+cDIojJR9NdLiCgh1v9AckJzQQh96NFsQ9w8s2FGUurMMih/dln\ +onyw0m/8VHYx1HPoIgwhJgOvsIrwHjkxG6gS4cIJCRBWwj/93nYgyYEBkBD24g5hMrsNpHfgf9jvQZ5y/Sj/5jNf4n0GzQXnTQur\ +Mm9FuEb3VAIfU1tNYevZ/xdF66yQ9NApmUXvTiHlitvI9ndebAW8etiLAwBajsb6eBbI489cOzCvI/9hoouFns3wSFNVuHNRD2qg\ +Ujl6dNPyPnuzow6tQz4mFPRi/WMl3aSq3CWZ9kybYJXNIO/2vaN85a7bx3tueZaAs1Jm/HrHpiwYXDM2nFqXYWDyeAfq+xLfwsJ0\ +a/eJ7s74Vjibl9ANfe7Pkb0v00y4vFkMJ60Yk/3TuW6qqLrIjAqQ8Qh+aFH/IZ1wFdibZk9Hk3yFoCV1CgA5hGT4WouTkEV8Z7PT\ +gC/ipwbgOPXUEq33yfTFDFbmrk9PvbpjSWKA9Aw+7CPA9j22j0ciYvNGacHKdf5Qgmh1J5W6uC0Rz+WupFEKwkYqj7MM3zp92tKQ\ +DXIoutcAPmQOsqapR6POtbz9J62RZLZDSkiWfMSyRzNuoOZW8TvdH7Xi/y4FH3bMBDIbNrdDIzS9yxrTMBjv773Aoa+iCtATmcU5\ +dGu22y9IUJ95hALMMRRu01RvzyImR3RZLM3zXVpMrdirFPcQ0xV3zXsxquNMBTm7LEaZPO5iUIC8kaaOSxy6X3ETG2Dd74WuB3C9\ +Y+3Jrx55yUd8vdgflIxwv3JxBhS+rqMqNSmS6ho/4Yip7SVLtrGNPyDt267y+CH2kLGyhjIccH46k/o0P/V3Rj+3RKkI5zea1jRG\ +N4ZqezhlpJJOea/MFbDS/1hV+3EAzklYs++Pw9Xeywtr21GtzVgGnmNlZj7aaf0f6VA5xC+CBjCCBacGCSqGSIb3DQEHAaCCBZgE\ +ggWUMIIFkDCCBYwGCyqGSIb3DQEMCgECoIIFOTCCBTUwXwYJKoZIhvcNAQUNMFIwMQYJKoZIhvcNAQUMMCQEENj6DxvnJypnlOxD\ +B4pal5ICAggAMAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBDwjW/DvRppLgPgUc4+brTxBIIE0Gibr1mXoSTq1KNRphdw8u0Q\ +PJosufEujUHoGpnTeYPnkjjfilvFrwSVN4nB8A8hB/pth1NCPFAxGSkdIZtf8AImtCZ2DDXoX1G8210m3RdoI1G5zA3RXgefKDzT\ +vVh5iKTjqIorB/slrDkTd2vBdI6odSzii+2wwUMeF6pxZ4XDjc155HFpXA5zvwIEUPbKOG+Ah9khv9ZsB2ya11hfay3/w30q87uJ\ +74lOnkEMU00e5fkHu4V/oE/2dcHRvY76f0vqpxVgLpVVQRAn5IhXNEOiJ5wDIB86zf8Eg4eMuTgWoJaOux8vA7pSzOgNZrrOD4hM\ +hXHRclWmMZqXYgz3bTTU1VfTaqID6XKnPKjQymbzfsre0M3lixdq8EdylKIDWazMuIGo3sLnJV0to0UAmKWrzqBUdedAVcSdKjHe\ +HF/NJmtzzbiLXI5s7UuqBPOKvwMLWWCm1JN70SQBX+IEP8OU1d1TJghAn9kFq6gEq4uMB/L69T+r8LQLY6ralvGbDvCGfBqvmbqM\ +una2ZKdHJ9X/B8IQuP2ioraI8ToN11wywLwPwGgISrwyVpBwQQDmPjfxs2yfgDNqb+NxZAT1+MnW9Sibo8WN+R91QOJRCxgMQmdV\ +alJFZljUH0ZhvugvdLeguAElnATMF2R5r6JmprYJA/jqz3BUo/WkUnHsV0nAhps7d9oHRkQMRQ/oYwzONBfLDmEb6AkbqAYLGJHw\ +PDHQ1efrgZlo0GeokG224wDzz2OlFSrWqMX1RQ95aM7DI/vUAO1kKI58uVYXSDwg3a3VBzhrZLedkkPU5m8SM2sYJgtmi6rKHllO\ +XvTpOPXX+XohJr7Q7S0XFR9KoSHeH1q29E/aOT01Wp7Wfq19hhtAkJtd48vOoZmoE4DdSy1mVfGXouU5piS6a+HF9HIhEZbMvP2T\ +t5EAptK5KxaJQ5xj3ICJ8tfFmePZqMITIeQem4Dpem1rcwc3eh5A1tGLoGITFEWB1TDl5wl65hY3MZItmAAqabBwaHIPhThIEYxu\ +xlSSj9GE9Tuhq00sBLfBQnDULf0XYxInFnoWalvFNtmWLR+3njdwJ5r4bPGJrNhnpDqPEPlwCJ/nKzQf1DGb/0rc7Vx2VDfNYkvU\ +4u7+M4YQm7KIsWBVZbWjNHOOUoP5iU5OaAbfFNjW5zs5h9VJSh1Yrh5UGbFk8rfR+UF+GlEA2NQ0X16N4lPFGvQqJhDX3IgKVKhX\ +nhyV1HSkLn0qUnQH8oT9ZfqASUxN0uaTN3MYGZQTRB/vKwg3V6zxKtQD3PLqRWR1eFm8UYq3/3Sa1H+qYje5GsWXL+wbB1UXrnP8\ +O4v1/PJ759QDqCpEXSc/YUAxw2J7g54LJEUKFwvvTEprlP75LFnXaRx60kzi0RDzvOzbBDIdjYtiOCEgX2l6D0TWnYPVvqsy4cK7\ +wY0OND6oE5WS2WxSCGMsfgIuOWjQ4zNFRZpjwVwBPjSbgYLY0Lxt+k3/9i+QQVrurodJQeO12rk5hn32ihc71JyQfMH5b8i/bVGs\ ++7cJhmc+I56DJ6S/o+M5RxHFIH03iBwp6wxwz9zu67OFa+w89Aybp80TeqjAcMFoqqJoO5tBub83yT7///FLwF3TraZUkWm1Cqgz\ +F5qTXAqUVgAYo3XCHFEjMUAwGQYJKoZIhvcNAQkUMQweCgBhAGwAaQBjAGUwIwYJKoZIhvcNAQkVMRYEFIVDIKpsK9ynC1lADgpT\ +GrG04AAzMEkwMTANBglghkgBZQMEAgEFAAQgGqUPhUzRMcaqds9vgTOSCbcRLzd3zWp/qA73DkTB8zsEEB9ajyrtEIfDiOZeZ+v5\ +L4kCAggA"; + +const LEGACY: &str = "\ +MIINQQIBAzCCDP8GCSqGSIb3DQEHAaCCDPAEggzsMIIM6DCCB58GCSqGSIb3DQEHBqCCB5AwggeMAgEAMIIHhQYJKoZIhvcNAQcB\ +MBwGCiqGSIb3DQEMAQMwDgQI0ywIdIL+wmUCAggAgIIHWCNIi5dNd/xDFZskzoB0TEfhZ7bZE/3+oz+hJ4aSPSKFQ12Dw77TkEio\ +FSJ3n2G8EimkuNz/d4JNhuo/kVHNQUBS6Fq//WcB1j7uQOO4M65Lz5nXcTCihxBqhVHamKWqYwnzAwkiYvjy+SLXcAS+JeXPieWX\ +BjTq2D8pSPZ2g18IalAPQFuF6wkN4K9ninrpz9IXhss5+05hgTj2xKZdj9zrU4HL3gZ5C9iAudsUDiMB9vA9ruvr7HrhLCW9ezWs\ +Vuav57JvSEXm1EGMhx0Xu5t6nf1AwgzKJ9+D3chvV4XvIV37ITvwoT5eCiAsHaCn1AJD8Q8R/26W9ypGOpuJfeXEtIyXcbybCkJ6\ +351XP0Wt87l1/i1JHsJHwgErfCASgrL2zkQGymIUxjdTtaE55kBgL9BJZvCjagI9uMw0rC5azJ8UwJwp+fsVnzYXzVsvCFK7cVR8\ +LLA0nQSiwu9E24U6/b7zn21WktBF3UFmLWsdCCEbvrrxZOmmGuwWikSF3Li4s5n2uNMJ9pJkm6qFqOvoie2048UOzcO4uuLbV+kb\ +KobV5BEo/EQQoiI66+Z7z7cK6nUjiEZNpeZKqaVnNunuJN2WvGlO4EqLykjj7vzVUU3XKHoKwpsaGalihbvKVcA939KvP4GYTyu0\ +N2UWQ9BUn/XLV+e/oHD2YLkclbYM6Xt5ZDf3RZ1mvDu8GVU8wCpL4TiYf7UA3Nc5k77O4fg9wy9cQgaM3gJwhTz4LmWJO4CgLaHY\ +Z1MoFgRghg6CWRgWrFuDwuB14FjkYsQSwCexd2KoZgbeCb2E9kVRHX9j16Y3fq4k1VzOlg70nSJr3xqhsKB4u7ahr0J3jdhIb6Xm\ +m2yknpFaOyVs9/6J8r7DYV0P1VjIAjhGfTlhQxh7Dzw/BDUrLeLbZAvzwDxZB7d2VeezGcwJz99QcyV3HC0G+rBUwyq6umUbE8cl\ +Lic0hZ1uXDiGraPSe5VZ/HCfIZCLPJfRn2of7B+QOORPiNQ869dj1Kpr59bcgu8D2hjU795TYSn4n34+5wUp3yF5mZ+DDlSEY/yZ\ +2De3QrZsEyRMrhHwDssDa2VQ4EVOeyx4KsSdfKKQDKsBoFk8cpu6Au4gw4j3/LVZZC6e7arqHwJae5vG9vuXa7TYulIQm81l8AGi\ +jV5EOWx6W7JZoiFpF506EISnDvjCjcSJ9xUPKoBoQpl0GjxPf66WakDMclKx5gsw3WTV5WNOsUHGqW7+fVS8+XdHTVzeniXprqKR\ +XXI7qQvTsgjeks300xfOXZczaBBM923HqKXzl2eR9gAJx/pcpqF330dL/KOOnJMsaXJNq20kD5ZPjjbQ+EjmEgb68QbbwSYNTg5Y\ +SCFtzrGuQ1XFAJ0e7tS6umNi2LSUOdPr1VlyXvm/03uf6Zm1JMHbmv61wia1dtyksUnO9FxrRbwpRSFT/5KBY7ZPZinbQpE2Rlxx\ +NTpu0fKCZOUokvgWHAI9brPEKgRrNdkiugRP9RvpY6UX6v82Lby14iPH+ehH9sP2NhY+vlL1qS91n9HY+HygWOcMP/PfN3HpAcZU\ +QnlZnsq4ZO+U5piY1NrKTTcnhzIGKx5ObQcDolaoczLZTFwSxyxiTlRcJyJllIR/ff+64/wNiTdYODI3rEJunEQAbf5kEPKD0Rqn\ +YRgZRtMEWk1ADKHHbjykFupIgP6dSncJ0oiH2Pq84KU0SrJspJ1gQfmywgGV0gGc8alLeifHqktPdU4OEVq4FKZzSAVyTh9o0BX9\ +KOfsbM8iRlDa2AYP+Qnfbm7wmOFThnseg5rJ4aA7jUgtlkLg9YhMOI0Uh/vIAUopr5sK1qiU/w0XykCbU0JD36qyVSFxCdSweB1E\ +rKBf1FZ5AF0pR9XgCadKBATY9vwaLxTBxTWPJwdxKSCbAOc2V3UD0yzWvxTgzL2sh3YPZFVvJJot1aYO2U+J0omYo3c86h0bYyrY\ +uCEESVoBz1Euzs912It5Z+2s4R/f2Xu6EGQHGSTFIzuRQlzuAlHyBPZhToLkclFegQapeXzyrJwOusUaGtGqkmJZoseZ/yTxGBhk\ +c9JXuTHTYnsCEiuKhyeFG1yGRDlf/AiCDN6zOBNMiXJGdpvKrcx+Efz8hdZ94CE4FUp2QRnyKDVBYKd+6fa4Cv+LsCF+Ohk8zCt0\ +FrniW0GMvjrjvRCZYADyS94LWIVm57Xggz9t+3OONOW0xpswJCNCNpwttxP/FYa3A63jYatywOj4343vOMyubLGWpeaNnAzPVMHb\ +Yb1Utx6Xhj4DMmfAK69E3cCHH06auio+bmJx7p23k5UCc+ifA9o4qW9HuZtqfRUhWc+qFycZAaENll2nMHKctlhxId5bZ+R3EzJp\ +a6doHHgwLA8/YJiCTmt68pXV9zHlMfGhv22E3RPBCJX94265+llB/juy1CdrfDzszoM8sE6ikJ0BCWbIOvDHmzHeOUpW9gq17/rC\ +bmAzZLsfD2fZW18+Ygzd86Ci+VgdB+4YtGDYUom0SIFlJn/QNGKFMIIFQQYJKoZIhvcNAQcBoIIFMgSCBS4wggUqMIIFJgYLKoZI\ +hvcNAQwKAQKgggTuMIIE6jAcBgoqhkiG9w0BDAEDMA4ECEwWX85zkiPsAgIIAASCBMijlMCuQ4vGtXt5aSh+gMYSRbErCCsU7YSQ\ +ShBrz2ELWaNE2tXKyICqb/+TD+9nLJFikT/x1wF2I4qtTq9TRLf3WhR7wQGN9vxbeAS8w+0V8iBBmDlesS8zE76m3hBbrnxpSjEh\ +Q4+IwKEFU33WwdEVTbSRQj0R3DhQN10QR/8hhRHpxZlEQY5S9u0eVrFH8vObMlj3HJCx1tUiTAEmDMeVIA2Yy3bnnbdE1z7PLyKt\ +peBvfCg/2nczZLW9DRUquGhZp9MwdbLvpkR7COgBDTZY5MBGU6SfDyPffBaNaHS9ZmTKeOIHR67ZYQ/tT/5IlA+NKmAoKmMTjmO6\ +GIv+uDLWJPZVwFPcNxDe0YHZWgFrxOHam1HFIDHacGzCjJ8kJgYK7qPT4UzW5658wZrPPayGUs7OdcBSlUXoUPwI6GzdgxtPh9DF\ +6CFbHqvuyOo/XFP7pENIcZ+Fgpk7ruB9dJGC1rMlbg9v2myYEDlvH7ydJMAQKWEF4Cosii6KO0Td+4HHz1RPXDzLT0vzdulg6pwP\ +BGEoHfcVfd0xUuJp+Rd0lO+SWIyrLNhQ9sNUowMLwuvIRJfOxWjZ/Hop21DEn1eJtweC2BOXKnxMRsdEVBmLMHPidc6bPi6djMds\ +xbYRz9rmQ0eaQFR87cvyUHQCSglO9uyLOnLFlmAehtWLev0AehRsexD5gaID5KReBXV7KNvPdTu0F8LvOCtNi2cf2eHwnJSWgKrN\ +QwHodyVhZ//pLe93tiGdASuvCrEXN7gdIREv0njRmRqxWUl8MKfLJn/XtpUrGNLnU4qFjxrKkvTo/k7Ax0A7DFAATyulan/NHnBq\ +iHF6ZuUL1jha7jMcyhq7J5zSqDSX/0LQqbaRHigZ8IsOXdV8gB4yCraG+fLm9H7PK3nIb9yIymu/eE/C2QWecIrfGSH7sem/q0ld\ +YXxOAwm12HtcJydR0iNzK0Ddty8heVqvZRoLe+G4aY899vk9Y+Lv/XP1kWQxp8sqFw2PWM4k8TCPdhlk76PgDlkmvtDg7Yl8usT0\ ++BDLRSxtebssQTkRZ+OZzHMuj3uvyDeB9xpicoqGLgU0Qqq5w6g1SXeqyJIiEf3z7dWWw+dXxb7vbDQYySMBaUEHvXFFSCwz31Ml\ +iQAmlDT+MBqLaQhsABTa/k47Pagov+X751QT4Hs3mr8khTUoqRpRZJmFol5GBpwk5GOTMYWHBdPfqoLoU8mEObQoHT7aOembQNaM\ +NOi3zpNeKZi9kNcmMCc8EMP9IuSqwpSdx7Vq0ZNK6dCUoGmod/PTVwk5rYKUdfenLoNS5HBZaawJa+0yXunNnbkHGU01AzR19d0Y\ +nrKczQxCwQz4tRi7cf2/d2xDWFgHbU6m5OH1BMaGZcW/d35zahiz0XXlvRNIN/3mxg2gi9BO+P5TLBi3iEHeQzOHJb4vmJlpcjXh\ +3nIPBZT2roWIKpb9THlzasf8OzTGphL+Ru0zBlNmeYeJhI5yF9lPj7yMDfRCo0jk39Yy1zcMQ7ZSIgXCVRzctJxdp5AsMLrqKQhp\ +eTUW7DQ1VFE2eCAPPNl2kMZ31tM/GKIUQbwnhgQspmjWbj9XwKlmRni6nWbh2/dp+7X/3e5cXS4fParNRcMZQmPt8Ka3IGTnS64x\ +JTAjBgkqhkiG9w0BCRUxFgQUhUMgqmwr3KcLWUAOClMasbTgADMwOTAhMAkGBSsOAwIaBQAEFMhJrwJwP5rTOUpuyMctQhSu75vz\ +BBA5cgeI/EDEl/gkbG7WnPM4AgIIAA=="; + +const RC2: &str = "\ +MIIJyQIBAzCCCYcGCSqGSIb3DQEHAaCCCXgEggl0MIIJcDCCBCcGCSqGSIb3DQEHBqCCBBgwggQUAgEAMIIEDQYJKoZIhvcNAQcB\ +MBwGCiqGSIb3DQEMAQYwDgQImY9Bmh6uNp8CAggAgIID4BTIb8wbN9av/HdVdrKW3Eu2N6IjA8GZZS44fkQWSMGQsHJqxJcJ4iHt\ +UNgG/fZUum+iwyceHL8dHrncGvaajpeyXvt8mqY33UxAesW3wj4Cw9PZMRy+Alsr6vv9vWiimdesEebRST+Y+eQWeXBRs8whlGQE\ +5sVNNtrm5QUsMOUas2tiOTF53sh7leVPLIaPq5sDw96dY5lK3RtIhcoORW8bPm2jqxWu8H5kyBIiOW2dRha4kyB4J6T3zT4Yzo/1\ +AK6RFkqU/UFTyYI8SRwozUE7nWAhO6zts+tTcyyTVFz+gcpP58PEtuWBJcGdFaNKh4Vf9E2oHwxFmjPRYgflmqtRvwVh8J1pL2zG\ +9LtDAqRrMwdjfw/PZHWgvbdKeZdj0oVRai5YlHBkqgJxKed9hH+ULrCuZOWrRcBV3V0zOPKvgcacdT81reJWP/DCEoVqaqxYea4I\ +oZ7TNsv0GQOOAriJKhsKGLy5vYFT9AOxtEcyr44vrJHzhZAxQUiBRbdbo46qEADkRGgVPRcnqzgJyxA8KAwCPSGeHHETxSE8qzvC\ +FqWdwxudGsQ6uxVDsptPKtyIZUkqR4nG/Fm4ZC0VgXjHfwKmiiLN9nYVvQDO7Xaq7TOrmUog+ifUaFuEEtbC3gbH88OX3Wr1g6lY\ +CLynNHp2KeoL559uVWLZMiNAjkQ4GevsP13GZTu84a00Ldc+hIKS9wj+bjP/JHlzSu++SHY9psD2/os+olCwHLUENMV5ML2rj1Oe\ +wcg6/HJF0TPmaAnsIxYYk5AgKSgpIwBocwco3siw16tn/1h6utRTEalO6vmPmBcWYMq9K5SeiqQ/J9X7JHC6qdGgtuOSTzAUqGzT\ +vwpHtMkIv2ITjWqewArQaUNw5WHxa0ZhhukprsFUmnc1Y1X7g0ddpGLZ3Dwn46AMivgsC4iA3FmPjykKGvhMddIxkaxLglNDKePx\ +1hfsCLYdNPYMHeIyw2EnYojyG9Ux/s5Z3f2LPYuK3WSS8xtvAZFDtrmVotKsGNzJiUpWH9dCTzOiHPmnakpodOJSxqxP/OlGuQzh\ +eIRMh3e6YKc809R0DVkKa3xP1kBbHPrdP+C0B24QTLUflYOLxzNY3dJ5wCZ5jbD1ZugJava/GqoV83qQkJ1hejaTsSWEhcRxBISm\ +z8guUuMemu7D2zS9cX+bJ+8scqijFzIx1/4q3WWkLPAiugK9HJ06DPfkqnxVvL4oaAVOHDVHyGJtaRiBzLUpOlC+dSkkbls/mmuk\ +sxzoiMZcAWO1vC1G/7wJsyXzS5wUvIKPgsIk3mF9GE+3TBADfnpuu6jw+GqotP53MLwuMIIFQQYJKoZIhvcNAQcBoIIFMgSCBS4w\ +ggUqMIIFJgYLKoZIhvcNAQwKAQKgggTuMIIE6jAcBgoqhkiG9w0BDAEDMA4ECOqPrTHFEt4EAgIIAASCBMjL1Rzzem4ErP7OZ3gD\ +eqNEzUjFxA1QlPbjaeLka39JtgzcsBAyIyEIgou3TddDzffJqd6V4/08Ls9SmpngPGpYXP07q6Xl1eFjrwQ+jMathtFWSHCqGgnm\ +5D9+IFalz/7/rQv43vVTqG7Cw7VCSKr0ly1dZAvGRFEnP83Ffvny+spKpSpWUY8SsY16333jp3Afb/V5NyfsJETdghxi8d56lThi\ +sx4FtTAhKMNXSLenQOkgHnscBh0w7Kg2PNBHzSW7qHQDvr5oq8ZOqIe6B3M1Lxxv5nVzSZRgHbvyy7d9nUFiuGSPMVINffXF8Acc\ +zTIbpkuW5+pEpCGKOyOsrqE8VyTLMq5e7MRPsmqu/v6CUR8gfFUp0B4ovFmsDyWOARbtoWx5aK4bhJbKX9CI+F3dKaWL9d4VJnxk\ +cYZtRHIfbrPKEb5Kk6oO4V9KOdPaXfhXkeARhLFsAQ9qb6tX3w75qfEaAwAiAjUJVgFFVQ7ycL8qNUUAt+xVNYTrYa3qXDVlsfW9\ +e/ok+XvIAhOlHIc60ug7OUmxa2E9zyeaEptRVxl1rMWaV/s8ZAQZhNzvRtNWPXUCR/pMGGySbO6G3fperpZZcIJqQ5o3nifM7Vak\ +XFHIpESFfiCD+dcl/cMlc8hzVORVaGNIc0kX6nzpZXKzXEAawEYwCpEf9T2CtD345/lZzfOGgxMEnENZrqaJCNeTmPxcSFmWAkDe\ +GsG2E6E7wX1XpuIpLu42Ik14Vgwb4Z1n9myuLqxATbnkMljJsIigr8WcGUSUOnru5ZoHZzZWGZGvQ5H3RGmDE4tWJMF4ngzTeOU7\ ++lvfmdg3bdL/jIdamvWXBbqUdsvECX1tORGZHAyJSkCqxupHaaARrSwd5t6hzM4y+dgDK5FRsxofN9ulujTDQPoKa/GuQ8rfCSxW\ +02kL8aCtv1BsqitghPMOeBst0xAFLvOrbYO6BVJpZPb4SNR957M964DVbannOhnrxPU11bWsB7V0q5Bp5mHSYON1Tslwa0VR7JsL\ +IDSQdGvldj66GGEfu7TJGrIEypKAOF83iFW72NuIrkN9qBw4XAC7Bpe8F2gkpHqCRCq+BYktD4BSnNglERLh6QiAVdwqa9J1LlwS\ +G+Kkgr0wr8uTKX7IV6XCc1Y0ngC9e4sT019+LmolLUg2v/pLw9BX90BjRyopV5oo4sywEs0pQ+2814fbBqvhRLpMKSOh5mcKr0fK\ +eStOGl2varQ6xV3g7x4ZYxnQBy/XYTBDuHhEzpGDEMk/iH6xOlvYleeUW2XgeFzDQk6B+tlkbXeCvmGZB+u+cIYG5QbT4Ro/e2Tq\ +LbCjXs2WfpIKoO466vBipuVmabca+yZ8Hdb+3dAlAq857JM8uEbZ79cWmb7pf9kPJEOrZfJobWD9YtgkTFihDbkgc2gpVYITwI0r\ +dFkk/V+NGcNon/8hMVUW51vTw93bIR74YyhCMMdei7z43ReARvAn1hPRzCJLKDPO1Pg9+WzufeGlqCko5wM5sr/xNCADeaLu7ont\ +4mRk6qSRHew4oVsQaoNkxiR4OupMSyXg7QQCfuShv30GFKileLpdXPAs3k72PtAjBEax5H58Mewnz6VOsYV26+ASBeTazwXwC8mu\ +4VxlEwy0k26/WoYxJTAjBgkqhkiG9w0BCRUxFgQUhUMgqmwr3KcLWUAOClMasbTgADMwOTAhMAkGBSsOAwIaBQAEFAc6BlZhfHcR\ +gqNVb4hRy9Y/isasBBAmnrhSYOIWt0AqY73UNFmQAgIIAA=="; + +const NO_MAC: &str = "\ +MIIJnQIBAzCCCZYGCSqGSIb3DQEHAaCCCYcEggmDMIIJfzCCA+sGCSqGSIb3DQEHAaCCA9wEggPYMIID1DCCA9AGCyqGSIb3DQEM\ +CgEDoIIDmDCCA5QGCiqGSIb3DQEJFgGgggOEBIIDgDCCA3wwggJkoAMCAQICEwWY7mm9ZFkbsOorJB5uhnxOV64wDQYJKoZIhvcN\ +AQELBQAwLDEYMBYGA1UEAwwPRXhhbXBsZSBUZXN0IENBMRAwDgYDVQQKDAdFeGFtcGxlMCAXDTI2MTExMDIzNTczNFoYDzIxMjYx\ +MDE3MjM1NzM0WjA6MRYwFAYDVQQDDA1BbGljZSBFeGFtcGxlMSAwHgYJKoZIhvcNAQkBFhFhbGljZUBleGFtcGxlLm9yZzCCASIw\ +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMUK1lXyl11Wa8nm/71zx548b0LNAi/mAN4gqxEV1ykHT2rpfmLHOBe/9jzNtib4\ +xFOq6GyQEI5uhyRitnwsv2cyQ6Q4BMdXzlGd7kXhhX0CUnG/a54A99qu1Kwwn5bsxvv1viA0FtwENk/RZQfAAZIof5MlZxTmUimR\ +74/wfpSplA2tVr1l27JYkTlcwEE75oTGHngMVcL+somdViVwL8W8g0XmrSR+guSF4lLadxE1dIv0kiW5hNIU5eTcj/5X/SkGDgvt\ +u7K8sXGk5czTLgPdIztVhWNJUgBF7DW8IvI9bFuHBIqe+ua2vWNPDCnHvHarblzP8I8K5+9DUqdx1uMCAwEAAaOBhjCBgzAcBgNV\ +HREEFTATgRFhbGljZUBleGFtcGxlLm9yZzAOBgNVHQ8BAf8EBAMCBaAwEwYDVR0lBAwwCgYIKwYBBQUHAwQwHQYDVR0OBBYEFM4K\ +BwgbSCFFH9KVBBwDlUFEN6DkMB8GA1UdIwQYMBaAFANXYErplgDksqE9CKJD3y1Ia/smMA0GCSqGSIb3DQEBCwUAA4IBAQB4ZaoH\ +YTiXV8YNiQDcC80L113hM18buMihpyRvWYvfa6IRebJhJDV09KmI1hDP1x8sp0eaMxrDeLIZZHs5gD5I6kdUmIsWGtE4Igo5UmJU\ +PrcYjcuE7VtmQ9tzwTBgFL4scwkfZbAa43+fZe/BqndyMs2CMxAKcMV7jzw/LbrLEI6BP0MXqQ/B9wj0VcwV0prs9MxlYDbTbS0F\ +r+A+tX+0VRE39IFKo59Xs7t/9IodTBpMxIWhVZ7Ukbh8NyhE2NRM/y6czTPsO9FCC/zPF2U523812v+fkc0CnGS62kEujmRD6VTl\ +P1eHQ049OEjzCU/WHYdL9VFFoWswb87G+Ae4MSUwIwYJKoZIhvcNAQkVMRYEFIVDIKpsK9ynC1lADgpTGrG04AAzMIIFjAYJKoZI\ +hvcNAQcBoIIFfQSCBXkwggV1MIIFcQYLKoZIhvcNAQwKAQKgggU5MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQ\ +plQrIjqtb1mmwuPxoJsREAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEECBNQ0E9PNp4Ldl4bt+M5zUEggTQAAIoW4KR\ +EhQManAkJRk+Qd7hNcuwIuKNAWevxRC/6fNNgWt3Sxn3dLs/NTuv29nSk9FSlnGMV8v6PyuRKWHPnlobZdQqJI+SRNsyAD1uRpFE\ +0t8bhpLbR+qiIuyiRNhujUnCyccs3PgQnbMnCgKYkL75Bnd0edHCRvtxu65T8cdaQZhpXqLJWwRi8lTT/xiN3Kn3krJ1J+6vnI73\ +WUQIK3PtQrGzpW+gHOeburYFHiYSDfUy1GF758R7Di//fsvd68i2RGNqFPygi3OU0uBu3eYlv0GwlbWHTRYc6dLTcalnHH0XKcBp\ +RElCVLl/phAmSiXAre4NvPkLCNlS8xfhhfOYr5bX1a9CE6TWxU4C0S6i4e1q7X7d78mD7boH2/SJ0VbufJJOoHfScReUgi3P5WKp\ +0lKvO0mPc/hlTvyq9oiYDLk0Gi0v26t7+prbuWkkAcD1HtQLwGIZjq3HyRcBT2hwx9B6VM0VS/4uSsxr6XwP2fvCI8tDLokBw+Ts\ +EAQbLR6Ozjz0eYuKnrnC4+/Pjn7TX1JvDGISZAbKNVsI6RrL/iZUbushmso78I/bg8cENE7ipGwTwYGMiZZ5+9oMKvymkowpOBr/\ +u78hppuWcJMCmty/5EtoEDVhImb6hPwJ7dY4k5ZEHl2tsweOgSEmlkzxh+dMPQPeYMc/+2VcxysDxNjW5jiaBbXVWS6XgKc/VJGu\ +29JHTN4KYdoQorWUuMBNAt0vLF+pJb/3KtgfHpZ4i6cJ28skain5RTSjXiL+RY1Q4zyKJgqgrCyMRvgXXUviEtjLIUrNdKsgPVP5\ +iV0vGkFB7/DNGn88DzEqoEGczdarU1dEsHN334swHGF6ZGdYXTfxeQu1rx5tgo1ObXcrrHYAmi6/3vufK1p/WMH2t+VzdJtR8Bjz\ +LxbCiEeaXAw8ZW3g9tClnYwdizcSq2tfmLBqhD57ydAjBjOKj8m3XwqPtk8rzedyZF9NDXPq7kqHIWX+RAtpyd/7HWHz44uj7fae\ +kYPyy1KsxMd+LlKc4BIHPmCnZ5Lk/uSvEVH9VuNoj87OQwHSdXTEQl5EA1kjeXXi7qA0OulEyVgiYwmIL8xwGDpRunC59TxYWFQU\ +KPA56IhG7jHq9owAMws5bv3XwpZAevik2RqBMoqitKSJiNUWeQZ3ILXVpvqjW6GNrFg9GRHqO3/bA3LIziboCohWLasMXywIhyaY\ +WnePvvvKouwkhLHjK5VJj71KHY3T91ULhmI/iDx0PdUgdcTH+pAX/Ogj6YG+vxnEUg1V/hZLsW5hFavvenj0iEzc+6qJyvKFpjBu\ +Rk/FBwebzYB/UJ016t9hDqyk27pnEbn8DHmsS4zCQ2IQHV0iiI1CVZALVf0yaZ4NDE/bkLBIiCUajUImzFvq/8YWYHN0RwbbtG/V\ +KJzAOHrot7pQlJy2cJyELhdbuNuPwEB/S86OwEsDIU4Ku5hF/c+WUdNKm646DsZM28EZlcq9jR+mK2x/prErV0jZcHrWaEF+n6FK\ +yEc1u/4obH2RCOK7mKQQIuTOc3JhEOcYAFjClm2OtcSanUccDT+yIBwiDkhLteXMH/GZ4VF0AXHWWD8uGZviUq5wunG9QVtlUQDz\ +Uvr4Oob6RK80S2zz3PCqwquX/vyuTIppXoYxJTAjBgkqhkiG9w0BCRUxFgQUhUMgqmwr3KcLWUAOClMasbTgADM="; + +const EC: &str = "\ +MIIE1AIBAzCCBGIGCSqGSIb3DQEHAaCCBFMEggRPMIIESzCCAvoGCSqGSIb3DQEHAaCCAusEggLnMIIC4zCCAt8GCyqGSIb3DQEM\ +CgEDoIICpzCCAqMGCiqGSIb3DQEJFgGgggKTBIICjzCCAoswggFzoAMCAQICEwWY7mm9ZFkbsOorJB5uhnxOV68wDQYJKoZIhvcN\ +AQELBQAwLDEYMBYGA1UEAwwPRXhhbXBsZSBUZXN0IENBMRAwDgYDVQQKDAdFeGFtcGxlMCAXDTI2MTExMDIzNTczNFoYDzIxMjYx\ +MDE3MjM1NzM0WjAWMRQwEgYDVQQDDAtCb2IgRXhhbXBsZTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABFTBl+in37wcV2KoZBpe\ +8HdIa3I67Y9fM249azdt06A2enfiMt60EGb1OYAn6qD/7HBmfSt++w736js0fPFRj6CjgYQwgYEwGgYDVR0RBBMwEYEPYm9iQGV4\ +YW1wbGUub3JnMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDBDAdBgNVHQ4EFgQUDX/llMpNqwOzpdvg6ZW6gpow\ +7jkwHwYDVR0jBBgwFoAUA1dgSumWAOSyoT0IokPfLUhr+yYwDQYJKoZIhvcNAQELBQADggEBABUyJYbCAXO4DRftivaELtGfecBe\ +lAyblNSgoObqXGpjfDbP4GR628maNzFSCSNpT9GaBtY2nsHyqwbTBbrZcrbXrE8IXhyF+QfXW4KjQXd4zl/VDL79lv997I2ocl/G\ +RYq8jMPO22zCDkzJW/ihqgTw77YfuJy3TRG1KFDCYpt+N8jy+ua7E8nVCcjAUIGdyoEZFJmvznih0qh/gAZrHH1JF3dvgmml3R1E\ +DBY8ZueV7uMWcBGHKwc4x+qd8zhyfvKibwl5Xd/NhtBqclmgKTR2IoZA4tojridkfdzmnrB2acqkp/AEByd9E8axNymFFExtlSrE\ +N3rxIi94y3IQXgcxJTAjBgkqhkiG9w0BCRUxFgQUjInlR11rxzqXIkizr2OoL11D9JIwggFJBgkqhkiG9w0BBwGgggE6BIIBNjCC\ +ATIwggEuBgsqhkiG9w0BDAoBAqCB9zCB9DBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQqWdl82FHAGkVnnehJZkd3wIC\ +CAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEAQIEEJgmrQYD1UonngDfy0Jb2UUEgZA+uRWJCzYL7FxB1NaX04qn17h2kOUbLwAT\ +MC2Qj28y4C1jXfvwP2/jJ66n1CYMQ5jrOyp7b2kn1CF3jYyfvUcuy1eRX5re20d3MO3BvVyJLACAwfNrG3XQhPBiqhi238zukWbC\ +Ub4PuKJIQ/w7Ro4e77aBGzhH1WN2okRbfbKJNwGO8+oD40su43K6/Pyg2ssxJTAjBgkqhkiG9w0BCRUxFgQUjInlR11rxzqXIkiz\ +r2OoL11D9JIwaTBRMA0GCWCGSAFlAwQCAwUABEB4m6CI+/V15b2q/hZZfc/EPIUaI48ZKAFYhEF3kRVR2NvgJt69KYUM0148qW+S\ +ddMTgHUukfMFkYfvSNHlPoByBBCW3D8EXEwst+W0w1AVuNT1AgIIAA=="; + +const EMPTY: &str = "\ +MIIKZwIBAzCCChUGCSqGSIb3DQEHAaCCCgYEggoCMIIJ/jCCBGoGCSqGSIb3DQEHBqCCBFswggRXAgEAMIIEUAYJKoZIhvcNAQcB\ +MF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBDF87jePepeWTUT3j7S2+0SAgIIADAMBggqhkiG9w0CCQUAMB0GCWCGSAFl\ +AwQBKgQQMtr209mOOryP12JAnbtuGoCCA+ByOsav2ReVfVr96Z8DrUpT7Yk491/QW8XjxxzhgZjZ8Vomefv54s/bqm7gd3q9ygOl\ +VMeA0zyOAvdnjFcy65fdJgAsjfj7p8rR46PWk8LsbV5OGgaueG+hDuNNwydEswqCrAN6E66X3X4zADJTzTLU85bbFdMGmdZ86Oly\ +T4eXoQOO9Fc4Sxl6CDMYsSqXft1bdl9byBazMjSpZuvKu+B4OwJx/u7g8f88QoMzRwnai82y/Dn9+aqg4cPq9deK308Yaq7Q4hML\ +uNHfpwUYjbULLBSq4NAzh0brm0vhjcFGJdjKi/S1KkiSFG7+xCzTPU9SFJ7AU/hti1Pe7ibP37dFm4IiYYylkiwNAPQs3q/P6sBc\ +rBYOT6Dyg2e8sQlXvaLp3B/cOheP6vU2k6WbM/2RePREH4Amx2qVdrXvNEM+i1TXMZXdurelNAS7DaG0gyGhmwzeyxApH4QqwNdv\ +DkgkW+sUONsxgJntlBNKEOyiRxi1YYCCFPgtbRucQ6lUSUjnzRr6HiuYApEk71aW/PZAMVhGKnJuoye2K59abhCyH8kxdz/umFzd\ +PNOm5Bjf8oOTtrmYP7JpPcVrDbYOUtJnzhPZEcg+SE9p1gt/lx6GjvqE8+/tZKgSNtd99xFNMat32Qbn8HG75vu0xcq8aVrN17qJ\ +fn68gd2UfGDsNfNwVcIWlTxsMlWHDfCL4QN3af4oFG1phxdMGlID7ALLcnC5VHc2fBaxH4DXTP2mriGGR0NMoZaZTqwyk16gbW5S\ +5bK4AvANC+ej9+PjEEYoHCi5T5Pad7HhkRUHyyrqN/jc+idS8JIzQoSwIH6+PGaDjofhaxr7LtKODmQ3nIAcUMs7n5BqPdcC318H\ +G9NqJ6zvAsbImrWVVYUkGhvA4T3qFqZqUgEzCf0NmTpyb0FHkGwSsmHlMdqr/DhicpBE3TU8Z8NJZOyYplaVRqOc3dRIGuzLqg/1\ +32+qblfFnE/9XidGQepwCMumitELsptymiU1FwdRfLSQjIf6DVbHAy/37RtttDHTrHTK2W8EqCiSSCSHZ4G+ORgTt5jZAn4VQbnC\ +BdtBwky2Cf/afKJYTgmV8He2KJ2DTzRX2APCQ4WRxu5wgnXA+aB/RwJyaXW653X0zh34tuaWTgikN8fJaeqTXq1cSc++vyDGVCpN\ +V5igIWfeNi7bUab6+BaBLxyJ0pIlJtGE5CuVf1bS8vx9/NcA+lyLNKuRNZAC5roLuF+ZcoviCjiVqhVpi6vMo3LjGKxZ+Pc8zl+w\ +G4W28K7Af2ZifdxR9H+5Rqa0ZiGFJOaS7akFeWHuMIML0ghkLrp0C1oG1jCCBYwGCSqGSIb3DQEHAaCCBX0EggV5MIIFdTCCBXEG\ +CyqGSIb3DQEMCgECoIIFOTCCBTUwXwYJKoZIhvcNAQUNMFIwMQYJKoZIhvcNAQUMMCQEEBwwyhmnKSJx/KzrtErA4x0CAggAMAwG\ +CCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBDf4dc8FXT+aYODSe2aT2gyBIIE0PsozHos8DialF+NaxO4hOL1U8n9PytgmrFH7MmM\ +HMVc3ScUVcgyC94+ZQjBJ3JWOjDo/2k+aH4c3V2k85+mXutBQU+idGNz8gh1DjHKWri8oX6SaogwG0dIVTpgAkeSVApXI1Tdzb7d\ +wxazLFIlFveL2bRGMGPpspMLgF+079AsL8phJ+EtI7G8kONL+406KYqIBr0nsqXravDIIFppB1pX83UqsBEs5Mxgkqh2P/Z9PXyQ\ +1zBCTofzXnwDISsM9WgVZfLyOSchUaO+LXnfxNAsSzm40nBn6N/s3k//JYWzyGQHIK0i/0C09J8AbiS2sGQd2tdDoEYofqECeMRl\ +JdjTv0wmJUMJldjSStDKWVNPTGBiGElWaNmDfhJrTXqIcVvoQRJZHvjCTqaYNqj12Oise2Y4p+u39U7NIVr3P1NoxdV3btaKUczd\ +MtqML1dHQJ5/0KlZBR9KINVNu7XpQpcgEu/KaGEIn6JILvQs5ISjKNmahNsfoCpUGtfV3xF3JzwRYrT9dzL7mr9Mv3s7ArZ34n3m\ +AqrGBGX6gQieMzYAtEJqUxtoNDck3SUNlgbWGs6Z9LHLrnMcCxN+k9xeanj2xnfaXNzCEcjzECvFHSr+RTCR6J+3sLj8QcAN0Pel\ +BjJICGrNHyyo4SqbixYYYe3iRpKFedTEC8ydoVmmeR7MtpSNg9K7a9fbd8cRwb/xCbi2u5t3/kFKy4UAeGVme0Tq95gvGai4/5nV\ +WkjzyXT1BPrnUIszrp0UNTs8MP6oJ1ndvKD4odlAdpQU0Ctl/eqQ+om7kqmWkSFIjUrex+YUv03euMsmUIqu6CpgCCcPV+SKHmU3\ +LPnrGH+oVYU7bPYQJcPfvL0lgcWeDiTp7AHOTB/qxEQ0OgjFc+JjNrmDwhV8qgjvAHtXRJHhRseBEWJs61IHtZ0JMvap53WfIKEn\ +IF0EihMfU1G3ht01uH4mBbUelfItlS9NGrMT+fXIy/qCB8a00doLv6b2xx2s+TBj1F1tXRe47ozNtWKxmTQw3gFhHoXXdRFX+XNa\ +5H+Qm6uGagZp58JQ0ybeit3p1Ck0TO1jYRPeLW1CW06kHCHFsvoYebhGtd9WqNk9KygjVU2h9aCg+Z+8c+mZ3nqxHs0VPMMNGrGE\ +TyUS4TechVigtVMJmj/cJA1Mme4eVyl7W2bdSvZntX+y9VTFMAJk8IHyxN6gOwvHgh/YfmvZQw/6ziL4BwEDcSVzJIGBW6X6PxcN\ +4gQ5kZhfshXwUIEKRebtmo3fTKn8D2WhUVbu3nge1I2G46ol+F2eZMtQisgjbAAxbGLr5Slz4SxijMrVgo8QHXXQhwWU2eeyCrTF\ +PKBUVHQG9CzNGRHsMmEmYk6WTyozR5ma2epCTYRPhR8fUxHxdjDuc/5qEWjPBg8m0FPCo0KbIYuhpZQTl52QRH+0mMs61kQsadow\ +bGTs+NMLOk10piUoMTDjz7A5vJwI5cS4WYmWALpIOXCVwSMLs97yJDOmFj/gFx+vbyn6W9rciQljO93vnpt7BvSUG7RQNufkePDZ\ +3VazbEmFWY0kvdOJDCeUF+AfqiOde94mOY5MNQx377q2yuBH4RNTGgY99r7/dJVd1/okNuLtK9wulLxqnZuV/iUDoF/egG4Egisd\ +Z+MXMSUwIwYJKoZIhvcNAQkVMRYEFIVDIKpsK9ynC1lADgpTGrG04AAzMEkwMTANBglghkgBZQMEAgEFAAQgcAZkx5WYR7XZrovc\ +Pgmgw0IuEAIj4FjBS78Zv6IAsScEEIk50Yy2OM0LI60aLfWObdcCAggA"; + +const SLOW: &str = "\ +MIIKagIBAzCCChcGCSqGSIb3DQEHAaCCCggEggoEMIIKADCCBGsGCSqGSIb3DQEHBqCCBFwwggRYAgEAMIIEUQYJKoZIhvcNAQcB\ +MGAGCSqGSIb3DQEFDTBTMDIGCSqGSIb3DQEFDDAlBBB8ks0TJ1AMoB0niaJzWOWJAgMehIAwDAYIKoZIhvcNAgkFADAdBglghkgB\ +ZQMEASoEEIQXlt2LpA9dPLJrIQbhjeCAggPgg1hhBenojqTc4iWsTMD37yvBa3dFNQUUB/y9ZLKMbyTRIorQx2API8WUpRqTQJHi\ +ad8BJgN8eUzaOFQtfpeCqeq8g/el9aJ/wiVDdyPWn8bEIa7bKSZUvC5Ei4qun29hHuf0GsEf38TjUz+Vwv+d/VxAnlNQrANGnZ6U\ +qNU1VQSNPhllyJnJGKhOkiCyv+7zn8518laLYcTj+Q6dGl1dINstFS+ve8BFmYv9236f6TNpDPu4n94CyUit2N6Hqg0LAVW6I0ct\ +MXoo6+7x3n0YgRzHNqo7XjfiRY96g2xb3lUJWCaHN1deVgJ1loGLrZZY1AYlWLtvUENZKC+Kwd6YpZbPydB27OApQc2sVkJYjp8T\ +9GDZ86fdIkNlfrKint59TniWPI7IPvXww27v2SHl828ADvaTR2XcS82QOqqq5INMYYRN9Kg4rjzwV1oWmDWywh8vD7cEIbbXzsBj\ +UexF5kzrjpe+j5/VYdA1VYNaERd0RlJqSXuyVxlvCvPziLzeADOoPT1lbVuloxaRNHTkr68hedHXh9Qju2YNUo+P7IbS4HXC6Nh1\ +m+8bjrRzVlA/MsLBhuxkwDv58z7n2B4iLJpu93/ZkxxyMPJI5cMg6ikeNLTmFj7vTxSb8uj31L73CySnXSlhi1CkKHCeofM6cKP+\ +DgUh5f9Axl91e+MOaNpxxZ6rxVaYMmtuzruDeABCRp2AxdA9eo5J2ReC6eHwNwDwVaECI8V1/tfdzdTTbbOD1YuaQ5z2mQgUx+C1\ +mqfVXJgWTnkUgNuwoFgOUJGQfAWuOjcZIaXx7slg9r7xQwitHnc1pn8Lj1ZB5l1ixHxn09wZCoLGhYbgR0fPEp/VQY/RlQZifxnF\ +Nc9LP6U/+qq+VbRmJ+wn7D3vcJ5/IMfOwrzYHBE2PaJLizpMR83W4dPVcOBLyogMowjkPoMFgnDzDOdlxi4Q1yaobzsS6VvnuD4Q\ +R1ehKNDG/x97CzgsFiovUW8KZkXacq0GtOUC8nuUI3O9d+HqBAPejfuq5A51r2pmn005DUCim9AEXYMxibVVqQ/qq2j9YkbRZ0gL\ +7XPiI2fxgR5B8IoZ/vbIopoy5BNhzVMRTGxLSOLLg3Y9gpdxojWS6Vg7Y2rD10UhbjIaMXMnXm2jOQ8Wv3NE5WfHotkpDV1MEEiH\ +xKn0pFByBi+WGIz/fjb6+DZtQ1JqHZZxMTSSOQcC8Ctv+Nlyi8MOxgMXKmuppKFiQxfZxgs/BRGsSY26HlohzkajQSb8nvsnx4er\ +xStV6ylCfQN1miQu1WmBWMa55v2b6YPfq3COIMVWqp/M9vlcdULkgHj23uUwggWNBgkqhkiG9w0BBwGgggV+BIIFejCCBXYwggVy\ +BgsqhkiG9w0BDAoBAqCCBTowggU2MGAGCSqGSIb3DQEFDTBTMDIGCSqGSIb3DQEFDDAlBBAchZc1zQburwsAUAl9cukPAgMehIAw\ +DAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEG6e5jeQsIVVfYE1Xo/vFtEEggTQpHmb8WWB5X0x2w9LAUs2s9HJD6Sn+TXkOLAg\ +Kgar2eH64/QfaaLyapDTTU5utuJlLYLuse5MmqD2Z6/rzTSNkDidMqhWaORB1AJYuz75BU8l13E8B9oLbgnGeo93XAtAyD+sTQ8M\ +kjc+LyDWgakOLYPLXGO9gPWdMc7qrn2PS8LRpjR7i3TPIJRmIwAiddGr0dZW8uEJke7jFTGkDdyGkR0VF6EeHhYPKQBTVdtqN7wI\ +BugMxrqNbrQjpiZezs91HGcvQK7POy6FGkYtmvjgQuNOO4NEbtXNCG4V8XTud/PgO3i5OEQRioj9TaNWclgTsn5R6hNoULijFYJw\ +jOKAa9MqquQvYoKXE3YlW0AccgpiHBF465DO+TO36vc2Ocy58oCIzwxObK34nbNnHpmQ4fwXtf2u1a43FUROd5d2RN0gCOUrmqdK\ +uPMYABQLgqFtYxKtaNrTBt0sMjdhksW6ttREJiudv8P5Zgo8Lzjrjwp8PSO05Dux5IxOOgnRlG9nl34PysHl5domXrNfs54/iesS\ +f3WakBTSEs5Of4itSRub9cpkMWYlBJ1TmliNBJHibytBQTgGiw2nPIzGlSMDkMQ8TZGBt2LCW8KBKc/4gJHi+AEOS8p5mIk+9DTv\ +Vm1l+i8ljwELfWkFVeHZZ0MKnd4lJY743H4KKvZMT+zMw0OKg7c5Oag9QfXNyBKh2QmgimnM/5Zu1f6DDju0QqCSDov/1nPJ3tdj\ +imCzIh3UxvuM9crzic4qtsQMQz0tNPqZJ2id/icRv4cGNepKUawoS+AcpKDzuMaqAOFWMbSt7WRHONdLbyylZioZQlXu/TaA9Hcm\ +1JItzMDxFh4ZqW9D7MJPs50Zn/aRK3xV5ADuAKCg26WSt+9svgrZS3sG6bF2dVE8M6tV8qz6ljkRRiP5a5YfpmffP/mA//FuKsPH\ +8JoIURm0jLzDF2Cyj2Xk/0HJFSDkbfI4W5O6Fe62QA6hTDlOJjd7eGSCV52u3OUTNK13qMFr8ZdaGfdpMKxt2x7WEufoWbju7TtM\ +4a4bM0AoN2ob2iziC16E0GZQtqVy4is5U/yUs/nLkA1rGdvwwcubIiTaGuI4cmVeVnMqBEp6TFH6WOYSadWmfN2RzMe5gDNFGMJb\ +AUgA9xdwzKRO7C/9fox4PQ2EnVvX1NwzcexeuTE15c0ry3/N9J2CnCmaVZFHyicQYaTOKGPi4bX1ZGSblJwHoJPS+Wm8rfYBXwK6\ +hjmz1SKSt0Eh0e8oKwuM8RwJnAN13lScGT0AD668PaOgzSK3WfMDSJMRJhvzTRmpHc4/eOIa8MbG8rkNm434k7E/jujaWbMAAWCv\ +w2UnOzqmba9buKNE62tSffWE+45pO/9grKFk/X7r6W2U3ECc66iV+NcP+4oLLX4x/w3Oi62M0PaWilWgVgpMZCur3tUb1O9eap8y\ +kToB2qBP0mgYlKbwjka3i1eHoPt472W0+D/ov7PqOt+ZbQqZLFCmXh7MhvNf0K2HrycL7iSb1SSENg3AjLDzbKwQk0cjm4Y37l5x\ +JzLgdnICu18j20yHZzPn7iNUMhQZGn/miKChpNbjOfn5eOdxfHb2tuNhGXUxcIFPHc+llSAae5dNQOx9jdJGIa/FSoZogWVweM8L\ +70AvjLgxJTAjBgkqhkiG9w0BCRUxFgQUhUMgqmwr3KcLWUAOClMasbTgADMwSjAxMA0GCWCGSAFlAwQCAQUABCBSwdTuQqfx6oMN\ +oRpM+476CU35vPBZAg7uDRQ2W0rxuwQQlBfL7bD0DVRjC7ff7DCBfgIDHoSA"; + +pub(crate) const ALICE_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIDfDCCAmSgAwIBAgITBZjuab1kWRuw6iskHm6GfE5XrjANBgkqhkiG9w0BAQsF\nADAsMRgwFgYDVQQDDA9FeGFtcGxlIFRlc3QgQ0ExEDAOBgNVBAoMB0V4YW1wbGUw\nIBcNMjYxMTEwMjM1NzM0WhgPMjEyNjEwMTcyMzU3MzRaMDoxFjAUBgNVBAMMDUFs\naWNlIEV4YW1wbGUxIDAeBgkqhkiG9w0BCQEWEWFsaWNlQGV4YW1wbGUub3JnMIIB\nIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxQrWVfKXXVZryeb/vXPHnjxv\nQs0CL+YA3iCrERXXKQdPaul+Ysc4F7/2PM22JvjEU6robJAQjm6HJGK2fCy/ZzJD\npDgEx1fOUZ3uReGFfQJScb9rngD32q7UrDCfluzG+/W+IDQW3AQ2T9FlB8ABkih/\nkyVnFOZSKZHvj/B+lKmUDa1WvWXbsliROVzAQTvmhMYeeAxVwv6yiZ1WJXAvxbyD\nReatJH6C5IXiUtp3ETV0i/SSJbmE0hTl5NyP/lf9KQYOC+27sryxcaTlzNMuA90j\nO1WFY0lSAEXsNbwi8j1sW4cEip765ra9Y08MKce8dqtuXM/wjwrn70NSp3HW4wID\nAQABo4GGMIGDMBwGA1UdEQQVMBOBEWFsaWNlQGV4YW1wbGUub3JnMA4GA1UdDwEB\n/wQEAwIFoDATBgNVHSUEDDAKBggrBgEFBQcDBDAdBgNVHQ4EFgQUzgoHCBtIIUUf\n0pUEHAOVQUQ3oOQwHwYDVR0jBBgwFoAUA1dgSumWAOSyoT0IokPfLUhr+yYwDQYJ\nKoZIhvcNAQELBQADggEBAHhlqgdhOJdXxg2JANwLzQvXXeEzXxu4yKGnJG9Zi99r\nohF5smEkNXT0qYjWEM/XHyynR5ozGsN4shlkezmAPkjqR1SYixYa0TgiCjlSYlQ+\ntxiNy4TtW2ZD23PBMGAUvixzCR9lsBrjf59l78Gqd3IyzYIzEApwxXuPPD8tussQ\njoE/QxepD8H3CPRVzBXSmuz0zGVgNtNtLQWv4D61f7RVETf0gUqjn1ezu3/0ih1M\nGkzEhaFVntSRuHw3KETY1Ez/LpzNM+w70UIL/M8XZTnbfzXa/5+RzQKcZLraQS6O\nZEPpVOU/V4dDTj04SPMJT9Ydh0v1UUWhazBvzsb4B7g=\n-----END CERTIFICATE-----\n"; + +pub(crate) const CA_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIDSzCCAjOgAwIBAgIUQiksTfPBn790EMSMwNs3Jn0jaiUwDQYJKoZIhvcNAQEL\nBQAwLDEYMBYGA1UEAwwPRXhhbXBsZSBUZXN0IENBMRAwDgYDVQQKDAdFeGFtcGxl\nMCAXDTI2MTExMDIzNTczNFoYDzIxMjYxMDE3MjM1NzM0WjAsMRgwFgYDVQQDDA9F\neGFtcGxlIFRlc3QgQ0ExEDAOBgNVBAoMB0V4YW1wbGUwggEiMA0GCSqGSIb3DQEB\nAQUAA4IBDwAwggEKAoIBAQCLZYmAht/KhFBvK9uNCHWCQ0viLErOUqeX1aXmT1gD\nK7pnO17kenetbfhEY1tBB8bvhkLYcW+A10RZslY/ZMJsf8PTHA+B+gZB5GdIDtAC\nASHTmiBJIr9bdJiD+eZ1hDNfSvXm2dlF7qEnaaUj+GoowKnyqkGQ4EbfFcVT1rJR\n09Gx1yu1Ti5gKG4/BoAZ9Q/Ho/TGKXhCOLbecWzFzFHMbwLU+oY5rVjibp/FVbwT\nC54cuuqmwS1z+t/ABBvIUv5cVZloWXcoe1Sw2KSN7IaGGM3ziCSDBM6RZiUsD/Fr\n6CkW5m2c+XPOSTwfHPz8h39bCITS0DbB86fXDy7kZQTTAgMBAAGjYzBhMB0GA1Ud\nDgQWBBQDV2BK6ZYA5LKhPQiiQ98tSGv7JjAfBgNVHSMEGDAWgBQDV2BK6ZYA5LKh\nPQiiQ98tSGv7JjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkq\nhkiG9w0BAQsFAAOCAQEAaT1BKjztiC5bgQ3hT0zRsqSLXlzGGRYAMC49eLPAAPvO\n6CL+ZPvNByZKTRy6pt+Tr06nbj7YH92z4xO601vILQBmBwwhsQNMotKDZ/Qedb8t\ng6maxc83l5rKOR/XHze6nIoFQR1uYWrvLT/JpwTZ9SfDk5pbMVCRyExACSAQL3NF\nS1boSb2RndOIHAcwKUF7uEYm+uoMbttCFcFZTcNcO1swL43/562cJ8w2AWwCBv4j\nz0Kcna6idZx/eTZxkHizZwMGzJL9Hzbvui0gPBu0RNAbBUTeJawC/1IOEFQq43Fj\nMxttmH5D5Ax3nffhFlrAH2IgjiHTI+IbzIzNR1J0Xw==\n-----END CERTIFICATE-----\n"; + +#[test] +fn matching_local_id_cannot_override_a_different_public_key() { + // Both are 2048-bit RSA, but the CA certificate does not belong to Alice's key. + let key = rsa_key(); + let alice = der(ALICE_PEM); + let other = der(CA_PEM); + let alice_key = crate::cert::Cert::from_der(&alice).unwrap(); + let other_key = crate::cert::Cert::from_der(&other).unwrap(); + assert_eq!(crate::algorithms::key_kind(alice_key.public_key()), crate::algorithms::key_kind(other_key.public_key())); + assert_ne!(alice_key.public_key(), other_key.public_key()); + assert!(open(&plain_p12(&key, &alice, b"same-id"), PASS).is_ok()); + assert_eq!(open(&plain_p12(&key, &other, b"same-id"), PASS).err(), Some(Error::NoCertificate)); +} + +#[test] +fn ec_key_pairing_is_derived_not_claimed_by_metadata() { + for algorithm in [&rcgen::PKCS_ECDSA_P256_SHA256, &rcgen::PKCS_ECDSA_P384_SHA384] { + let key = rcgen::KeyPair::generate_for(algorithm).unwrap(); + let other = rcgen::KeyPair::generate_for(algorithm).unwrap(); + let params = rcgen::CertificateParams::new(vec!["example.org".into()]).unwrap(); + let certificate = params.self_signed(&key).unwrap(); + let wrong = params.self_signed(&other).unwrap(); + let pkcs8 = key.serialize_der(); + let (info, _) = craft_ber::read(&pkcs8).unwrap(); + let fields = craft_ber::children(info.value).unwrap(); + let (inner, _) = craft_ber::read(fields[2].value).unwrap(); + let parts = craft_ber::children(inner.value).unwrap(); + let without_point: Vec<Vec<u8>> = parts.iter().filter(|p| p.tag != 0xa1).map(|p| p.whole.to_vec()).collect(); + let omitted = seq(&[fields[0].whole.to_vec(), fields[1].whole.to_vec(), tlv(0x04, &seq(&without_point))]); + assert!(open(&plain_p12(&omitted, certificate.der(), b"same-id"), PASS).is_ok()); + assert_eq!(open(&plain_p12(&omitted, wrong.der(), b"same-id"), PASS).err(), Some(Error::NoCertificate)); + + let other_der = other.serialize_der(); + let (other_info, _) = craft_ber::read(&other_der).unwrap(); + let other_fields = craft_ber::children(other_info.value).unwrap(); + let (other_inner, _) = craft_ber::read(other_fields[2].value).unwrap(); + let other_parts = craft_ber::children(other_inner.value).unwrap(); + let point = other_parts.iter().find(|p| p.tag == 0xa1).unwrap(); + let mut forged_parts = without_point; + forged_parts.push(point.whole.to_vec()); + let forged = seq(&[fields[0].whole.to_vec(), fields[1].whole.to_vec(), tlv(0x04, &seq(&forged_parts))]); + assert_eq!(open(&plain_p12(&forged, wrong.der(), b"same-id"), PASS).err(), Some(Error::NoCertificate)); + } +} + +#[test] +fn legacy_decryption_uses_the_empty_password_representation_verified_by_the_mac() { + use aes::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7}; + use hmac::{KeyInit, Mac}; + use pkcs12::kdf::{Pkcs12KeyType, derive_key}; + let salt = b"empty password fixture salt"; + let key = rsa_key(); + let certificate = der(ALICE_PEM); + for password in [b"".as_slice(), &[0, 0][..]] { + for encrypt_safe in [false, true] { + let encrypt = |plain: &[u8]| { + let key = derive_key::<sha1::Sha1>(password, salt, Pkcs12KeyType::EncryptionKey, 2048, 24).unwrap(); + let iv = derive_key::<sha1::Sha1>(password, salt, Pkcs12KeyType::Iv, 2048, 8).unwrap(); + let mut buffer = plain.to_vec(); + buffer.resize(plain.len() + 8, 0); + cbc::Encryptor::<des::TdesEde3>::new_from_slices(&key, &iv) + .unwrap() + .encrypt_padded::<Pkcs7>(&mut buffer, plain.len()) + .unwrap() + .to_vec() + }; + let algorithm = seq(&[oid("1.2.840.113549.1.12.1.3"), seq(&[tlv(0x04, salt), tlv(0x02, &[0x08, 0x00])])]); + let key_bag = if encrypt_safe { + bag("1.2.840.113549.1.12.10.1.1", key.clone(), b"id") + } else { + bag("1.2.840.113549.1.12.10.1.2", seq(&[algorithm.clone(), tlv(0x04, &encrypt(&key))]), b"id") + }; + let cert = seq(&[oid("1.2.840.113549.1.9.22.1"), tlv(0xa0, &tlv(0x04, &certificate))]); + let safe = seq(&[key_bag, bag("1.2.840.113549.1.12.10.1.3", cert, b"id")]); + let data = |content: &[u8]| seq(&[oid("1.2.840.113549.1.7.1"), tlv(0xa0, &tlv(0x04, content))]); + let content = if encrypt_safe { + let encrypted_info = seq(&[oid("1.2.840.113549.1.7.1"), algorithm, tlv(0x80, &encrypt(&safe))]); + seq(&[oid("1.2.840.113549.1.7.6"), tlv(0xa0, &seq(&[tlv(0x02, &[0]), encrypted_info]))]) + } else { + data(&safe) + }; + let auth_safe = seq(&[content]); + let mac_key = derive_key::<sha2::Sha256>(password, salt, Pkcs12KeyType::Mac, 2048, 32).unwrap(); + let mut mac = <hmac::Hmac<sha2::Sha256> as KeyInit>::new_from_slice(&mac_key).unwrap(); + mac.update(&auth_safe); + let digest = mac.finalize().into_bytes(); + let sha256 = seq(&[oid("2.16.840.1.101.3.4.2.1"), vec![0x05, 0]]); + let mac_data = seq(&[seq(&[sha256, tlv(0x04, &digest)]), tlv(0x04, salt), tlv(0x02, &[0x08, 0x00])]); + let p12 = seq(&[tlv(0x02, &[3]), data(&auth_safe), mac_data]); + let opened = open(&p12, "").unwrap(); + assert_eq!(&*opened.private_key, &key); + assert_eq!(opened.certificate, certificate); + assert!(opened.key_encrypted); + assert_eq!(open(&p12, "wrong").err(), Some(Error::WrongPassphrase)); + } + } +} diff --git a/crates/smime/src/tests.rs b/crates/smime/src/tests.rs new file mode 100644 index 000000000..0b9c83948 --- /dev/null +++ b/crates/smime/src/tests.rs @@ -0,0 +1,1104 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Checking S/MIME Digital signatures (#30): fixed vectors signed with RFC 9216's example +//! certificate for Alice (by OpenSSL, `testdata/`), and certificates of example.org authorities +//! and signers made here; and never a panic on any bytes. + +use crate::digital_signature::{Coverage, Verdict, Why}; +use cms::cert::IssuerAndSerialNumber; +use cms::content_info::{CmsVersion, ContentInfo}; +use cms::signed_data::{CertificateSet, EncapsulatedContentInfo, SignedData, SignerIdentifier, SignerInfo, SignerInfos}; +use const_oid::ObjectIdentifier; +use der::asn1::{OctetString, SetOfVec}; +use der::{Any, Decode, Encode}; +use proptest::prelude::*; +use spki::AlgorithmIdentifierOwned; +use x509_cert::Certificate; +use x509_cert::attr::Attribute; + +use crate::{Anchors, Checked, Context, Signed, check}; + +const CA: &[u8] = include_bytes!("../testdata/ca.rsa.der"); +const ALICE: &[u8] = include_bytes!("../testdata/alice.sign.der"); +const DETACHED: &[u8] = include_bytes!("../testdata/detached.eml"); +const OPAQUE: &[u8] = include_bytes!("../testdata/opaque.eml"); +const OPAQUE_BER: &[u8] = include_bytes!("../testdata/opaque-ber.eml"); +const SHA1: &[u8] = include_bytes!("../testdata/sha1.eml"); +const NO_ATTRIBUTES: &[u8] = include_bytes!("../testdata/noattr.eml"); +const PSS: &[u8] = include_bytes!("../testdata/pss.eml"); +const NO_CERTS: &[u8] = include_bytes!("../testdata/nocerts.eml"); + +/// 2026-11-09, within the RFC 9216 certificates' years. +const NOW: i64 = 1_794_182_400; + +fn base64(text: &[u8]) -> Vec<u8> { + const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = Vec::new(); + let (mut acc, mut bits) = (0u32, 0u32); + for c in text { + let Some(v) = ALPHABET.iter().position(|a| a == c) else { continue }; + acc = (acc << 6) | v as u32; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + } + } + out +} + +/// A message's body: what follows its first empty line. +fn body(message: &[u8]) -> &[u8] { + let at = message.windows(4).position(|w| w == b"\r\n\r\n").unwrap(); + &message[at + 4..] +} + +/// The two halves of a detached fixture: the signed part as it came, and the CMS. +fn halves(message: &[u8]) -> (Vec<u8>, Vec<u8>) { + let text = String::from_utf8_lossy(message); + let boundary = text.split("boundary=\"").nth(1).unwrap().split('"').next().unwrap().to_string(); + let delimiter = format!("\r\n--{boundary}"); + let body = String::from_utf8_lossy(body(message)).into_owned(); + let pieces: Vec<&str> = body.split(delimiter.as_str()).collect(); + // pieces[0] is the preamble up to the first delimiter line; the content follows its CRLF. + let content = pieces[1].strip_prefix("\r\n").unwrap().as_bytes().to_vec(); + let signature_part = pieces[2].strip_prefix("\r\n").unwrap(); + (content, base64(body_of(signature_part.as_bytes()))) +} + +fn body_of(part: &[u8]) -> &[u8] { + let at = part.windows(4).position(|w| w == b"\r\n\r\n").unwrap(); + &part[at + 4..] +} + +fn anchors() -> Anchors { + Anchors::new([CA]) +} + +fn checked_detached(message: &[u8], anchors: &Anchors, from: &str, now: i64, known: &[&[u8]]) -> Checked { + let (content, signature) = halves(message); + check(Signed::Detached { content: &content, signature: &signature }, &Context { anchors, from, now, known, coverage: Coverage::Whole }).unwrap() +} + +fn checked_opaque(message: &[u8], anchors: &Anchors, from: &str) -> Checked { + let cms = base64(body(message)); + check(Signed::Opaque(&cms), &Context { anchors, from, now: NOW, known: &[], coverage: Coverage::Whole }).unwrap() +} + +#[test] +fn alices_detached_signature_is_verified() { + let c = checked_detached(DETACHED, &anchors(), "alice@smime.example", NOW, &[]); + assert_eq!(c.signature.verdict, Verdict::Verified, "{c:?}"); + assert_eq!(c.signature.why, None); + let signer = c.signature.signer.clone().unwrap(); + assert_eq!(signer.name, "Alice Lovelace"); + assert_eq!(signer.addresses, vec!["alice@smime.example".to_string()]); + assert_eq!(signer.issuer, "Sample LAMPS RSA Certification Authority"); + assert_eq!(signer.fingerprint.len(), 32 * 3 - 1); + assert!(signer.not_before < NOW && NOW < signer.not_after); + assert!(c.signature.signed_at.is_some(), "OpenSSL gives a signing time"); + assert!(!c.signature.revocation_checked); + assert_eq!(c.certificate.as_deref(), Some(ALICE), "the certificate is worth keeping"); +} + +#[test] +fn the_address_is_compared_without_regard_to_case() { + let c = checked_detached(DETACHED, &anchors(), "Alice@SMIME.example", NOW, &[]); + assert_eq!(c.signature.verdict, Verdict::Verified); +} + +#[test] +fn opaque_ber_pss_and_bare_signatures_are_verified() { + for message in [OPAQUE, OPAQUE_BER] { + let c = checked_opaque(message, &anchors(), "alice@smime.example"); + assert_eq!(c.signature.verdict, Verdict::Verified, "{c:?}"); + } + for message in [NO_ATTRIBUTES, PSS] { + let c = checked_detached(message, &anchors(), "alice@smime.example", NOW, &[]); + assert_eq!(c.signature.verdict, Verdict::Verified, "{c:?}"); + } +} + +#[test] +fn sha1_is_no_longer_safe() { + let c = checked_detached(SHA1, &anchors(), "alice@smime.example", NOW, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Unchecked, Some(Why::WeakAlgorithm))); + assert_eq!(c.certificate, None); +} + +#[test] +fn a_signature_without_its_certificate_needs_one_kept_here() { + let c = checked_detached(NO_CERTS, &anchors(), "alice@smime.example", NOW, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Unchecked, Some(Why::NoPublicKey))); + let c = checked_detached(NO_CERTS, &anchors(), "alice@smime.example", NOW, &[ALICE]); + assert_eq!(c.signature.verdict, Verdict::Verified); +} + +#[test] +fn an_unknown_issuer_another_address_and_an_expired_certificate_are_not_verified() { + let c = checked_detached(DETACHED, &Anchors::default(), "alice@smime.example", NOW, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::NotVerified, Some(Why::UnknownIssuer))); + assert_eq!(c.certificate, None, "only a certificate that is trusted and valid is kept (#30 review 7)"); + let c = checked_detached(DETACHED, &anchors(), "bob@smime.example", NOW, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::NotVerified, Some(Why::AddressMismatch))); + assert_eq!(c.certificate, None, "not kept for an address it isn't for"); + // 2060: past 2052. + let c = checked_detached(DETACHED, &anchors(), "alice@smime.example", 2_840_140_800, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::NotVerified, Some(Why::Expired))); + assert_eq!(c.certificate, None, "nor one out of date"); + let c = checked_detached(DETACHED, &anchors(), "alice@smime.example", NOW, &[]); + assert!(c.certificate.is_some(), "a trusted one, valid now, for the sender, is"); +} + +#[test] +fn a_change_after_signing_is_seen() { + let (mut content, signature) = halves(DETACHED); + let at = content.windows(7).position(|w| w == b"Tuesday").unwrap(); + content[at] = b'W'; + let c = check( + Signed::Detached { content: &content, signature: &signature }, + &Context { anchors: &anchors(), from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Changed, Some(Why::Altered))); + // Opaque: the content inside the CMS. + let mut cms = base64(body(OPAQUE)); + let at = cms.windows(7).position(|w| w == b"Tuesday").unwrap(); + cms[at] = b'W'; + let c = + check(Signed::Opaque(&cms), &Context { anchors: &anchors(), from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Whole }) + .unwrap(); + assert_eq!(c.signature.verdict, Verdict::Changed); + // The signature itself. + let (content, mut signature) = halves(DETACHED); + let last = signature.len() - 1; + signature[last] ^= 1; + let c = check( + Signed::Detached { content: &content, signature: &signature }, + &Context { anchors: &anchors(), from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!(c.signature.verdict, Verdict::Changed); +} + +#[test] +fn content_in_lf_lines_is_checked_in_its_canonical_form() { + let (content, signature) = halves(DETACHED); + let lf: Vec<u8> = String::from_utf8_lossy(&content).replace("\r\n", "\n").into_bytes(); + let c = check( + Signed::Detached { content: &lf, signature: &signature }, + &Context { anchors: &anchors(), from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!(c.signature.verdict, Verdict::Verified); +} + +#[test] +fn enveloped_data_is_no_digital_signature_and_junk_is_unreadable() { + // ContentInfo { envelopedData, [0] { SEQUENCE {} } }. + let enveloped = [0x30, 0x0f, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x03, 0xa0, 0x02, 0x30, 0x00]; + let context = Context { anchors: &Anchors::default(), from: "a@example.org", now: NOW, known: &[], coverage: Coverage::Whole }; + assert_eq!(check(Signed::Opaque(&enveloped), &context), None); + let junk = check(Signed::Opaque(b"not a CMS"), &context).unwrap(); + assert_eq!((junk.signature.verdict, junk.signature.why), (Verdict::Unchecked, Some(Why::Unreadable))); +} + +// ---- certificates made here ---- + +const SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1"); +const ECDSA_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2"); +const ECDSA_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.3"); +const SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2"); + +struct Made { + der: Vec<u8>, + key: rcgen::KeyPair, + params: rcgen::CertificateParams, +} + +fn params(name: &str) -> rcgen::CertificateParams { + let mut p = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap(); + p.distinguished_name = rcgen::DistinguishedName::new(); + p.distinguished_name.push(rcgen::DnType::CommonName, name); + p.not_before = rcgen::date_time_ymd(2020, 1, 1); + p.not_after = rcgen::date_time_ymd(2050, 1, 1); + p +} + +fn ca_params(name: &str) -> rcgen::CertificateParams { + let mut p = params(name); + p.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + p.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign, rcgen::KeyUsagePurpose::CrlSign]; + p +} + +fn signer_params(name: &str, address: &str) -> rcgen::CertificateParams { + let mut p = params(name); + p.subject_alt_names = vec![rcgen::SanType::Rfc822Name(address.try_into().unwrap())]; + p.key_usages = vec![rcgen::KeyUsagePurpose::DigitalSignature]; + p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::EmailProtection]; + p +} + +fn key(alg: &'static rcgen::SignatureAlgorithm) -> rcgen::KeyPair { + rcgen::KeyPair::generate_for(alg).unwrap() +} + +fn root(name: &str) -> Made { + let key = key(&rcgen::PKCS_ECDSA_P256_SHA256); + let params = ca_params(name); + let der = params.self_signed(&key).unwrap().der().to_vec(); + Made { der, key, params } +} + +fn issued(params: rcgen::CertificateParams, key: rcgen::KeyPair, by: &Made) -> Made { + let issuer = rcgen::Issuer::new(by.params.clone(), &by.key); + let der = params.signed_by(&key, &issuer).unwrap().der().to_vec(); + Made { der, key, params } +} + +/// A detached CMS SignedData over `content` by `signer`, carrying `certs`. +fn sign(content: &[u8], signer: &Made, certs: &[&Made], p384: bool) -> Vec<u8> { + sign_with(content, signer, certs, p384, |_| {}) +} + +/// [`sign`], with the signer's information changed by `tweak` after it is made. +fn sign_with(content: &[u8], signer: &Made, certs: &[&Made], p384: bool, tweak: impl Fn(&mut SignerInfo)) -> Vec<u8> { + sign_data_with(content, signer, certs, p384, tweak, |_| {}) +} + +/// [`sign_with`], with the SignedData changed by `tweak_data` too. +fn sign_data_with( + content: &[u8], + signer: &Made, + certs: &[&Made], + p384: bool, + tweak: impl Fn(&mut SignerInfo), + tweak_data: impl Fn(&mut SignedData), +) -> Vec<u8> { + let cert = Certificate::from_der(&signer.der).unwrap(); + let (digest_oid, sig_oid) = if p384 { (SHA384, ECDSA_SHA384) } else { (SHA256, ECDSA_SHA256) }; + let digest = if p384 { ring::digest::digest(&ring::digest::SHA384, content) } else { ring::digest::digest(&ring::digest::SHA256, content) }; + let attr = |oid: &str, value: Any| Attribute { oid: ObjectIdentifier::new_unwrap(oid), values: SetOfVec::try_from(vec![value]).unwrap() }; + let attrs: SetOfVec<Attribute> = SetOfVec::try_from(vec![ + attr("1.2.840.113549.1.9.3", Any::encode_from(&ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1")).unwrap()), + attr("1.2.840.113549.1.9.4", Any::encode_from(&OctetString::new(digest.as_ref().to_vec()).unwrap()).unwrap()), + ]) + .unwrap(); + let to_sign = attrs.to_der().unwrap(); + let alg = if p384 { &ring::signature::ECDSA_P384_SHA384_ASN1_SIGNING } else { &ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING }; + let rng = ring::rand::SystemRandom::new(); + let pair = ring::signature::EcdsaKeyPair::from_pkcs8(alg, &signer.key.serialize_der(), &rng).unwrap(); + let signature = pair.sign(&rng, &to_sign).unwrap(); + let info = SignerInfo { + version: CmsVersion::V1, + sid: SignerIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber { + issuer: cert.tbs_certificate().issuer().clone(), + serial_number: cert.tbs_certificate().serial_number().clone(), + }), + digest_alg: AlgorithmIdentifierOwned { oid: digest_oid, parameters: None }, + signed_attrs: Some(attrs), + signature_algorithm: AlgorithmIdentifierOwned { oid: sig_oid, parameters: None }, + signature: OctetString::new(signature.as_ref().to_vec()).unwrap(), + unsigned_attrs: None, + }; + let mut info = info; + tweak(&mut info); + let set: Vec<cms::cert::CertificateChoices> = + certs.iter().map(|c| cms::cert::CertificateChoices::Certificate(Certificate::from_der(&c.der).unwrap())).collect(); + let mut data = SignedData { + version: CmsVersion::V1, + digest_algorithms: SetOfVec::try_from(vec![AlgorithmIdentifierOwned { oid: digest_oid, parameters: None }]).unwrap(), + encap_content_info: EncapsulatedContentInfo { econtent_type: ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1"), econtent: None }, + certificates: Some(CertificateSet::try_from(set).unwrap()), + crls: None, + signer_infos: SignerInfos::try_from(vec![info]).unwrap(), + }; + tweak_data(&mut data); + ContentInfo { content_type: ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.2"), content: Any::encode_from(&data).unwrap() }.to_der().unwrap() +} + +fn verdict(cms: &[u8], content: &[u8], anchors: &Anchors, from: &str) -> (Verdict, Option<Why>) { + let c = check(Signed::Detached { content, signature: cms }, &Context { anchors, from, now: NOW, known: &[], coverage: Coverage::Whole }).unwrap(); + (c.signature.verdict, c.signature.why) +} + +const CONTENT: &[u8] = b"Content-Type: text/plain\r\n\r\nThe accounts are ready.\r\n"; + +#[test] +fn a_path_through_an_intermediate_authority_is_verified() { + let root = root("Example Root"); + let intermediate = issued(ca_params("Example Mail CA"), key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let ada = issued(signer_params("Ada", "ada@example.org"), key(&rcgen::PKCS_ECDSA_P256_SHA256), &intermediate); + let cms = sign(CONTENT, &ada, &[&ada, &intermediate], false); + let anchors = Anchors::new([&root.der]); + assert_eq!(verdict(&cms, CONTENT, &anchors, "ada@example.org"), (Verdict::Verified, None)); + // Without the intermediate authority's certificate there is no path. + let alone = sign(CONTENT, &ada, &[&ada], false); + assert_eq!(verdict(&alone, CONTENT, &anchors, "ada@example.org"), (Verdict::NotVerified, Some(Why::UnknownIssuer))); + // A P-384 signer. + let grace = issued(signer_params("Grace", "grace@example.org"), key(&rcgen::PKCS_ECDSA_P384_SHA384), &intermediate); + let cms = sign(CONTENT, &grace, &[&grace, &intermediate], true); + assert_eq!(verdict(&cms, CONTENT, &anchors, "grace@example.org"), (Verdict::Verified, None)); +} + +#[test] +fn a_certificate_not_for_mail_or_signed_by_itself_is_not_verified() { + let root = root("Example Root"); + let anchors = Anchors::new([&root.der]); + let mut web = signer_params("Web", "web@example.org"); + web.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth]; + let web = issued(web, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let cms = sign(CONTENT, &web, &[&web], false); + assert_eq!(verdict(&cms, CONTENT, &anchors, "web@example.org"), (Verdict::NotVerified, Some(Why::NotForEmail))); + let own_key = key(&rcgen::PKCS_ECDSA_P256_SHA256); + let own_params = signer_params("Self", "self@example.org"); + let own = Made { der: own_params.self_signed(&own_key).unwrap().der().to_vec(), key: own_key, params: own_params }; + let cms = sign(CONTENT, &own, &[&own], false); + assert_eq!(verdict(&cms, CONTENT, &anchors, "self@example.org"), (Verdict::NotVerified, Some(Why::SelfSigned))); + // Unless the host trusts it itself. + assert_eq!(verdict(&cms, CONTENT, &Anchors::new([&own.der]), "self@example.org"), (Verdict::Verified, None)); +} + +#[test] +fn an_expired_link_is_not_verified() { + let root = root("Example Root"); + let mut old = signer_params("Old", "old@example.org"); + old.not_after = rcgen::date_time_ymd(2021, 1, 1); + let old = issued(old, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let cms = sign(CONTENT, &old, &[&old], false); + assert_eq!(verdict(&cms, CONTENT, &Anchors::new([&root.der]), "old@example.org"), (Verdict::NotVerified, Some(Why::Expired))); +} + +#[test] +fn a_certificate_from_another_authority_of_the_same_name_is_not_trusted() { + let real = root("Example Root"); + let fake = root("Example Root"); + let ada = issued(signer_params("Ada", "ada@example.org"), key(&rcgen::PKCS_ECDSA_P256_SHA256), &fake); + let cms = sign(CONTENT, &ada, &[&ada], false); + assert_eq!(verdict(&cms, CONTENT, &Anchors::new([&real.der]), "ada@example.org"), (Verdict::NotVerified, Some(Why::UnknownIssuer))); +} + +/// A certificate of the signer's issuer and serial number put in the message (anybody can put +/// one there) is not the signer's unless its key made the signature: it changes nothing. +#[test] +fn a_certificate_that_only_claims_the_signers_name_changes_nothing() { + let real = root("Example Root"); + let fake = root("Example Root"); + let serial = |mut p: rcgen::CertificateParams| { + p.serial_number = Some(rcgen::SerialNumber::from(vec![0x30, 0x01, 0x02])); + p + }; + let ada = issued(serial(signer_params("Ada", "ada@example.org")), key(&rcgen::PKCS_ECDSA_P256_SHA256), &real); + let impostor = issued(serial(signer_params("Ada", "ada@example.org")), key(&rcgen::PKCS_ECDSA_P256_SHA256), &fake); + let anchors = Anchors::new([&real.der]); + // The impostor first: the signer is still found, and verified. + let cms = sign(CONTENT, &ada, &[&impostor, &ada], false); + assert_eq!(verdict(&cms, CONTENT, &anchors, "ada@example.org"), (Verdict::Verified, None)); + // Changed content is put down to the signer that fits, and named. + let changed = b"Content-Type: text/plain\r\n\r\nThe accounts are empty.\r\n"; + let c = check( + Signed::Detached { content: changed, signature: &cms }, + &Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Changed, Some(Why::Altered))); + let named = c.signature.signer.unwrap(); + assert_eq!(named.fingerprint, crate::cert::Cert::from_der(&ada.der).unwrap().fingerprint(), "the real signer, not the impostor"); + // With only the impostor's certificate, nobody is named as having signed it. + let alone = sign(CONTENT, &ada, &[&impostor], false); + let c = check( + Signed::Detached { content: CONTENT, signature: &alone }, + &Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!(c.signature.verdict, Verdict::Changed); + assert!(c.signature.signer.is_none()); + assert!(c.certificate.is_none(), "nothing of it is kept"); +} + +/// A signature that can't be read is "can't be checked", never "changed". +#[test] +fn a_malformed_signature_cant_be_checked() { + let root = root("Example Root"); + let ada = issued(signer_params("Ada", "ada@example.org"), key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let junk = sign_with(CONTENT, &ada, &[&ada], false, |info| info.signature = OctetString::new(vec![0xff; 12]).unwrap()); + assert_eq!(verdict(&junk, CONTENT, &Anchors::new([&root.der]), "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); + // An RSA signature algorithm for an elliptic-curve key: of different kinds. + let crossed = sign_with(CONTENT, &ada, &[&ada], false, |info| { + info.signature_algorithm = AlgorithmIdentifierOwned { oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11"), parameters: None } + }); + assert_eq!(verdict(&crossed, CONTENT, &Anchors::new([&root.der]), "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); +} + +/// A valid signature by a trusted signer over only part of a message (a wrapper's first part) +/// is never verified for the message. +#[test] +fn a_signature_over_part_of_a_message_is_not_verified_for_it() { + let (content, signature) = halves(DETACHED); + let anchors = anchors(); + let c = check( + Signed::Detached { content: &content, signature: &signature }, + &Context { anchors: &anchors, from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Part }, + ) + .unwrap(); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::NotVerified, Some(Why::PartlySigned))); + assert_eq!(c.signature.coverage, Coverage::Part); + // A message from several people is nobody's alone: no address matches. + let c = checked_detached(DETACHED, &anchors, "", NOW, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::NotVerified, Some(Why::AddressMismatch))); +} + +// ---- #30 review: what a path must keep (RFC 5280 §4.2, §6.1) ---- + +/// An authority's certificate for `name` issued by `by`, changed by `change` first. +fn authority(name: &str, by: &Made, change: impl FnOnce(&mut rcgen::CertificateParams)) -> Made { + let mut p = ca_params(name); + change(&mut p); + issued(p, key(&rcgen::PKCS_ECDSA_P256_SHA256), by) +} + +fn signer_by(name: &str, address: &str, by: &Made) -> Made { + issued(signer_params(name, address), key(&rcgen::PKCS_ECDSA_P256_SHA256), by) +} + +/// The verdict for a message by `leaf` carrying `chain`, against `root`. +fn path_verdict(leaf: &Made, chain: &[&Made], root: &Made, from: &str) -> (Verdict, Option<Why>) { + let mut certs = vec![leaf]; + certs.extend_from_slice(chain); + let cms = sign(CONTENT, leaf, &certs, false); + verdict(&cms, CONTENT, &Anchors::new([&root.der]), from) +} + +#[test] +fn name_constraints_on_mail_addresses_are_kept() { + let root = root("Example Root"); + let corp = authority("Corp CA", &root, |p| { + p.name_constraints = Some(rcgen::NameConstraints { + permitted_subtrees: vec![rcgen::GeneralSubtree::Rfc822Name("corp.example".into())], + excluded_subtrees: vec![rcgen::GeneralSubtree::Rfc822Name("ceo@corp.example".into())], + }) + }); + let inside = signer_by("Ada", "ada@corp.example", &corp); + assert_eq!(path_verdict(&inside, &[&corp], &root, "ada@corp.example"), (Verdict::Verified, None)); + let outside = signer_by("CEO", "ceo@bank.example", &corp); + assert_eq!(path_verdict(&outside, &[&corp], &root, "ceo@bank.example"), (Verdict::NotVerified, Some(Why::Constrained))); + let excluded = signer_by("CEO", "ceo@corp.example", &corp); + assert_eq!(path_verdict(&excluded, &[&corp], &root, "ceo@corp.example"), (Verdict::NotVerified, Some(Why::Constrained))); + // A leading dot: any host under the domain, not the domain itself. + let sub = authority("Sub CA", &root, |p| { + p.name_constraints = Some(rcgen::NameConstraints { + permitted_subtrees: vec![rcgen::GeneralSubtree::Rfc822Name(".corp.example".into())], + excluded_subtrees: vec![], + }) + }); + let mail = signer_by("Ada", "ada@mail.corp.example", &sub); + assert_eq!(path_verdict(&mail, &[&sub], &root, "ada@mail.corp.example"), (Verdict::Verified, None)); + let bare = signer_by("Ada", "ada@corp.example", &sub); + assert_eq!(path_verdict(&bare, &[&sub], &root, "ada@corp.example"), (Verdict::NotVerified, Some(Why::Constrained))); + assert!(crate::cert::mail_within("Ada@Corp.Example", "corp.example")); + assert!(!crate::cert::mail_within("ada@evilcorp.example", ".corp.example")); +} + +#[test] +fn name_constraints_on_directory_names_are_kept() { + let root = root("Example Root"); + let mut corp_dn = rcgen::DistinguishedName::new(); + corp_dn.push(rcgen::DnType::OrganizationName, "Corp"); + let corp = authority("Corp CA", &root, |p| { + p.name_constraints = Some(rcgen::NameConstraints { + permitted_subtrees: vec![rcgen::GeneralSubtree::DirectoryName(corp_dn.clone())], + excluded_subtrees: vec![], + }) + }); + let mut inside = signer_params("Ada", "ada@corp.example"); + inside.distinguished_name = rcgen::DistinguishedName::new(); + inside.distinguished_name.push(rcgen::DnType::OrganizationName, "Corp"); + inside.distinguished_name.push(rcgen::DnType::CommonName, "Ada"); + let inside = issued(inside, key(&rcgen::PKCS_ECDSA_P256_SHA256), &corp); + assert_eq!(path_verdict(&inside, &[&corp], &root, "ada@corp.example"), (Verdict::Verified, None)); + let outside = signer_by("Mallory", "mallory@corp.example", &corp); + assert_eq!(path_verdict(&outside, &[&corp], &root, "mallory@corp.example"), (Verdict::NotVerified, Some(Why::Constrained))); +} + +#[test] +fn an_excluded_directory_name_written_another_way_is_still_excluded() { + let root = root("Example Root"); + let mut rogue = rcgen::DistinguishedName::new(); + rogue.push(rcgen::DnType::OrganizationName, "Rogue Unit"); + let ca = authority("Corp CA", &root, |p| { + p.name_constraints = + Some(rcgen::NameConstraints { permitted_subtrees: vec![], excluded_subtrees: vec![rcgen::GeneralSubtree::DirectoryName(rogue)] }) + }); + // The same name in another string type, case and spacing (RFC 5280 §7.1). + let mut dressed = signer_params("Mallory", "mallory@corp.example"); + dressed.distinguished_name = rcgen::DistinguishedName::new(); + dressed.distinguished_name.push(rcgen::DnType::OrganizationName, rcgen::DnValue::PrintableString(" ROGUE unit ".try_into().unwrap())); + dressed.distinguished_name.push(rcgen::DnType::CommonName, "Mallory"); + let dressed = issued(dressed, key(&rcgen::PKCS_ECDSA_P256_SHA256), &ca); + assert_eq!(path_verdict(&dressed, &[&ca], &root, "mallory@corp.example"), (Verdict::NotVerified, Some(Why::Constrained))); + let other = signer_by("Ada", "ada@corp.example", &ca); + assert_eq!(path_verdict(&other, &[&ca], &root, "ada@corp.example"), (Verdict::Verified, None)); +} + +#[test] +fn an_unknown_critical_extension_is_refused() { + let root = root("Example Root"); + let mut odd = signer_params("Ada", "ada@example.org"); + let mut ext = rcgen::CustomExtension::from_oid_content(&[1, 3, 6, 1, 4, 1, 99999, 1], vec![0x05, 0x00]); + ext.set_criticality(true); + odd.custom_extensions = vec![ext]; + let odd = issued(odd, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + assert_eq!(path_verdict(&odd, &[], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); + // On an authority on the way too. + let ca = authority("Odd CA", &root, |p| { + let mut ext = rcgen::CustomExtension::from_oid_content(&[1, 3, 6, 1, 4, 1, 99999, 2], vec![0x05, 0x00]); + ext.set_criticality(true); + p.custom_extensions = vec![ext]; + }); + let ada = signer_by("Ada", "ada@example.org", &ca); + assert_eq!(path_verdict(&ada, &[&ca], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); +} + +#[test] +fn a_path_length_constraint_is_kept() { + let root = root("Example Root"); + let ca = authority("Mail CA", &root, |p| p.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Constrained(0))); + let rogue = authority("Rogue CA", &ca, |_| {}); + let leaf = signer_by("Ada", "ada@example.org", &rogue); + assert_eq!(path_verdict(&leaf, &[&rogue, &ca], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); + // Directly below it, a signer is fine. + let direct = signer_by("Ada", "ada@example.org", &ca); + assert_eq!(path_verdict(&direct, &[&ca], &root, "ada@example.org"), (Verdict::Verified, None)); +} + +#[test] +fn an_authority_not_for_mail_cant_vouch_for_a_mail_certificate() { + let root = root("Example Root"); + let web = authority("Web CA", &root, |p| p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth]); + let leaf = signer_by("Ada", "ada@example.org", &web); + assert_eq!(path_verdict(&leaf, &[&web], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); + let mail = authority("Mail CA", &root, |p| p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::EmailProtection]); + let leaf = signer_by("Ada", "ada@example.org", &mail); + assert_eq!(path_verdict(&leaf, &[&mail], &root, "ada@example.org"), (Verdict::Verified, None)); +} + +#[test] +fn another_path_is_tried_when_the_first_doesnt_hold() { + let root = root("Example Root"); + let shared = key(&rcgen::PKCS_ECDSA_P256_SHA256); + let again = || rcgen::KeyPair::try_from(shared.serialize_der().as_slice()).unwrap(); + // The same authority, its key and name, in two certificates: one ran out, one is current. + let mut old = ca_params("Mail CA"); + old.not_after = rcgen::date_time_ymd(2021, 1, 1); + let old = issued(old, again(), &root); + let current = issued(ca_params("Mail CA"), again(), &root); + let leaf = signer_by("Ada", "ada@example.org", &current); + assert_eq!(path_verdict(&leaf, &[&old, &current], &root, "ada@example.org"), (Verdict::Verified, None)); + assert_eq!(path_verdict(&leaf, &[&old], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Expired))); +} + +#[test] +fn the_search_for_a_path_keeps_to_its_budget() { + let root = root("Example Root"); + let a = authority("A CA", &root, |_| {}); + let b = authority("B CA", &a, |_| {}); + let leaf = signer_by("Ada", "ada@example.org", &b); + let pool: Vec<crate::cert::Cert> = [&b, &a].iter().map(|m| crate::cert::Cert::from_der(&m.der).unwrap()).collect(); + let leaf = crate::cert::Cert::from_der(&leaf.der).unwrap(); + let anchors = Anchors::new([&root.der]); + let mut budget = 3; + assert_eq!(crate::chain::trust(&leaf, &pool, &anchors, NOW, &mut budget), Ok(())); + assert_eq!(budget, 0, "three links, three signatures"); + let mut budget = 2; + assert_eq!(crate::chain::trust(&leaf, &pool, &anchors, NOW, &mut budget), Err(Why::TooMuch), "stops when it runs out, and says so"); + assert_eq!(crate::MAX_VERIFICATIONS, 32); +} + +/// `cms` with its signers' information put in place of its own, in this order. +fn with_signers(cms: &[u8], infos: &[&[u8]]) -> Vec<u8> { + let (info, _) = craft_ber::read(cms).unwrap(); + let fields = craft_ber::children(info.value).unwrap(); + let (sd, _) = craft_ber::read(fields[1].value).unwrap(); + let parts = craft_ber::children(sd.value).unwrap(); + let mut inner: Vec<u8> = parts[..parts.len() - 1].iter().flat_map(|p| p.whole.to_vec()).collect(); + inner.extend(tlv(0x31, &infos.concat())); + let mut ci = fields[0].whole.to_vec(); + ci.extend(tlv(0xa0, &tlv(0x30, &inner))); + tlv(0x30, &ci) +} + +/// The first signer's information in `cms`, as it is written. +fn first_signer(cms: &[u8]) -> Vec<u8> { + let (info, _) = craft_ber::read(cms).unwrap(); + let fields = craft_ber::children(info.value).unwrap(); + let (sd, _) = craft_ber::read(fields[1].value).unwrap(); + let parts = craft_ber::children(sd.value).unwrap(); + craft_ber::children(parts.last().unwrap().value).unwrap()[0].whole.to_vec() +} + +/// The second try of a signature without signed attributes, over the content in its canonical +/// form, is a verification of its own, paid from the budget (#30 review 6). +#[test] +fn the_canonical_try_is_paid_from_the_budget() { + const LF: &[u8] = b"Content-Type: text/plain\n\nThe accounts are ready.\n"; + let root = root("Example Root"); + let mail = authority("Mail CA", &root, |_| {}); + let ada = signer_by("Ada", "ada@example.org", &mail); + // Without its signed attributes, the signature (made over them) fails as it came and in the + // canonical form alike. + let cms = sign_with(LF, &ada, &[&ada], false, |i| i.signed_attrs = None); + let anchors = Anchors::default(); + let context = Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &[], coverage: Coverage::Whole }; + let signed = Signed::Detached { content: LF, signature: &cms }; + let one = crate::verify::check_within(signed, &context, 1).unwrap(); + assert_eq!((one.signature.verdict, one.signature.why), (Verdict::Unchecked, Some(Why::TooMuch)), "one verification: no canonical try"); + let two = crate::verify::check_within(signed, &context, 2).unwrap(); + assert_eq!(two.signature.verdict, Verdict::Changed); +} + +/// A signer's name and issuer are shown without format characters: no bidirectional override +/// reorders them and no zero-width space hides in them (#30 review 6). +#[test] +fn a_certificates_names_lose_their_format_characters() { + let root = root("Example Root"); + let mail = authority("Mail\u{202e} CA\u{200b}", &root, |_| {}); + let ada = signer_by("Ada\u{202e}gpj.exe\u{200b}", "ada@example.org", &mail); + let cms = sign(CONTENT, &ada, &[&ada], false); + let anchors = Anchors::default(); + let context = Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &[], coverage: Coverage::Whole }; + let c = check(Signed::Detached { content: CONTENT, signature: &cms }, &context).unwrap(); + let signer = c.signature.signer.unwrap(); + assert_eq!(signer.name, "Adagpj.exe"); + assert!(signer.issuer.contains("Mail CA") && !signer.issuer.contains(['\u{202e}', '\u{200b}']), "{:?}", signer.issuer); +} + +#[test] +fn a_message_with_too_much_to_check_is_said_so() { + let root = root("Example Root"); + // Thirty authorities of the right name with the wrong keys come before the one that signed: + // the first signer's path takes all the budget, and the second signer is left with none. + let mut known: Vec<Made> = (0..30).map(|_| authority("Mail CA", &root, |_| {})).collect(); + let mail = authority("Mail CA", &root, |_| {}); + let ada = signer_by("Ada", "ada@example.org", &mail); + // A signer this computer trusts itself: no link to check, only its signature. + let trusted = issued(signer_params("Ada", "ada@example.org"), key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + known.push(mail); + let first = sign(CONTENT, &ada, &[&ada], false); + let second = sign(CONTENT, &trusted, &[], false); + let cms = with_signers(&first, &[&first_signer(&first), &first_signer(&second)]); + let known: Vec<&[u8]> = known.iter().map(|m| m.der.as_slice()).chain([trusted.der.as_slice()]).collect(); + let anchors = Anchors::new([&root.der, &trusted.der]); + let c = check( + Signed::Detached { content: CONTENT, signature: &cms }, + &Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &known, coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Unchecked, Some(Why::TooMuch))); + // With the budget to spare, the trusted signer alone is verified. + let alone = with_signers(&first, &[&first_signer(&second)]); + let c = check( + Signed::Detached { content: CONTENT, signature: &alone }, + &Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &known, coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Verified, None)); +} + +#[test] +fn an_authoritys_certificate_never_signs_mail_and_the_matching_address_is_said() { + let root = root("Example Root"); + let mut ca_signer = signer_params("Ada", "ada@example.org"); + ca_signer.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + let ca_signer = issued(ca_signer, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + assert_eq!(path_verdict(&ca_signer, &[], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::NotForEmail))); + let mut two = signer_params("Ada", "other@example.org"); + two.subject_alt_names.push(rcgen::SanType::Rfc822Name("ada@example.org".try_into().unwrap())); + let two = issued(two, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let cms = sign(CONTENT, &two, &[&two], false); + let anchors = Anchors::new([&root.der]); + let c = check( + Signed::Detached { content: CONTENT, signature: &cms }, + &Context { anchors: &anchors, from: "ADA@example.org", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!(c.signature.verdict, Verdict::Verified); + assert_eq!(c.signature.signer.unwrap().addresses.first().map(String::as_str), Some("ada@example.org")); +} + +#[test] +fn an_address_is_compared_as_it_is_written() { + let root = root("Example Root"); + let mut spaced = signer_params("Ada", "ada@example.org"); + spaced.subject_alt_names = vec![rcgen::SanType::Rfc822Name("ada@example.org ".try_into().unwrap())]; + let spaced = issued(spaced, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + assert_eq!(path_verdict(&spaced, &[], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::AddressMismatch))); + let ada = crate::cert::Cert::from_der(&signer_by("Ada", "ada@example.org", &root).der).unwrap(); + assert!(ada.is_for("ADA@EXAMPLE.ORG")); + assert!(!ada.is_for("ada@example.org\n")); + assert!(!ada.is_for("")); +} + +// ---- #30 review: SignedData read strictly ---- + +/// A DER element of `tag` holding `content`. +fn tlv(tag: u8, content: &[u8]) -> Vec<u8> { + let mut out = vec![tag]; + let n = content.len(); + if n < 0x80 { + out.push(n as u8); + } else if n < 0x100 { + out.extend([0x81, n as u8]); + } else { + out.extend([0x82, (n >> 8) as u8, n as u8]); + } + out.extend_from_slice(content); + out +} + +/// `cms` with `extra` put into its SignedData just before the signers. +fn smuggled(cms: &[u8], extra: &[u8]) -> Vec<u8> { + let (info, _) = craft_ber::read(cms).unwrap(); + let fields = craft_ber::children(info.value).unwrap(); + let (sd, _) = craft_ber::read(fields[1].value).unwrap(); + let parts = craft_ber::children(sd.value).unwrap(); + let mut inner = Vec::new(); + for (i, p) in parts.iter().enumerate() { + if i == parts.len() - 1 { + inner.extend_from_slice(extra); + } + inner.extend_from_slice(p.whole); + } + let sd = tlv(0x30, &inner); + let mut ci = fields[0].whole.to_vec(); + ci.extend(tlv(0xa0, &sd)); + tlv(0x30, &ci) +} + +#[test] +fn signed_data_with_anything_else_in_it_cant_be_checked() { + let root = root("Example Root"); + let ada = signer_by("Ada", "ada@example.org", &root); + let cms = sign(CONTENT, &ada, &[&ada], false); + let anchors = Anchors::new([&root.der]); + assert_eq!(verdict(&cms, CONTENT, &anchors, "ada@example.org"), (Verdict::Verified, None)); + // A field smuggled in, an OCTET STRING with other content, is refused, not passed over. + let forged = smuggled(&cms, &tlv(0x04, b"<p>Wire 10000 EUR to Mallory</p>")); + assert_eq!(verdict(&forged, CONTENT, &anchors, "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); + // And after the signers, where nothing may follow. + let signers = first_signer(&cms); + let mut after = with_signers(&cms, &[&signers]); + assert_eq!(verdict(&after, CONTENT, &anchors, "ada@example.org"), (Verdict::Verified, None)); + after = { + let (info, _) = craft_ber::read(&after).unwrap(); + let fields = craft_ber::children(info.value).unwrap(); + let (sd, _) = craft_ber::read(fields[1].value).unwrap(); + let mut inner = sd.value.to_vec(); + inner.extend(tlv(0x04, b"after")); + let mut ci = fields[0].whole.to_vec(); + ci.extend(tlv(0xa0, &tlv(0x30, &inner))); + tlv(0x30, &ci) + }; + assert_eq!(verdict(&after, CONTENT, &anchors, "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); + // A version that isn't one, and a detached signature that carries content too. + let versioned = sign_data_with(CONTENT, &ada, &[&ada], false, |_| {}, |d| d.version = CmsVersion::V2); + assert_eq!(verdict(&versioned, CONTENT, &anchors, "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); + let carrying = sign_data_with( + CONTENT, + &ada, + &[&ada], + false, + |_| {}, + |d| d.encap_content_info.econtent = Some(Any::encode_from(&OctetString::new(b"other".to_vec()).unwrap()).unwrap()), + ); + assert_eq!(verdict(&carrying, CONTENT, &anchors, "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); + // What mail signs is id-data. + let other_type = sign_data_with( + CONTENT, + &ada, + &[&ada], + false, + |_| {}, + |d| d.encap_content_info.econtent_type = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.16.1.4"), + ); + assert_eq!(verdict(&other_type, CONTENT, &anchors, "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); +} + +#[test] +fn an_opaque_signatures_content_is_given_for_showing() { + let cms = base64(body(OPAQUE)); + let content = craft_ber::signed_content(&cms).unwrap(); + assert!(String::from_utf8_lossy(&content).contains("Hello Bob"), "the signed MIME entity"); + let ber = base64(body(OPAQUE_BER)); + assert_eq!(craft_ber::signed_content(&ber), Some(content)); + let (_, detached) = halves(DETACHED); + assert_eq!(craft_ber::signed_content(&detached), None); +} + +#[test] +fn the_ber_reader_keeps_der_as_it_is_and_joins_pieces() { + assert_eq!(craft_ber::to_der(CA).as_deref(), Some(CA)); + // SEQUENCE (indefinite) { OCTET STRING in pieces "ab" "c" }. + let ber = [0x30, 0x80, 0x24, 0x80, 0x04, 0x02, b'a', b'b', 0x04, 0x01, b'c', 0x00, 0x00, 0x00, 0x00]; + assert_eq!(craft_ber::to_der(&ber), Some(vec![0x30, 0x05, 0x04, 0x03, b'a', b'b', b'c'])); + // A definite length inside, written longer than it need be (a certificate's, say, which its + // signature covers), is kept as it was written. + let ber = [0x30, 0x80, 0x30, 0x81, 0x03, 0x02, 0x01, 0x05, 0x00, 0x00]; + assert_eq!(craft_ber::to_der(&ber), Some(vec![0x30, 0x06, 0x30, 0x81, 0x03, 0x02, 0x01, 0x05])); + // Nesting past the bound is refused, not followed. + let deep: Vec<u8> = std::iter::repeat_n([0x30u8, 0x80], 200).flatten().chain(std::iter::repeat_n(0u8, 400)).collect(); + assert_eq!(craft_ber::to_der(&deep), None); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(512))] + + #[test] + fn any_bytes_never_panic(bytes in proptest::collection::vec(any::<u8>(), 0..4096)) { + let anchors = Anchors::new([CA]); + let context = Context { anchors: &anchors, from: "alice@smime.example", now: NOW, known: &[&bytes], coverage: Coverage::Whole }; + let _ = check(Signed::Opaque(&bytes), &context); + let _ = check(Signed::Detached { content: b"x", signature: &bytes }, &context); + let _ = craft_ber::to_der(&bytes); + let _ = Anchors::new([&bytes]); + } + + #[test] + fn a_damaged_cms_never_panics(flip in 0usize..3000, byte in any::<u8>(), cut in 0usize..3000) { + let mut cms = base64(body(OPAQUE_BER)); + if let Some(b) = cms.get_mut(flip) { + *b = byte; + } + cms.truncate(cut); + let anchors = Anchors::new([CA]); + let context = Context { anchors: &anchors, from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Whole }; + let _ = check(Signed::Opaque(&cms), &context); + let (content, signature) = halves(DETACHED); + let mut signature = signature; + if let Some(b) = signature.get_mut(flip) { + *b = byte; + } + let _ = check(Signed::Detached { content: &content, signature: &signature }, &context); + } +} + +#[test] +fn certificate_rejects_mismatched_outer_signature_algorithm() { + assert!(crate::cert::Cert::from_der(CA).is_some()); + let (outer, _) = craft_ber::read(CA).unwrap(); + let fields = craft_ber::children(outer.value).unwrap(); + let (algorithm, _) = craft_ber::read(fields[1].value).unwrap(); + assert_eq!(algorithm.tag, 0x06); + let offset = CA.len() - outer.value.len() + fields[0].whole.len() + fields[1].whole.len() - fields[1].value.len() + algorithm.whole.len() - 1; + let mut changed = CA.to_vec(); + changed[offset] ^= 1; + // The mutation remains a syntactically valid certificate: rejection must come from + // algorithm agreement, not a DER decoding error. Without that guard Cert accepts it. + let decoded = Certificate::from_der(&changed).unwrap(); + assert_ne!(decoded.signature_algorithm(), decoded.tbs_certificate().signature()); + assert!(crate::cert::Cert::from_der(&changed).is_none()); +} + +#[test] +fn shared_result_preserves_partial_coverage_and_name_bounds() { + use crate::digital_signature::{DigitalSignature, MAX_SIGNER_TEXT, SignatureFormat, signer_text}; + let signature = DigitalSignature::bare(SignatureFormat::Smime, Verdict::Verified, Why::PartlySigned).covering(Coverage::Part); + assert_eq!(signature.verdict, Verdict::NotVerified); + assert_eq!(signature.why, Some(Why::PartlySigned)); + assert_eq!(signer_text("Alice\u{202e}\u{200b}\nBob"), "Alice Bob"); + assert_eq!(signer_text(&"A".repeat(1000)).chars().count(), MAX_SIGNER_TEXT); +} + +#[test] +fn name_constraints_cover_addresses_beyond_the_display_limit() { + let root = root("Example Root"); + let corp = authority("Corp CA", &root, |p| { + p.name_constraints = Some(rcgen::NameConstraints { + permitted_subtrees: vec![rcgen::GeneralSubtree::Rfc822Name("corp.example".into())], + excluded_subtrees: vec![], + }); + }); + let mut params = signer_params("Many names", "ada@corp.example"); + for n in 1..crate::digital_signature::MAX_SIGNER_ADDRESSES { + params.subject_alt_names.push(rcgen::SanType::Rfc822Name(format!("alias{n}@corp.example").try_into().unwrap())); + } + params.subject_alt_names.push(rcgen::SanType::Rfc822Name("ceo@bank.example".try_into().unwrap())); + let signer = issued(params, key(&rcgen::PKCS_ECDSA_P256_SHA256), &corp); + assert_eq!(path_verdict(&signer, &[&corp], &root, "ada@corp.example"), (Verdict::NotVerified, Some(Why::Constrained))); +} + +#[test] +fn pss_restricted_public_keys_are_not_treated_as_unrestricted_rsa() { + use crate::algorithms::{Fault, Hash}; + let certificate = crate::cert::Cert::from_der(ALICE).unwrap(); + for message in [NO_ATTRIBUTES, PSS] { + let (content, cms) = halves(message); + let info = SignerInfo::from_der(&first_signer(&cms)).unwrap(); + let signed = info.signed_attrs.as_ref().map(|a| a.to_der().unwrap()).unwrap_or(content); + let hash = Hash::of(&info.digest_alg).unwrap(); + let mut key = certificate.public_key().clone(); + assert_eq!(crate::algorithms::verify(&key, &info.signature_algorithm, Some(hash), &signed, info.signature.as_bytes()), Ok(())); + key.algorithm.oid = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10"); + // An empty PSS parameter sequence restricts the key to SHA-1 defaults, not + // the SHA-256 signature above. PKCS#1 v1.5 is never allowed for a PSS key. + key.algorithm.parameters = Some(Any::from_der(&[0x30, 0]).unwrap()); + assert_eq!(crate::algorithms::verify(&key, &info.signature_algorithm, Some(hash), &signed, info.signature.as_bytes()), Err(Fault::Unknown)); + } +} + +#[test] +fn malformed_critical_san_is_not_an_absent_identity() { + let root = root("Example Root"); + let mut params = signer_params("Ada", "ada@example.org"); + params.subject_alt_names.clear(); + params + .distinguished_name + .push(rcgen::DnType::CustomDnType(vec![1, 2, 840, 113549, 1, 9, 1]), rcgen::DnValue::Ia5String("ada@example.org".try_into().unwrap())); + let mut san = rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 17], vec![0x05, 0]); + san.set_criticality(true); + params.custom_extensions.push(san); + let signer = issued(params, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + assert!(Certificate::from_der(&signer.der).is_ok(), "outer certificate is valid DER"); + assert!(crate::cert::Cert::from_der(&signer.der).is_none()); + assert_ne!(path_verdict(&signer, &[], &root, "ada@example.org").0, Verdict::Verified); +} + +#[test] +fn excluded_directory_san_is_checked_even_with_empty_subject() { + let root = root("Example Root"); + let mut rogue = rcgen::DistinguishedName::new(); + rogue.push(rcgen::DnType::OrganizationName, "Rogue"); + let ca = authority("Corp CA", &root, |p| { + p.name_constraints = + Some(rcgen::NameConstraints { permitted_subtrees: vec![], excluded_subtrees: vec![rcgen::GeneralSubtree::DirectoryName(rogue)] }); + }); + let directory: x509_cert::name::Name = "O=Rogue".parse().unwrap(); + for empty_subject in [false, true] { + let mut params = signer_params("Ada", "ada@example.org"); + if empty_subject { + params.distinguished_name = rcgen::DistinguishedName::new(); + } + params.subject_alt_names.clear(); + let mut names = tlv(0x81, b"ada@example.org"); + names.extend(tlv(0xa4, &directory.to_der().unwrap())); + let mut san = rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 17], tlv(0x30, &names)); + san.set_criticality(true); + params.custom_extensions.push(san); + let signer = issued(params, key(&rcgen::PKCS_ECDSA_P256_SHA256), &ca); + assert_eq!(path_verdict(&signer, &[&ca], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); + } +} + +#[test] +fn unsupported_unicode_directory_normalization_fails_closed() { + let root = root("Example Root"); + let mut excluded = rcgen::DistinguishedName::new(); + excluded.push(rcgen::DnType::OrganizationName, "STRASSE"); + let ca = authority("Corp CA", &root, |p| { + p.name_constraints = + Some(rcgen::NameConstraints { permitted_subtrees: vec![], excluded_subtrees: vec![rcgen::GeneralSubtree::DirectoryName(excluded)] }); + }); + let mut params = signer_params("Ada", "ada@example.org"); + params.distinguished_name = rcgen::DistinguishedName::new(); + params.distinguished_name.push(rcgen::DnType::OrganizationName, "Straße"); + let signer = issued(params, key(&rcgen::PKCS_ECDSA_P256_SHA256), &ca); + assert_eq!(path_verdict(&signer, &[&ca], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); +} + +#[test] +fn opaque_binary_content_is_verified_as_exact_octets_with_or_without_attributes() { + const BINARY: &[u8] = b"Content-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\nA\r\nB"; + const CHANGED: &[u8] = b"Content-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\nA\nB"; + let root = root("Example Root"); + let signer = signer_by("Ada", "ada@example.org", &root); + let anchors = Anchors::new([&root.der]); + let context = Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &[], coverage: Coverage::Whole }; + for bare in [false, true] { + let cms = sign_data_with( + BINARY, + &signer, + &[&signer], + false, + |info| { + if bare { + let rng = ring::rand::SystemRandom::new(); + let pair = ring::signature::EcdsaKeyPair::from_pkcs8( + &ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING, + &signer.key.serialize_der(), + &rng, + ) + .unwrap(); + info.signed_attrs = None; + info.signature = OctetString::new(pair.sign(&rng, BINARY).unwrap().as_ref().to_vec()).unwrap(); + } + }, + |data| data.encap_content_info.econtent = Some(Any::encode_from(&OctetString::new(BINARY.to_vec()).unwrap()).unwrap()), + ); + assert_eq!(check(Signed::Opaque(&cms), &context).unwrap().signature.verdict, Verdict::Verified); + let info = ContentInfo::from_der(&cms).unwrap(); + let mut data = info.content.decode_as::<SignedData>().unwrap(); + data.encap_content_info.econtent = Some(Any::encode_from(&OctetString::new(CHANGED.to_vec()).unwrap()).unwrap()); + let changed = ContentInfo { content_type: info.content_type, content: Any::encode_from(&data).unwrap() }.to_der().unwrap(); + assert_eq!(craft_ber::signed_content(&changed).unwrap(), CHANGED); + assert_eq!(check(Signed::Opaque(&changed), &context).unwrap().signature.verdict, Verdict::Changed); + } +} + +#[test] +fn unsupported_name_constraints_fail_closed_for_dns_ip_and_uri() { + // Critical excludedSubtrees for each unsupported form, alongside valid email identity. + for (tag, excluded, presented) in [ + (0x82, b"blocked.example".as_slice(), b"blocked.example".as_slice()), + (0x87, &[192, 0, 2, 0, 255, 255, 255, 0][..], &[192, 0, 2, 1][..]), + (0x86, b"blocked.example".as_slice(), b"https://blocked.example/path".as_slice()), + ] { + let root = root("Root"); + let ca = authority("Constrained CA", &root, |params| { + let subtree = tlv(0x30, &tlv(tag, excluded)); + let mut extension = rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 30], tlv(0x30, &tlv(0xa1, &subtree))); + extension.set_criticality(true); + params.custom_extensions.push(extension); + }); + let mut params = signer_params("Ada", "ada@example.org"); + params.subject_alt_names.clear(); + let mut names = tlv(0x81, b"ada@example.org"); + names.extend(tlv(tag, presented)); + params.custom_extensions.push(rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 17], tlv(0x30, &names))); + let signer = issued(params, key(&rcgen::PKCS_ECDSA_P256_SHA256), &ca); + assert_eq!(path_verdict(&signer, &[&ca], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); + } +} + +#[test] +fn later_matching_certificates_are_checked_for_trust_usage_and_address() { + let root = root("Renewal Root"); + let id = b"same-key-after-renewal"; + let with_id = |mut params: rcgen::CertificateParams| { + params.custom_extensions.push(rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 14], tlv(0x04, id))); + params + }; + let current = issued(with_id(signer_params("Ada", "ada@example.org")), key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let cms = sign_with(CONTENT, &current, &[], false, |info| { + info.version = CmsVersion::V3; + info.sid = SignerIdentifier::SubjectKeyIdentifier(x509_cert::ext::pkix::SubjectKeyIdentifier(OctetString::new(id.to_vec()).unwrap())); + }); + let anchors = Anchors::new([&root.der]); + for kind in 0..3 { + let mut params = signer_params("Ada", "ada@example.org"); + match kind { + 0 => params.not_after = rcgen::date_time_ymd(2021, 1, 1), + 1 => params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth], + _ => params.subject_alt_names = vec![rcgen::SanType::Rfc822Name("other@example.org".try_into().unwrap())], + } + let issuer = rcgen::Issuer::new(root.params.clone(), &root.key); + let first = with_id(params).signed_by(&current.key, &issuer).unwrap(); + let known: &[&[u8]] = &[first.der().as_ref(), &current.der]; + let context = Context { anchors: &anchors, from: "ada@example.org", now: NOW, known, coverage: Coverage::Whole }; + let checked = check(Signed::Detached { content: CONTENT, signature: &cms }, &context).unwrap(); + assert_eq!((checked.signature.verdict, checked.signature.why), (Verdict::Verified, None)); + assert_eq!(checked.certificate.as_deref(), Some(current.der.as_slice())); + // A later trusted certificate never excuses changed signed content. + let changed = check(Signed::Detached { content: b"changed", signature: &cms }, &context).unwrap(); + assert_eq!(changed.signature.verdict, Verdict::Changed); + } +} diff --git a/crates/smime/src/verify.rs b/crates/smime/src/verify.rs new file mode 100644 index 000000000..c2f9af084 --- /dev/null +++ b/crates/smime/src/verify.rs @@ -0,0 +1,478 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Checking CMS SignedData (RFC 5652 §5) as S/MIME carries it (RFC 8551 §3.5): the signer's +//! digest of what was signed, their signature over it, and whether their certificate is trusted +//! and for the message's sender. + +use crate::Timestamp; +use crate::digital_signature::{Coverage, DigitalSignature, SignatureFormat, Signer, Verdict, Why}; +use cms::signed_data::{EncapsulatedContentInfo, SignerIdentifier, SignerInfo}; +use const_oid::ObjectIdentifier; +use der::asn1::OctetString; +use der::{Decode, Encode}; + +use crate::algorithms::{self, Fault, Hash}; +use crate::cert::Cert; +use crate::chain::{self, Anchors}; +use craft_ber::{self as ber, Tlv}; + +/// The most certificates read from one message. +pub const MAX_CERTS: usize = 32; +/// The most signers of one message that are checked. +pub const MAX_SIGNERS: usize = 8; +/// The most signatures checked for one message, its signers' and their certificates' together +/// (#30): an RSA key of 8192 bits takes a while, and a message may carry many. +pub const MAX_VERIFICATIONS: usize = 32; +/// The most certificates tried for one signer: those that its identifier names (the message +/// may carry several of one name; only the one whose key made the signature is the signer's). +pub const MAX_CANDIDATES: usize = 4; + +const SIGNED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.2"); +const DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1"); +const CONTENT_TYPE: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.3"); +const MESSAGE_DIGEST: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.4"); +const SIGNING_TIME: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.5"); + +/// What a check is made against. +#[derive(Clone, Copy, Debug)] +pub struct Context<'a> { + /// The certificates the host trusts. + pub anchors: &'a Anchors, + /// The message's From address. + pub from: &'a str, + /// The time of the check, seconds since 1970. + pub now: Timestamp, + /// Certificates kept for the sender already, in DER: a message that doesn't carry its + /// signer's certificate may be checked with one of them. + pub known: &'a [&'a [u8]], + /// How much of the message the signed part is: the whole of it only when it is the + /// message's top level. A part is never verified for the message. + pub coverage: Coverage, +} + +/// A Digitally signed message's two halves. +#[derive(Clone, Copy, Debug)] +pub enum Signed<'a> { + /// `multipart/signed`: the signed part as it came (its MIME header and body) and the + /// signature part's bytes (the CMS SignedData, decoded from base64). + Detached { content: &'a [u8], signature: &'a [u8] }, + /// `application/pkcs7-mime; smime-type=signed-data`: the CMS SignedData holding what was + /// signed (decoded from base64). + Opaque(&'a [u8]), +} + +/// What a check found. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Checked { + pub signature: DigitalSignature, + /// The signer's certificate, in DER, when the signature over the message is the signer's + /// and the certificate is for the From address: worth keeping for that address (#30 R9). + pub certificate: Option<Vec<u8>>, +} + +/// Check `signed` against `context`. `None` when the CMS isn't SignedData at all (an Encrypted +/// message's enveloped data, say): not a Digital signature. Never fails otherwise: what can't be +/// read is [`Verdict::Unchecked`]. +pub fn check(signed: Signed<'_>, context: &Context<'_>) -> Option<Checked> { + check_within(signed, context, MAX_VERIFICATIONS) +} + +/// [`check`] with at most `verifications` signatures checked (for the tests, which spend a +/// smaller budget). +pub(crate) fn check_within(signed: Signed<'_>, context: &Context<'_>, verifications: usize) -> Option<Checked> { + let blob = match signed { + Signed::Detached { signature, .. } => signature, + Signed::Opaque(blob) => blob, + }; + let unreadable = || Some(unchecked(Why::Unreadable)); + let Some(der) = ber::to_der(blob) else { return unreadable() }; + let Some(parts) = content_info(&der) else { return unreadable() }; + if parts.content_type != SIGNED_DATA { + return None; + } + let Some(data) = signed_data(parts.content) else { return unreadable() }; + let Ok(eci) = EncapsulatedContentInfo::from_der(data.encap.whole) else { return unreadable() }; + // What mail signs is MIME, id-data (RFC 8551 §3.5); a detached signature carries none of it + // and an opaque one all of it. + if eci.econtent_type != DATA { + return unreadable(); + } + let content: &[u8] = match (signed, econtent(&data.encap)) { + (Signed::Detached { content, .. }, None) if eci.econtent.is_none() => content, + (Signed::Opaque(_), Some(c)) => c, + _ => return unreadable(), + }; + let mut pool: Vec<Cert> = data.certificates.iter().take(MAX_CERTS).filter_map(|c| Cert::from_der(c.whole)).collect(); + pool.extend(context.known.iter().take(MAX_CERTS).filter_map(|c| Cert::from_der(c))); + let mut digests = Digests::new(content, matches!(signed, Signed::Detached { .. })); + let mut budget = verifications; + let mut best: Option<Checked> = None; + for signer in data.signers.iter().take(MAX_SIGNERS) { + let found = one_signer(signer, &eci, &mut digests, &pool, context, &mut budget); + best = Some(match best { + Some(b) if b.signature.verdict <= found.signature.verdict => b, + _ => found, + }); + } + best.or_else(unreadable).map(|mut c| { + c.signature = c.signature.covering(context.coverage); + c + }) +} + +/// What was signed and its digests, each worked out once (#30: a long message isn't hashed +/// again for every signer and key tried), as it came and in its canonical form. +struct Digests<'a> { + content: &'a [u8], + allow_transport_normalization: bool, + /// The content with lone LFs made CRLF, when it has any: worked out at its first use. + canonical: Option<Option<Vec<u8>>>, + plain: Vec<(Hash, Vec<u8>)>, + crlf: Vec<(Hash, Vec<u8>)>, +} + +impl<'a> Digests<'a> { + fn new(content: &'a [u8], allow_transport_normalization: bool) -> Self { + Digests { content, allow_transport_normalization, canonical: None, plain: Vec::new(), crlf: Vec::new() } + } + + fn of(&mut self, hash: Hash) -> Vec<u8> { + if let Some((_, d)) = self.plain.iter().find(|(h, _)| *h == hash) { + return d.clone(); + } + let d = hash.digest(self.content); + self.plain.push((hash, d.clone())); + d + } + + /// The digest of the canonical form; `None` when the content has no lone LF (it is its own). + fn of_canonical(&mut self, hash: Hash) -> Option<Vec<u8>> { + // Encapsulated content is already the exact signed octet sequence. Rewriting + // binary payload newlines would authenticate different bytes than we expose. + if !self.allow_transport_normalization { + return None; + } + if let Some((_, d)) = self.crlf.iter().find(|(h, _)| *h == hash) { + return Some(d.clone()); + } + let content = self.content; + let canonical = self.canonical.get_or_insert_with(|| canonical(content)).as_ref()?; + let d = hash.digest(canonical); + self.crlf.push((hash, d.clone())); + Some(d) + } + + /// Whether `said` is the digest of the content as it came or in its canonical form. + fn matches(&mut self, hash: Hash, said: &[u8]) -> bool { + self.of(hash) == said || self.of_canonical(hash).is_some_and(|d| d == said) + } +} + +fn unchecked(why: Why) -> Checked { + Checked { signature: DigitalSignature::bare(SignatureFormat::Smime, Verdict::Unchecked, why), certificate: None } +} + +struct ContentInfoParts<'a> { + content_type: ObjectIdentifier, + content: &'a [u8], +} + +/// ContentInfo: its type, and the value inside its `[0] EXPLICIT`. +fn content_info(der: &[u8]) -> Option<ContentInfoParts<'_>> { + let (outer, rest) = ber::read(der)?; + if outer.tag != 0x30 || !rest.is_empty() { + return None; + } + let fields = ber::children(outer.value)?; + let [oid, explicit] = fields.as_slice() else { return None }; + if oid.tag != 0x06 || explicit.tag != 0xa0 { + return None; + } + let content_type = ObjectIdentifier::from_der(oid.whole).ok()?; + Some(ContentInfoParts { content_type, content: explicit.value }) +} + +/// SignedData's parts as they came, so that signatures are checked over the bytes the signer +/// wrote: what is inside, the certificates, and the signers. +struct SignedDataParts<'a> { + encap: Tlv<'a>, + certificates: Vec<Tlv<'a>>, + signers: Vec<Tlv<'a>>, +} + +/// SignedData read strictly (RFC 5652 §5.1): its version one of those defined, its digest +/// algorithms a SET of algorithm identifiers, encapContentInfo, the certificates and the +/// revocation lists when they are there, in that order, and the signers last: nothing else, and +/// nothing after. +fn signed_data(content: &[u8]) -> Option<SignedDataParts<'_>> { + let (outer, rest) = ber::read(content)?; + if outer.tag != 0x30 || !rest.is_empty() { + return None; + } + let fields = ber::children(outer.value)?; + let mut fields = fields.into_iter(); + let version = fields.next().filter(|f| f.tag == 0x02)?; + if !matches!(version.value, [1] | [3] | [4] | [5]) { + return None; + } + let digests = fields.next().filter(|f| f.tag == 0x31)?; + for d in ber::children(digests.value)? { + spki::AlgorithmIdentifierOwned::from_der(d.whole).ok()?; + } + let encap = fields.next().filter(|f| f.tag == 0x30)?; + let mut next = fields.next()?; + let mut certificates = Vec::new(); + if next.tag == 0xa0 { + // (Other kinds of certificate, [0]..[3] IMPLICIT, are left out; they are never a path.) + certificates = ber::children(next.value)?.into_iter().filter(|c| c.tag == 0x30).collect(); + next = fields.next()?; + } + if next.tag == 0xa1 { + next = fields.next()?; + } + if next.tag != 0x31 || fields.next().is_some() { + return None; + } + Some(SignedDataParts { encap, certificates, signers: ber::children(next.value)? }) +} + +/// The OCTET STRING inside encapContentInfo's `[0] EXPLICIT eContent`, when there is one (and +/// nothing else is there). +fn econtent<'a>(encap: &Tlv<'a>) -> Option<&'a [u8]> { + let fields = ber::children(encap.value)?; + let explicit = fields.get(1).filter(|f| f.tag == 0xa0)?; + let (octets, rest) = ber::read(explicit.value)?; + (octets.tag == 0x04 && rest.is_empty()).then_some(octets.value) +} + +/// The value of the signed attribute `oid`, in DER (its one value), when there is one. +fn attribute(info: &SignerInfo, oid: ObjectIdentifier) -> Option<Vec<u8>> { + let attrs = info.signed_attrs.as_ref()?; + let attr = attrs.iter().find(|a| a.oid == oid)?; + if attr.values.len() != 1 { + return None; + } + attr.values.iter().next()?.to_der().ok() +} + +/// The bytes a signer with signed attributes signed (RFC 5652 §5.4): the attributes as they came, +/// with their `[0] IMPLICIT` tag made the SET OF's. +fn signed_attributes(raw: &Tlv<'_>) -> Option<Vec<u8>> { + let fields = ber::children(raw.value)?; + let attrs = fields.iter().find(|f| f.tag == 0xa0)?; + let mut out = attrs.whole.to_vec(); + *out.first_mut()? = 0x31; + Some(out) +} + +/// `content` with every lone LF made CRLF (RFC 8551 §3.1.1's canonical form), when it has one. +fn canonical(content: &[u8]) -> Option<Vec<u8>> { + let mut lone = false; + let mut out = Vec::with_capacity(content.len().saturating_add(content.len() / 32)); + let mut previous = 0u8; + for &b in content { + if b == b'\n' && previous != b'\r' { + out.push(b'\r'); + lone = true; + } + out.push(b); + previous = b; + } + lone.then_some(out) +} + +fn one_signer( + raw: &Tlv<'_>, + eci: &EncapsulatedContentInfo, + digests: &mut Digests<'_>, + pool: &[Cert], + context: &Context<'_>, + budget: &mut usize, +) -> Checked { + let Ok(info) = SignerInfo::from_der(raw.whole) else { return unchecked(Why::Unreadable) }; + let hash = match Hash::of(&info.digest_alg) { + Ok(hash) => hash, + Err(fault) => return unchecked(why_not(fault)), + }; + let candidates = signer_certs(&info.sid, pool); + if candidates.is_empty() { + return unchecked(Why::NoPublicKey); + } + let signature = info.signature.as_bytes(); + // What the signer's key signed: the signed attributes (which hold the content's digest), or + // without them the content itself, as it came or in its canonical form. + let attributes = match &info.signed_attrs { + Some(_) => match signed_attributes(raw) { + Some(bytes) => Some(bytes), + None => return unchecked(Why::Unreadable), + }, + None => None, + }; + // The signer is the certificate whose key made the signature, of those its identifier names: + // another one of the same name (any can be put in a message) makes no difference. + let mut fault: Option<Fault> = None; + let mut signer: Option<(&Cert, Result<(), Why>)> = None; + let mut ran_out = false; + for cert in candidates { + let Some(left) = budget.checked_sub(1) else { + ran_out = true; + break; + }; + *budget = left; + let verified = match &attributes { + Some(bytes) => algorithms::verify(cert.public_key(), &info.signature_algorithm, Some(hash), bytes, signature), + None => { + let plain = algorithms::verify_hashed(cert.public_key(), &info.signature_algorithm, Some(hash), &mut |h| digests.of(h), signature); + // (Signed in its canonical form, perhaps: another verification, from the budget.) + if plain == Err(Fault::Invalid) && digests.of_canonical(hash).is_some() { + let Some(left) = budget.checked_sub(1) else { + ran_out = true; + break; + }; + *budget = left; + algorithms::verify_hashed( + cert.public_key(), + &info.signature_algorithm, + Some(hash), + &mut |h| digests.of_canonical(h).unwrap_or_default(), + signature, + ) + } else { + plain + } + } + }; + match verified { + Ok(()) => { + // Matching keys can occur in expired or renewed certificates. A valid + // signature alone does not select the certificate we can trust for mail. + let for_email = cert.for_email() && !cert.is_authority(); + let trust = chain::trust(cert, pool, context.anchors, context.now, budget) + .and_then(|()| for_email.then_some(()).ok_or(Why::NotForEmail)) + .and_then(|()| if cert.is_for(context.from) { Ok(()) } else { Err(Why::AddressMismatch) }); + if trust.is_ok() { + signer = Some((cert, trust)); + break; + } + if signer.is_none() { + signer = Some((cert, trust)); + } + if trust == Err(Why::TooMuch) { + ran_out = true; + break; + } + } + // (Of several faults, what says most: an algorithm, then a malformed key, then no + // match.) + Err(f) => fault = Some(fault.map_or(f, |g| worse(g, f))), + } + } + let Some((cert, mut trust)) = signer else { + return match fault { + // (A certificate not tried may have made it: no answer.) + _ if ran_out => unchecked(Why::TooMuch), + // No key it names made it: changed after signing, or never signed by any of them; + // nobody is named, since none of them fits. + Some(Fault::Invalid) | None => { + Checked { signature: DigitalSignature::bare(SignatureFormat::Smime, Verdict::Changed, Why::Altered), certificate: None } + } + Some(f) => unchecked(why_not(f)), + }; + }; + let result = |verdict: Verdict, why: Option<Why>| Checked { + signature: DigitalSignature { + format: SignatureFormat::Smime, + verdict, + why, + signer: Some(signer_of(cert)), + signed_at: signing_time(&info), + revocation_checked: false, + // (`check` says, from where in the message the signed part sat.) + coverage: Coverage::Part, + }, + certificate: None, + }; + if attributes.is_some() { + // The attributes are the signer's own words now: what they say of the content holds. + let Some(said_type) = attribute(&info, CONTENT_TYPE).and_then(|d| ObjectIdentifier::from_der(&d).ok()) else { + return unchecked(Why::Unreadable); + }; + let Some(said_digest) = attribute(&info, MESSAGE_DIGEST).and_then(|d| OctetString::from_der(&d).ok()) else { + return unchecked(Why::Unreadable); + }; + if said_type != eci.econtent_type || !digests.matches(hash, said_digest.as_bytes()) { + return result(Verdict::Changed, Some(Why::Altered)); + } + } + // A candidate left untried may be acceptable. Do not report the first + // refusal as definitive when the shared verification budget was exhausted. + if ran_out { + trust = Err(Why::TooMuch); + } + let mut r = match trust { + Ok(()) => result(Verdict::Verified, None), + Err(Why::TooMuch) => result(Verdict::Unchecked, Some(Why::TooMuch)), + // (An algorithm that's no longer safe on the way to a trust anchor: the certificate can't + // be relied on, but the message is as it was signed.) + Err(why) => result(Verdict::NotVerified, Some(why)), + }; + // Kept for the sender only when it is trusted, valid now and theirs: it is what mail to them + // will be encrypted with. + if trust.is_ok() { + r.certificate = Some(cert.der().to_vec()); + } + // The signer's address that is the sender's comes first: it is the one said. + if let (Some(address), Some(signer)) = (cert.address_for(context.from), r.signature.signer.as_mut()) { + let shown = crate::digital_signature::signer_text(&address); + signer.addresses.retain(|a| !a.eq_ignore_ascii_case(&shown)); + signer.addresses.insert(0, shown); + } + r +} + +/// Of two faults, the one that says most of why a signature can't be relied on. +fn worse(a: Fault, b: Fault) -> Fault { + let rank = |f: Fault| match f { + Fault::Weak => 0, + Fault::Unknown => 1, + Fault::Malformed => 2, + Fault::Invalid => 3, + }; + if rank(b) < rank(a) { b } else { a } +} + +fn why_not(fault: Fault) -> Why { + match fault { + Fault::Weak => Why::WeakAlgorithm, + Fault::Unknown => Why::UnknownAlgorithm, + Fault::Invalid => Why::Altered, + Fault::Malformed => Why::Unreadable, + } +} + +/// The certificates in `pool` that `sid` names, at most [`MAX_CANDIDATES`]. +fn signer_certs<'a>(sid: &SignerIdentifier, pool: &'a [Cert]) -> Vec<&'a Cert> { + match sid { + SignerIdentifier::IssuerAndSerialNumber(isn) => { + let Ok(issuer) = isn.issuer.to_der() else { return Vec::new() }; + let serial = isn.serial_number.as_bytes(); + pool.iter().filter(|c| c.issuer() == issuer.as_slice() && c.serial() == serial).take(MAX_CANDIDATES).collect() + } + SignerIdentifier::SubjectKeyIdentifier(ski) => { + let id = ski.0.as_bytes(); + pool.iter().filter(|c| c.key_id().as_deref() == Some(id)).take(MAX_CANDIDATES).collect() + } + } +} + +fn signer_of(cert: &Cert) -> Signer { + let (not_before, not_after) = cert.validity(); + Signer { name: cert.name(), addresses: cert.addresses(), fingerprint: cert.fingerprint(), issuer: cert.issuer_name(), not_before, not_after } +} + +/// The signing time the signer gives (RFC 5652 §11.3): their word, unchecked. +fn signing_time(info: &SignerInfo) -> Option<Timestamp> { + let der = attribute(info, SIGNING_TIME)?; + let time = x509_cert::time::Time::from_der(&der).ok()?; + Timestamp::try_from(time.to_unix_duration().as_secs()).ok() +} diff --git a/crates/smime/testdata/README.md b/crates/smime/testdata/README.md new file mode 100644 index 000000000..9200f2cc1 --- /dev/null +++ b/crates/smime/testdata/README.md @@ -0,0 +1,7 @@ +# S/MIME test vectors + +Restored from `UCS-Care-Group/mailcraft` commit +`240d1d42fe394cf3274402b180663ba9b43ca180`, `crates/smime/testdata`. +The source test suite identifies these as RFC 9216 example certificates and +OpenSSL-generated message vectors. These are public examples, not user mail or keys. +Source attribution: MailCraft contributors, MIT OR Apache-2.0. diff --git a/crates/smime/testdata/alice.sign.der b/crates/smime/testdata/alice.sign.der new file mode 100644 index 000000000..9bff7d1b3 Binary files /dev/null and b/crates/smime/testdata/alice.sign.der differ diff --git a/crates/smime/testdata/ca.rsa.der b/crates/smime/testdata/ca.rsa.der new file mode 100644 index 000000000..193b9ab9f Binary files /dev/null and b/crates/smime/testdata/ca.rsa.der differ diff --git a/crates/smime/testdata/detached.eml b/crates/smime/testdata/detached.eml new file mode 100644 index 000000000..51e8d3204 --- /dev/null +++ b/crates/smime/testdata/detached.eml @@ -0,0 +1,60 @@ +To: bob@smime.example +From: alice@smime.example +Subject: Signed minutes +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-256"; boundary="----011A3E8D1DC66D3261BBFB3EB4674ACD" + +This is an S/MIME signed message + +------011A3E8D1DC66D3261BBFB3EB4674ACD +Content-Type: text/plain; charset=us-ascii + +Hello Bob, + +The minutes of Tuesday are attached in spirit. + +Alice + +------011A3E8D1DC66D3261BBFB3EB4674ACD +Content-Type: application/pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIIGiQYJKoZIhvcNAQcCoIIGejCCBnYCAQExDTALBglghkgBZQMEAgEwCwYJKoZI +hvcNAQcBoIID0zCCA88wggK3oAMCAQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJ +KoZIhvcNAQENBQAwVTENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMgV0cx +MTAvBgNVBAMTKFNhbXBsZSBMQU1QUyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkwIBcNMTkxMTIwMDY1NDE4WhgPMjA1MjA5MjcwNjU0MThaMDsxDTALBgNVBAoT +BElFVEYxETAPBgNVBAsTCExBTVBTIFdHMRcwFQYDVQQDEw5BbGljZSBMb3ZlbGFj +ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT0iehYOBY+TZp/T5K2 +KNI05Hwr+E3wP6XTvyi6WWyTgBK9LCOwI2juwdRrjFBSXkk7pWpjXwsA3A5GOtz0 +FpfgyC7OxsVcF7q4WHWZWleYXFKlQHJD73nQwXP968+A/3rBX7PhO0DBbZnfitOL +PgPEwjTtdg0VQQ6Wz+CRQ/YbHPKaw7aRphZO63dKvIKp4cQVtkWQHi6syTjGsgkL +cLNau5LZDQUdsGV+SAo3nBdWCRYV+I65x8Kf4hCxqqmjV3d/2NKRu0BXnDe/N+iD +z3X0zEoj0fqXgq4SWcC0nsG1lyyXt1TL270I6ATKRGJWiQVCCpDtc0NT6vdJ45bC +SzsCAwEAAaOBrzCBrDAMBgNVHRMBAf8EAjAAMBcGA1UdIAQQMA4wDAYKYIZIAWUD +AgEwATAeBgNVHREEFzAVgRNhbGljZUBzbWltZS5leGFtcGxlMBMGA1UdJQQMMAoG +CCsGAQUFBwMEMA4GA1UdDwEB/wQEAwIGwDAdBgNVHQ4EFgQUu/bMsi0dBhIcl64p +apAQ0yBmZnMwHwYDVR0jBBgwFoAUkTCOfAcXDKfxCShlNhpnHGh29FkwDQYJKoZI +hvcNAQENBQADggEBAHOJojanzqmgaSN3/gqSQ4cbbmdj/R40BEPr+gXT+xiidfZ2 +iLNwYyTneuK6AChwKfnNvOFb8lV1iffRTF/KtmVEDMR/sYeqAH83KM5p3el2lVh4 +OHhyI0qNuz5oShNaACSioQ23WxHGVy9vsdVfnbhsplrWg9NQ2WbpCmK+2oMh2oYl +0Z/wvXMt9cG6jbMvcdH4z0IOvg6mrYkKTM/RCGnumghxwYToj1OyD5Gs4D2IJCw+ +fX5ODxh52MbNRYXTus2ZPRPM8JXNQC4GWv4km3M4rKnJDd6hnoQ9rNeozIcBVyyb +QYjfrgg4DRvw9Ksk22OH4ConlB8f7R7s1LM2cSYxggJ8MIICeAIBATBsMFUxDTAL +BgNVBAoTBElFVEYxETAPBgNVBAsTCExBTVBTIFdHMTEwLwYDVQQDEyhTYW1wbGUg +TEFNUFMgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5AhM3QQV57XV/QqmiXDr0 ++GrOmqnXMAsGCWCGSAFlAwQCAaCB5DAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcB +MBwGCSqGSIb3DQEJBTEPFw0yNjExMDkxMjA5NTBaMC8GCSqGSIb3DQEJBDEiBCCl +3jtcr1bjeDRcGd4HoRLXWhkBqvOm0Ywlw7H6AYF2pzB5BgkqhkiG9w0BCQ8xbDBq +MAsGCWCGSAFlAwQBKjALBglghkgBZQMEARYwCwYJYIZIAWUDBAECMAoGCCqGSIb3 +DQMHMA4GCCqGSIb3DQMCAgIAgDANBggqhkiG9w0DAgIBQDAHBgUrDgMCBzANBggq +hkiG9w0DAgIBKDANBgkqhkiG9w0BAQEFAASCAQCda8b7o1a3/12TBKbRDLoAW5sm +1MBd1j0huWs+wTdj6G3q0cOAPJ2OxZuNfZnUwce+CNAWsKyNyPXIm9k997yW837b +e//lUIXPh8b12hUM6te298xvNqCdNNA0Y3/ihNZvb0fbl4nJfu0X+QMo2VqcFI6w +cSRBcbMB1/pB47AZF1qOR1+WlvxWTfJ1gHRMvpgtmd5NwNx96jM4i8yMxa4zoXmW +ROlOHYcNSDpVkkuhH+m60zxk52vOdTmOdg6CY+rFcMrgY6R2qZu/sfQrWAFiKOYl +CSgqvp/pPEty15Kt8inC+DYrIDNdlLg9A1RPpV+H4XxTSgRiEPTFbPKdOjG/ + +------011A3E8D1DC66D3261BBFB3EB4674ACD-- + diff --git a/crates/smime/testdata/noattr.eml b/crates/smime/testdata/noattr.eml new file mode 100644 index 000000000..0a5d7dad1 --- /dev/null +++ b/crates/smime/testdata/noattr.eml @@ -0,0 +1,56 @@ +To: bob@smime.example +From: alice@smime.example +Subject: No attributes +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-256"; boundary="----9D215F381F61DA9DBEC8E6CEAF3E2E88" + +This is an S/MIME signed message + +------9D215F381F61DA9DBEC8E6CEAF3E2E88 +Content-Type: text/plain; charset=us-ascii + +Hello Bob, + +The minutes of Tuesday are attached in spirit. + +Alice + +------9D215F381F61DA9DBEC8E6CEAF3E2E88 +Content-Type: application/pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIIFogYJKoZIhvcNAQcCoIIFkzCCBY8CAQExDTALBglghkgBZQMEAgEwCwYJKoZI +hvcNAQcBoIID0zCCA88wggK3oAMCAQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJ +KoZIhvcNAQENBQAwVTENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMgV0cx +MTAvBgNVBAMTKFNhbXBsZSBMQU1QUyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkwIBcNMTkxMTIwMDY1NDE4WhgPMjA1MjA5MjcwNjU0MThaMDsxDTALBgNVBAoT +BElFVEYxETAPBgNVBAsTCExBTVBTIFdHMRcwFQYDVQQDEw5BbGljZSBMb3ZlbGFj +ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT0iehYOBY+TZp/T5K2 +KNI05Hwr+E3wP6XTvyi6WWyTgBK9LCOwI2juwdRrjFBSXkk7pWpjXwsA3A5GOtz0 +FpfgyC7OxsVcF7q4WHWZWleYXFKlQHJD73nQwXP968+A/3rBX7PhO0DBbZnfitOL +PgPEwjTtdg0VQQ6Wz+CRQ/YbHPKaw7aRphZO63dKvIKp4cQVtkWQHi6syTjGsgkL +cLNau5LZDQUdsGV+SAo3nBdWCRYV+I65x8Kf4hCxqqmjV3d/2NKRu0BXnDe/N+iD +z3X0zEoj0fqXgq4SWcC0nsG1lyyXt1TL270I6ATKRGJWiQVCCpDtc0NT6vdJ45bC +SzsCAwEAAaOBrzCBrDAMBgNVHRMBAf8EAjAAMBcGA1UdIAQQMA4wDAYKYIZIAWUD +AgEwATAeBgNVHREEFzAVgRNhbGljZUBzbWltZS5leGFtcGxlMBMGA1UdJQQMMAoG +CCsGAQUFBwMEMA4GA1UdDwEB/wQEAwIGwDAdBgNVHQ4EFgQUu/bMsi0dBhIcl64p +apAQ0yBmZnMwHwYDVR0jBBgwFoAUkTCOfAcXDKfxCShlNhpnHGh29FkwDQYJKoZI +hvcNAQENBQADggEBAHOJojanzqmgaSN3/gqSQ4cbbmdj/R40BEPr+gXT+xiidfZ2 +iLNwYyTneuK6AChwKfnNvOFb8lV1iffRTF/KtmVEDMR/sYeqAH83KM5p3el2lVh4 +OHhyI0qNuz5oShNaACSioQ23WxHGVy9vsdVfnbhsplrWg9NQ2WbpCmK+2oMh2oYl +0Z/wvXMt9cG6jbMvcdH4z0IOvg6mrYkKTM/RCGnumghxwYToj1OyD5Gs4D2IJCw+ +fX5ODxh52MbNRYXTus2ZPRPM8JXNQC4GWv4km3M4rKnJDd6hnoQ9rNeozIcBVyyb +QYjfrgg4DRvw9Ksk22OH4ConlB8f7R7s1LM2cSYxggGVMIIBkQIBATBsMFUxDTAL +BgNVBAoTBElFVEYxETAPBgNVBAsTCExBTVBTIFdHMTEwLwYDVQQDEyhTYW1wbGUg +TEFNUFMgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5AhM3QQV57XV/QqmiXDr0 ++GrOmqnXMAsGCWCGSAFlAwQCATANBgkqhkiG9w0BAQEFAASCAQB424lCX+hFmHkC +NtPDglt4jFneZge6fSFGI898+4Ve5+SehVpM2pmyugnk9NvpiEqI9ywInDENgbPc +lDxTkNSWoFRMAvexvyK91CLZ6E8oRur8unC6ZMMxcnpqbJqgJgW9BR4j8Q2octPv +IFwERtqcsNLuDx9kUh+MR6Z66rELQAesXzOiWMhqDwJKmQxNZqVu4k+BQqLmyHbK +BRS6uDN54Xgs7tHdFKhewEwoMLA+PEOTCpLcFRzWydywlxTJMMivqmEdvPC4R8pA +8XKDYA4k++6y9wjiq4e1Uc/+Ex/n6CgcJZNAo2qS8u0wIGfBL9xW9qEOnAI8wZPp +IoaGX1Qa + +------9D215F381F61DA9DBEC8E6CEAF3E2E88-- + diff --git a/crates/smime/testdata/nocerts.eml b/crates/smime/testdata/nocerts.eml new file mode 100644 index 000000000..69741fc90 --- /dev/null +++ b/crates/smime/testdata/nocerts.eml @@ -0,0 +1,40 @@ +To: bob@smime.example +From: alice@smime.example +Subject: No certificate +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-256"; boundary="----C714793EB4AEA5E36741725AF174BFC1" + +This is an S/MIME signed message + +------C714793EB4AEA5E36741725AF174BFC1 +Content-Type: text/plain; charset=us-ascii + +Hello Bob, + +The minutes of Tuesday are attached in spirit. + +Alice + +------C714793EB4AEA5E36741725AF174BFC1 +Content-Type: application/pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIICsgYJKoZIhvcNAQcCoIICozCCAp8CAQExDTALBglghkgBZQMEAgEwCwYJKoZI +hvcNAQcBMYICfDCCAngCAQEwbDBVMQ0wCwYDVQQKEwRJRVRGMREwDwYDVQQLEwhM +QU1QUyBXRzExMC8GA1UEAxMoU2FtcGxlIExBTVBTIFJTQSBDZXJ0aWZpY2F0aW9u +IEF1dGhvcml0eQITN0EFee11f0Kpolw69Phqzpqp1zALBglghkgBZQMEAgGggeQw +GAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMjYxMTA5 +MTIwOTUxWjAvBgkqhkiG9w0BCQQxIgQgpd47XK9W43g0XBneB6ES11oZAarzptGM +JcOx+gGBdqcweQYJKoZIhvcNAQkPMWwwajALBglghkgBZQMEASowCwYJYIZIAWUD +BAEWMAsGCWCGSAFlAwQBAjAKBggqhkiG9w0DBzAOBggqhkiG9w0DAgICAIAwDQYI +KoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwDQYJKoZIhvcNAQEB +BQAEggEAnQNd8e5Phn1idVWgZqoGUqKXZQF2ojmQ9duGv5gAIzTmOpI6l4WaKj4t +T2EFa8cwQaIVhFz9ZKshEPSDep9y7IukzVi379CuHRonelJ9rwPQhkX7KLJVfnmh +AFc5XH9AdVxHPvpnP59ZankXO6MvzVO9kYKQdflZC8gv5Bl7Sh+FpS/0VGPEXNH+ +tkRGeX2jo5YY5Xsj2gGTBbiZQ07urn+dcETJxeGI+cLa5tkg3YBeLKthGEMekv9t +JakkfMsvpMW5m4TsiOz0A8gBrk5zP5YWEU+h+jKvSlQXyYcGbU04+Ir+y0HSa2ob +KUozlJlOmmhYzeok0wAsFf+V6qipCg== + +------C714793EB4AEA5E36741725AF174BFC1-- + diff --git a/crates/smime/testdata/opaque-ber.eml b/crates/smime/testdata/opaque-ber.eml new file mode 100644 index 000000000..e6b171749 --- /dev/null +++ b/crates/smime/testdata/opaque-ber.eml @@ -0,0 +1,47 @@ +To: bob@smime.example +From: alice@smime.example +Subject: Opaque minutes +MIME-Version: 1.0 +Content-Disposition: attachment; filename="smime.p7m" +Content-Type: application/pkcs7-mime; smime-type=signed-data; name="smime.p7m" +Content-Transfer-Encoding: base64 + +MIAGCSqGSIb3DQEHAqCAMIACAQExDTALBglghkgBZQMEAgEwgAYJKoZIhvcNAQcB +oIAkgAR1Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PXVzLWFzY2lp +DQoNCkhlbGxvIEJvYiwNCg0KVGhlIG1pbnV0ZXMgb2YgVHVlc2RheSBhcmUgYXR0 +YWNoZWQgaW4gc3Bpcml0Lg0KDQpBbGljZQ0KAAAAAAAAoIID0zCCA88wggK3oAMC +AQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJKoZIhvcNAQENBQAwVTENMAsGA1UE +ChMESUVURjERMA8GA1UECxMITEFNUFMgV0cxMTAvBgNVBAMTKFNhbXBsZSBMQU1Q +UyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwIBcNMTkxMTIwMDY1NDE4WhgP +MjA1MjA5MjcwNjU0MThaMDsxDTALBgNVBAoTBElFVEYxETAPBgNVBAsTCExBTVBT +IFdHMRcwFQYDVQQDEw5BbGljZSBMb3ZlbGFjZTCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBALT0iehYOBY+TZp/T5K2KNI05Hwr+E3wP6XTvyi6WWyTgBK9 +LCOwI2juwdRrjFBSXkk7pWpjXwsA3A5GOtz0FpfgyC7OxsVcF7q4WHWZWleYXFKl +QHJD73nQwXP968+A/3rBX7PhO0DBbZnfitOLPgPEwjTtdg0VQQ6Wz+CRQ/YbHPKa +w7aRphZO63dKvIKp4cQVtkWQHi6syTjGsgkLcLNau5LZDQUdsGV+SAo3nBdWCRYV ++I65x8Kf4hCxqqmjV3d/2NKRu0BXnDe/N+iDz3X0zEoj0fqXgq4SWcC0nsG1lyyX +t1TL270I6ATKRGJWiQVCCpDtc0NT6vdJ45bCSzsCAwEAAaOBrzCBrDAMBgNVHRMB +Af8EAjAAMBcGA1UdIAQQMA4wDAYKYIZIAWUDAgEwATAeBgNVHREEFzAVgRNhbGlj +ZUBzbWltZS5leGFtcGxlMBMGA1UdJQQMMAoGCCsGAQUFBwMEMA4GA1UdDwEB/wQE +AwIGwDAdBgNVHQ4EFgQUu/bMsi0dBhIcl64papAQ0yBmZnMwHwYDVR0jBBgwFoAU +kTCOfAcXDKfxCShlNhpnHGh29FkwDQYJKoZIhvcNAQENBQADggEBAHOJojanzqmg +aSN3/gqSQ4cbbmdj/R40BEPr+gXT+xiidfZ2iLNwYyTneuK6AChwKfnNvOFb8lV1 +iffRTF/KtmVEDMR/sYeqAH83KM5p3el2lVh4OHhyI0qNuz5oShNaACSioQ23WxHG +Vy9vsdVfnbhsplrWg9NQ2WbpCmK+2oMh2oYl0Z/wvXMt9cG6jbMvcdH4z0IOvg6m +rYkKTM/RCGnumghxwYToj1OyD5Gs4D2IJCw+fX5ODxh52MbNRYXTus2ZPRPM8JXN +QC4GWv4km3M4rKnJDd6hnoQ9rNeozIcBVyybQYjfrgg4DRvw9Ksk22OH4ConlB8f +7R7s1LM2cSYxggJ8MIICeAIBATBsMFUxDTALBgNVBAoTBElFVEYxETAPBgNVBAsT +CExBTVBTIFdHMTEwLwYDVQQDEyhTYW1wbGUgTEFNUFMgUlNBIENlcnRpZmljYXRp +b24gQXV0aG9yaXR5AhM3QQV57XV/QqmiXDr0+GrOmqnXMAsGCWCGSAFlAwQCAaCB +5DAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0yNjEx +MDkxMjA5NTFaMC8GCSqGSIb3DQEJBDEiBCCl3jtcr1bjeDRcGd4HoRLXWhkBqvOm +0Ywlw7H6AYF2pzB5BgkqhkiG9w0BCQ8xbDBqMAsGCWCGSAFlAwQBKjALBglghkgB +ZQMEARYwCwYJYIZIAWUDBAECMAoGCCqGSIb3DQMHMA4GCCqGSIb3DQMCAgIAgDAN +BggqhkiG9w0DAgIBQDAHBgUrDgMCBzANBggqhkiG9w0DAgIBKDANBgkqhkiG9w0B +AQEFAASCAQCdA13x7k+GfWJ1VaBmqgZSopdlAXaiOZD124a/mAAjNOY6kjqXhZoq +Pi1PYQVrxzBBohWEXP1kqyEQ9IN6n3Lsi6TNWLfv0K4dGid6Un2vA9CGRfsoslV+ +eaEAVzlcf0B1XEc++mc/n1lqeRc7oy/NU72RgpB1+VkLyC/kGXtKH4WlL/RUY8Rc +0f62REZ5faOjlhjleyPaAZMFuJlDTu6uf51wRMnF4Yj5wtrm2SDdgF4sq2EYQx6S +/20lqSR8yy+kxbmbhOyI7PQDyAGuTnM/lhYRT6H6Mq9KVBfJhwZtTTj4iv7LQdJr +ahspSjOUmU6aaFjN6iTTACwV/5XqqKkKAAAAAAAA + diff --git a/crates/smime/testdata/opaque.eml b/crates/smime/testdata/opaque.eml new file mode 100644 index 000000000..226af352b --- /dev/null +++ b/crates/smime/testdata/opaque.eml @@ -0,0 +1,47 @@ +To: bob@smime.example +From: alice@smime.example +Subject: Opaque minutes +MIME-Version: 1.0 +Content-Disposition: attachment; filename="smime.p7m" +Content-Type: application/pkcs7-mime; smime-type=signed-data; name="smime.p7m" +Content-Transfer-Encoding: base64 + +MIIHAwYJKoZIhvcNAQcCoIIG9DCCBvACAQExDTALBglghkgBZQMEAgEwgYQGCSqG +SIb3DQEHAaB3BHVDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9dXMt +YXNjaWkNCg0KSGVsbG8gQm9iLA0KDQpUaGUgbWludXRlcyBvZiBUdWVzZGF5IGFy +ZSBhdHRhY2hlZCBpbiBzcGlyaXQuDQoNCkFsaWNlDQqgggPTMIIDzzCCAregAwIB +AgITN0EFee11f0Kpolw69Phqzpqp1zANBgkqhkiG9w0BAQ0FADBVMQ0wCwYDVQQK +EwRJRVRGMREwDwYDVQQLEwhMQU1QUyBXRzExMC8GA1UEAxMoU2FtcGxlIExBTVBT +IFJTQSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAgFw0xOTExMjAwNjU0MThaGA8y +MDUyMDkyNzA2NTQxOFowOzENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMg +V0cxFzAVBgNVBAMTDkFsaWNlIExvdmVsYWNlMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEAtPSJ6Fg4Fj5Nmn9PkrYo0jTkfCv4TfA/pdO/KLpZbJOAEr0s +I7AjaO7B1GuMUFJeSTulamNfCwDcDkY63PQWl+DILs7GxVwXurhYdZlaV5hcUqVA +ckPvedDBc/3rz4D/esFfs+E7QMFtmd+K04s+A8TCNO12DRVBDpbP4JFD9hsc8prD +tpGmFk7rd0q8gqnhxBW2RZAeLqzJOMayCQtws1q7ktkNBR2wZX5ICjecF1YJFhX4 +jrnHwp/iELGqqaNXd3/Y0pG7QFecN7836IPPdfTMSiPR+peCrhJZwLSewbWXLJe3 +VMvbvQjoBMpEYlaJBUIKkO1zQ1Pq90njlsJLOwIDAQABo4GvMIGsMAwGA1UdEwEB +/wQCMAAwFwYDVR0gBBAwDjAMBgpghkgBZQMCATABMB4GA1UdEQQXMBWBE2FsaWNl +QHNtaW1lLmV4YW1wbGUwEwYDVR0lBAwwCgYIKwYBBQUHAwQwDgYDVR0PAQH/BAQD +AgbAMB0GA1UdDgQWBBS79syyLR0GEhyXrilqkBDTIGZmczAfBgNVHSMEGDAWgBSR +MI58BxcMp/EJKGU2GmccaHb0WTANBgkqhkiG9w0BAQ0FAAOCAQEAc4miNqfOqaBp +I3f+CpJDhxtuZ2P9HjQEQ+v6BdP7GKJ19naIs3BjJOd64roAKHAp+c284VvyVXWJ +99FMX8q2ZUQMxH+xh6oAfzcozmnd6XaVWHg4eHIjSo27PmhKE1oAJKKhDbdbEcZX +L2+x1V+duGymWtaD01DZZukKYr7agyHahiXRn/C9cy31wbqNsy9x0fjPQg6+Dqat +iQpMz9EIae6aCHHBhOiPU7IPkazgPYgkLD59fk4PGHnYxs1FhdO6zZk9E8zwlc1A +LgZa/iSbczisqckN3qGehD2s16jMhwFXLJtBiN+uCDgNG/D0qyTbY4fgKieUHx/t +HuzUszZxJjGCAnwwggJ4AgEBMGwwVTENMAsGA1UEChMESUVURjERMA8GA1UECxMI +TEFNUFMgV0cxMTAvBgNVBAMTKFNhbXBsZSBMQU1QUyBSU0EgQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkCEzdBBXntdX9CqaJcOvT4as6aqdcwCwYJYIZIAWUDBAIBoIHk +MBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTI2MTEw +OTEyMDk1MVowLwYJKoZIhvcNAQkEMSIEIKXeO1yvVuN4NFwZ3gehEtdaGQGq86bR +jCXDsfoBgXanMHkGCSqGSIb3DQEJDzFsMGowCwYJYIZIAWUDBAEqMAsGCWCGSAFl +AwQBFjALBglghkgBZQMEAQIwCgYIKoZIhvcNAwcwDgYIKoZIhvcNAwICAgCAMA0G +CCqGSIb3DQMCAgFAMAcGBSsOAwIHMA0GCCqGSIb3DQMCAgEoMA0GCSqGSIb3DQEB +AQUABIIBAJ0DXfHuT4Z9YnVVoGaqBlKil2UBdqI5kPXbhr+YACM05jqSOpeFmio+ +LU9hBWvHMEGiFYRc/WSrIRD0g3qfcuyLpM1Yt+/Qrh0aJ3pSfa8D0IZF+yiyVX55 +oQBXOVx/QHVcRz76Zz+fWWp5FzujL81TvZGCkHX5WQvIL+QZe0ofhaUv9FRjxFzR +/rZERnl9o6OWGOV7I9oBkwW4mUNO7q5/nXBEycXhiPnC2ubZIN2AXiyrYRhDHpL/ +bSWpJHzLL6TFuZuE7Ijs9APIAa5Ocz+WFhFPofoyr0pUF8mHBm1NOPiK/stB0mtq +GylKM5SZTppoWM3qJNMALBX/leqoqQo= + diff --git a/crates/smime/testdata/pss.eml b/crates/smime/testdata/pss.eml new file mode 100644 index 000000000..1fa054da5 --- /dev/null +++ b/crates/smime/testdata/pss.eml @@ -0,0 +1,62 @@ +To: bob@smime.example +From: alice@smime.example +Subject: PSS minutes +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-384"; boundary="----E33A7E587DACB5F6484402726C200129" + +This is an S/MIME signed message + +------E33A7E587DACB5F6484402726C200129 +Content-Type: text/plain; charset=us-ascii + +Hello Bob, + +The minutes of Tuesday are attached in spirit. + +Alice + +------E33A7E587DACB5F6484402726C200129 +Content-Type: application/pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIIGzQYJKoZIhvcNAQcCoIIGvjCCBroCAQExDTALBglghkgBZQMEAgIwCwYJKoZI +hvcNAQcBoIID0zCCA88wggK3oAMCAQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJ +KoZIhvcNAQENBQAwVTENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMgV0cx +MTAvBgNVBAMTKFNhbXBsZSBMQU1QUyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkwIBcNMTkxMTIwMDY1NDE4WhgPMjA1MjA5MjcwNjU0MThaMDsxDTALBgNVBAoT +BElFVEYxETAPBgNVBAsTCExBTVBTIFdHMRcwFQYDVQQDEw5BbGljZSBMb3ZlbGFj +ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT0iehYOBY+TZp/T5K2 +KNI05Hwr+E3wP6XTvyi6WWyTgBK9LCOwI2juwdRrjFBSXkk7pWpjXwsA3A5GOtz0 +FpfgyC7OxsVcF7q4WHWZWleYXFKlQHJD73nQwXP968+A/3rBX7PhO0DBbZnfitOL +PgPEwjTtdg0VQQ6Wz+CRQ/YbHPKaw7aRphZO63dKvIKp4cQVtkWQHi6syTjGsgkL +cLNau5LZDQUdsGV+SAo3nBdWCRYV+I65x8Kf4hCxqqmjV3d/2NKRu0BXnDe/N+iD +z3X0zEoj0fqXgq4SWcC0nsG1lyyXt1TL270I6ATKRGJWiQVCCpDtc0NT6vdJ45bC +SzsCAwEAAaOBrzCBrDAMBgNVHRMBAf8EAjAAMBcGA1UdIAQQMA4wDAYKYIZIAWUD +AgEwATAeBgNVHREEFzAVgRNhbGljZUBzbWltZS5leGFtcGxlMBMGA1UdJQQMMAoG +CCsGAQUFBwMEMA4GA1UdDwEB/wQEAwIGwDAdBgNVHQ4EFgQUu/bMsi0dBhIcl64p +apAQ0yBmZnMwHwYDVR0jBBgwFoAUkTCOfAcXDKfxCShlNhpnHGh29FkwDQYJKoZI +hvcNAQENBQADggEBAHOJojanzqmgaSN3/gqSQ4cbbmdj/R40BEPr+gXT+xiidfZ2 +iLNwYyTneuK6AChwKfnNvOFb8lV1iffRTF/KtmVEDMR/sYeqAH83KM5p3el2lVh4 +OHhyI0qNuz5oShNaACSioQ23WxHGVy9vsdVfnbhsplrWg9NQ2WbpCmK+2oMh2oYl +0Z/wvXMt9cG6jbMvcdH4z0IOvg6mrYkKTM/RCGnumghxwYToj1OyD5Gs4D2IJCw+ +fX5ODxh52MbNRYXTus2ZPRPM8JXNQC4GWv4km3M4rKnJDd6hnoQ9rNeozIcBVyyb +QYjfrgg4DRvw9Ksk22OH4ConlB8f7R7s1LM2cSYxggLAMIICvAIBATBsMFUxDTAL +BgNVBAoTBElFVEYxETAPBgNVBAsTCExBTVBTIFdHMTEwLwYDVQQDEyhTYW1wbGUg +TEFNUFMgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5AhM3QQV57XV/QqmiXDr0 ++GrOmqnXMAsGCWCGSAFlAwQCAqCB9DAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcB +MBwGCSqGSIb3DQEJBTEPFw0yNjExMDkxMjA5NTFaMD8GCSqGSIb3DQEJBDEyBDD4 +2qGCADijATcenlkhPijI4rlMODPEVAYYj23MDi+U5OoGk43dPeqaLE2/OuP3d9Ew +eQYJKoZIhvcNAQkPMWwwajALBglghkgBZQMEASowCwYJYIZIAWUDBAEWMAsGCWCG +SAFlAwQBAjAKBggqhkiG9w0DBzAOBggqhkiG9w0DAgICAIAwDQYIKoZIhvcNAwIC +AUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwQQYJKoZIhvcNAQEKMDSgDzANBglg +hkgBZQMEAgIFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgIFAKIDAgEwBIIB +AFYJfuEecetLuIAZBdhyppBpqzeF9JN9RuGyi7qmrUFFU8xSyNh8/NFFE7UJ91Eo ++/zbQkuz0lfak8NSA1dw+qr2LnmnvpjD7LelEDJawTWJwzFnAVQaW7PaduLBwxZU +WmJRV6h4UZ1YEh8XEjpCqeUHTfqSiEyCaw0XOct6UoPOZQ64/7ytBOwrMUdMZNO5 +upqKR/NZSTwG91Izy78ORpW97ckbFcsklPOedHypUuecJTK5gzMEh2w5TGYZGRNs +x2kz6OqzzdhMUdT9DG84PGmZDTrp+Gw8lBWCUJs/1AMYm8ZKx/eSJwasJpeGaFUS +gPrYtiiA1mEl+vujBbhlwSo= + +------E33A7E587DACB5F6484402726C200129-- + diff --git a/crates/smime/testdata/sha1.eml b/crates/smime/testdata/sha1.eml new file mode 100644 index 000000000..3a25ad941 --- /dev/null +++ b/crates/smime/testdata/sha1.eml @@ -0,0 +1,60 @@ +To: bob@smime.example +From: alice@smime.example +Subject: Old minutes +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha1"; boundary="----C0EDEE0A5F012496F372EFC5533B6179" + +This is an S/MIME signed message + +------C0EDEE0A5F012496F372EFC5533B6179 +Content-Type: text/plain; charset=us-ascii + +Hello Bob, + +The minutes of Tuesday are attached in spirit. + +Alice + +------C0EDEE0A5F012496F372EFC5533B6179 +Content-Type: application/pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIIGdQYJKoZIhvcNAQcCoIIGZjCCBmICAQExCTAHBgUrDgMCGjALBgkqhkiG9w0B +BwGgggPTMIIDzzCCAregAwIBAgITN0EFee11f0Kpolw69Phqzpqp1zANBgkqhkiG +9w0BAQ0FADBVMQ0wCwYDVQQKEwRJRVRGMREwDwYDVQQLEwhMQU1QUyBXRzExMC8G +A1UEAxMoU2FtcGxlIExBTVBTIFJTQSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAg +Fw0xOTExMjAwNjU0MThaGA8yMDUyMDkyNzA2NTQxOFowOzENMAsGA1UEChMESUVU +RjERMA8GA1UECxMITEFNUFMgV0cxFzAVBgNVBAMTDkFsaWNlIExvdmVsYWNlMIIB +IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtPSJ6Fg4Fj5Nmn9PkrYo0jTk +fCv4TfA/pdO/KLpZbJOAEr0sI7AjaO7B1GuMUFJeSTulamNfCwDcDkY63PQWl+DI +Ls7GxVwXurhYdZlaV5hcUqVAckPvedDBc/3rz4D/esFfs+E7QMFtmd+K04s+A8TC +NO12DRVBDpbP4JFD9hsc8prDtpGmFk7rd0q8gqnhxBW2RZAeLqzJOMayCQtws1q7 +ktkNBR2wZX5ICjecF1YJFhX4jrnHwp/iELGqqaNXd3/Y0pG7QFecN7836IPPdfTM +SiPR+peCrhJZwLSewbWXLJe3VMvbvQjoBMpEYlaJBUIKkO1zQ1Pq90njlsJLOwID +AQABo4GvMIGsMAwGA1UdEwEB/wQCMAAwFwYDVR0gBBAwDjAMBgpghkgBZQMCATAB +MB4GA1UdEQQXMBWBE2FsaWNlQHNtaW1lLmV4YW1wbGUwEwYDVR0lBAwwCgYIKwYB +BQUHAwQwDgYDVR0PAQH/BAQDAgbAMB0GA1UdDgQWBBS79syyLR0GEhyXrilqkBDT +IGZmczAfBgNVHSMEGDAWgBSRMI58BxcMp/EJKGU2GmccaHb0WTANBgkqhkiG9w0B +AQ0FAAOCAQEAc4miNqfOqaBpI3f+CpJDhxtuZ2P9HjQEQ+v6BdP7GKJ19naIs3Bj +JOd64roAKHAp+c284VvyVXWJ99FMX8q2ZUQMxH+xh6oAfzcozmnd6XaVWHg4eHIj +So27PmhKE1oAJKKhDbdbEcZXL2+x1V+duGymWtaD01DZZukKYr7agyHahiXRn/C9 +cy31wbqNsy9x0fjPQg6+DqatiQpMz9EIae6aCHHBhOiPU7IPkazgPYgkLD59fk4P +GHnYxs1FhdO6zZk9E8zwlc1ALgZa/iSbczisqckN3qGehD2s16jMhwFXLJtBiN+u +CDgNG/D0qyTbY4fgKieUHx/tHuzUszZxJjGCAmwwggJoAgEBMGwwVTENMAsGA1UE +ChMESUVURjERMA8GA1UECxMITEFNUFMgV0cxMTAvBgNVBAMTKFNhbXBsZSBMQU1Q +UyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkCEzdBBXntdX9CqaJcOvT4as6a +qdcwBwYFKw4DAhqggdgwGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG +9w0BCQUxDxcNMjYxMTA5MTIwOTUxWjAjBgkqhkiG9w0BCQQxFgQU7fMLLzqCEOLs +sYLIvwK6bSUQpwQweQYJKoZIhvcNAQkPMWwwajALBglghkgBZQMEASowCwYJYIZI +AWUDBAEWMAsGCWCGSAFlAwQBAjAKBggqhkiG9w0DBzAOBggqhkiG9w0DAgICAIAw +DQYIKoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwDQYJKoZIhvcN +AQEBBQAEggEApwr9S+87L4Z+UZdVtuNmWH0eLmERMX6KTQ+zrlDxpXCq0ZPFkB7E +UijWdUoaWHOuwQbQac1tAoC9jP5cdpI9S3BB4QySECdzDOg6djzEnFEYrqddCKGY +nQswbRP/+mTMzN+lxO4kYjiHfb34egKPjgBiX6kUCpoxEZeV6joAtFRgBnkbUL4H +B2R+aiYiJt5jO1kB5beMf/gSFoIaycOf3EuTifNpPm2LsNGuEFZ72CRl2aHs2njc +O6XSZr8kODvUsPKJlXeqtThamr7Iy3NRvxQjDPFiW6i3TW9eo1/1LKSpDjjP8qet +p+iNds1neRoqaaDEkLifdykzuBLA0Sig8Q== + +------C0EDEE0A5F012496F372EFC5533B6179-- + diff --git a/crates/stream-codecs/src/ccitt.rs b/crates/stream-codecs/src/ccitt.rs index 2733cf98b..c5a213cea 100644 --- a/crates/stream-codecs/src/ccitt.rs +++ b/crates/stream-codecs/src/ccitt.rs @@ -152,6 +152,76 @@ fn starts_with_end_of_line(data: &[u8]) -> bool { /// Rows of 1-bit samples filled from a decoder's pixels: `columns` a row, each row on a new byte, at /// most `rows` rows. Pixels past a row's end and rows past the last are dropped. +/// Reason a raw CCITT fax decode stopped or failed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CcittErrorKind { + UnexpectedEof, + Overflow, + InvalidData, +} + +impl std::fmt::Display for CcittErrorKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UnexpectedEof => f.write_str("unexpected end of CCITT stream"), + Self::Overflow => f.write_str("CCITT stream overflow"), + Self::InvalidData => f.write_str("invalid CCITT data"), + } + } +} + +/// Result of [`decode_ccitt_raw`], including any partial rows decoded before an error. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CcittRawOutput { + pub data: Vec<u8>, + pub rows_decoded: u32, + pub bytes_consumed: usize, + pub error: Option<CcittErrorKind>, +} + +/// Decodes CCITT Group 3 or Group 4 fax `data` with caller-specified `params` and `max_rows`, +/// returning packed MSB-first rows, rows decoded, input bytes consumed, and any decode error. +pub fn decode_ccitt_raw(data: &[u8], p: &CcittParams, max_rows: u32) -> Result<CcittRawOutput, CodecError> { + if p.columns <= 0 || p.columns > i64::from(MAX_CCITT_COLUMNS) { + return Err(CodecError::Corrupt { filter: "CCITTFaxDecode", detail: format!("CCITT columns {} outside 1..={MAX_CCITT_COLUMNS}", p.columns) }); + } + let columns = u32::try_from(p.columns).map_err(|_| CodecError::Corrupt { filter: "CCITTFaxDecode", detail: "invalid CCITT columns".into() })?; + let rows = if p.rows > 0 { u32::try_from(p.rows).unwrap_or(max_rows).min(max_rows) } else { max_rows }; + let settings = hayro_ccitt::DecodeSettings { + columns, + rows, + end_of_block: p.end_of_block, + end_of_line: p.end_of_line, + rows_are_byte_aligned: p.encoded_byte_align && (p.k < 0 || !starts_with_end_of_line(data)), + encoding: match p.k { + ..0 => hayro_ccitt::EncodingMode::Group4, + 0 => hayro_ccitt::EncodingMode::Group3_1D, + k => hayro_ccitt::EncodingMode::Group3_2D { k: u32::try_from(k).unwrap_or(u32::MAX) }, + }, + invert_black: false, + }; + let mut out = Rows::new(columns as usize, rows as usize, p.black_is_1); + let (bytes_consumed, error) = match hayro_ccitt::decode(data, &mut out, &mut hayro_ccitt::DecoderContext::new(settings)) { + Ok(used) => (used, None), + Err(e) => { + let kind = match e { + hayro_ccitt::DecodeError::UnexpectedEof => CcittErrorKind::UnexpectedEof, + hayro_ccitt::DecodeError::Overflow => CcittErrorKind::Overflow, + _ => CcittErrorKind::InvalidData, + }; + let used = if out.done > 0 { + let mut drop_rows = Rows::new(columns as usize, out.done, p.black_is_1); + let retry = hayro_ccitt::DecodeSettings { rows: u32::try_from(out.done).unwrap_or(u32::MAX), ..settings }; + hayro_ccitt::decode(data, &mut drop_rows, &mut hayro_ccitt::DecoderContext::new(retry)).unwrap_or(data.len()) + } else { + 0 + }; + (used, Some(kind)) + } + }; + Ok(CcittRawOutput { data: out.out, rows_decoded: u32::try_from(out.done).unwrap_or(u32::MAX), bytes_consumed, error }) +} + pub(crate) struct Rows { pub(crate) out: Vec<u8>, row: Vec<u8>, diff --git a/crates/stream-codecs/src/lib.rs b/crates/stream-codecs/src/lib.rs index d129cacaa..ee275b2ce 100644 --- a/crates/stream-codecs/src/lib.rs +++ b/crates/stream-codecs/src/lib.rs @@ -42,7 +42,7 @@ mod mq; pub mod predictor; pub mod runlength; -pub use ccitt::{CcittParams, MAX_CCITT_COLUMNS, MAX_G4_COLUMNS, decode_ccitt_within, encode_g4}; +pub use ccitt::{CcittErrorKind, CcittParams, CcittRawOutput, MAX_CCITT_COLUMNS, MAX_G4_COLUMNS, decode_ccitt_raw, decode_ccitt_within, encode_g4}; pub use jbig2::{MAX_JBIG2_COLUMNS, MAX_JBIG2_PIXELS, SharedJbig2, decode_jbig2_within, encode_jbig2, encode_jbig2_generic, encode_jbig2_shared}; /// Parameters of the predictors and of LZW, as a PDF `/DecodeParms` dictionary gives them diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 3d20a0e5b..3615a719c 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -18,6 +18,8 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"] kurbo = { workspace = true } roxmltree = "0.21.2" thiserror = { workspace = true } +vectorcraft-geom = { workspace = true } +vectorcraft-pathops = { workspace = true } # The full SVG parser (Apache-2.0 OR MIT). The one version every Craft app uses: apps depend on # craft-svg's `tree` feature and take usvg from its re-export, never directly. usvg = { version = "=0.48.1", default-features = false, optional = true } @@ -25,9 +27,11 @@ usvg = { version = "=0.48.1", default-features = false, optional = true } # so callers that only need bounded SVG text/tree parsing do not pull in raster backends. resvg = { version = "=0.48.1", default-features = false, features = ["text", "raster-images"], optional = true } +data-url = { version = "0.3.2", optional = true } + [features] # `craft_svg::tree`: usvg behind the bounded entry point. -tree = ["dep:usvg"] +tree = ["dep:usvg", "dep:data-url"] # Text converted to paths (needs a font database in the options). tree-text = ["tree", "usvg/text"] # The system's fonts in `usvg::fontdb`. diff --git a/crates/svg/src/paths.rs b/crates/svg/src/paths.rs index e909283fd..504a1dd1b 100644 --- a/crates/svg/src/paths.rs +++ b/crates/svg/src/paths.rs @@ -6,12 +6,11 @@ //! millimetres, with its stroke paint and the clip regions that apply to it. The caller tags //! shapes through [`Kind`] (cut or engrave, layer, pen…) from each element's computed style and //! class. Input is treated as hostile: size, node, depth and instance limits, and cyclic -//! references, are errors. -//! -//! Geometry only. Boolean operations (applying [`Clip`]s) are left to the caller. Stroke paint -//! is returned as written; [`crate::color::parse_color`] reads it as a CSS colour. +//! references, are errors. [`Imported::clipped_path`] applies the collected clip regions with +//! their SVG fill rules. Stroke paint is returned as written; [`crate::color::parse_color`] +//! reads it as a CSS colour. -use kurbo::BezPath; +use kurbo::{BezPath, PathEl, Point, Shape as _}; /// Why an SVG could not be read; the message starts with the name given to [`import`]. #[derive(Debug, thiserror::Error)] @@ -60,7 +59,7 @@ pub struct Clip { pub pieces: Vec<(BezPath, FillRule)>, } -/// One drawable element, transformed into the document's millimetre space and not yet clipped. +/// One drawable element, transformed into the document's millimetre space. #[derive(Debug, Clone, PartialEq)] pub struct Shape<K> { pub path: BezPath, @@ -70,6 +69,12 @@ pub struct Shape<K> { /// The stroke colour as written (`currentColor` and paint-server fallbacks resolved), or /// `None` without a stroke. pub stroke: Option<String>, + /// Whether the computed style paints the path interior (`fill` defaults to black). + pub has_fill: bool, + /// Whether the computed style paints a stroke. + pub has_stroke: bool, + /// The computed `fill-rule`, defaulting to SVG's `nonzero` rule. + pub fill_rule: FillRule, /// The regions the shape is clipped by, as indices into [`Imported::clips`], outermost first. pub clips: Vec<usize>, /// The name of the innermost Inkscape layer the element is in: a `<g>` with @@ -96,6 +101,275 @@ pub struct Imported<K> { pub dropped_warnings: usize, } +impl<K> Imported<K> { + /// Return one imported shape with every applicable SVG `clip-path` applied. + /// + /// Clip geometry is evaluated here so applications can map the resulting path into their own + /// document model without reimplementing SVG fill rules or boolean clipping. + pub fn clipped_path(&self, shape: &Shape<K>) -> Result<BezPath, Error> { + let mut path = shape.path.clone(); + let mut work_left = MAX_CLIP_WORK; + let mut output_left = MAX_CLIPPED_POINTS; + for &clip_index in &shape.clips { + let clip = self.clips.get(clip_index).ok_or_else(|| Error("SVG shape refers to a missing clip region".into()))?; + path = apply_clip(&path, clip, shape.has_fill, shape.has_stroke, shape.fill_rule, &mut work_left, &mut output_left)?; + } + Ok(path) + } +} + +fn apply_clip( + path: &BezPath, + clip: &Clip, + has_fill: bool, + has_stroke: bool, + fill_rule: FillRule, + work_left: &mut usize, + output_left: &mut usize, +) -> Result<BezPath, Error> { + if clip.pieces.is_empty() { + return Ok(BezPath::new()); + } + let pieces: Vec<_> = clip + .pieces + .iter() + .map(|(path, rule)| { + ( + vectorcraft_geom::PathData::from_bezpath(path), + match rule { + FillRule::EvenOdd => vectorcraft_geom::FillRule::EvenOdd, + FillRule::NonZero => vectorcraft_geom::FillRule::NonZero, + }, + ) + }) + .collect(); + let inputs: Vec<_> = pieces.iter().map(|(path, rule)| (path, *rule)).collect(); + let region = vectorcraft_pathops::try_boolean_n(&inputs, |inside: &[bool]| inside.iter().any(|v| *v)) + .map_err(|e| Error(format!("SVG clip-path: {e}")))? + .to_bezpath(); + clip_path_to_region(path, &region, has_fill, has_stroke, fill_rule, work_left, output_left).map_err(|e| Error(format!("SVG clip-path: {e}"))) +} + +fn clip_path_to_region( + path: &BezPath, + region: &BezPath, + has_fill: bool, + has_stroke: bool, + fill_rule: FillRule, + work_left: &mut usize, + output_left: &mut usize, +) -> Result<BezPath, String> { + if region.elements().is_empty() { + return Ok(BezPath::new()); + } + let mut out = BezPath::new(); + if has_fill { + let kept = vectorcraft_pathops::try_boolean( + &vectorcraft_geom::PathData::from_bezpath(path), + match fill_rule { + FillRule::EvenOdd => vectorcraft_geom::FillRule::EvenOdd, + FillRule::NonZero => vectorcraft_geom::FillRule::NonZero, + }, + &vectorcraft_geom::PathData::from_bezpath(region), + vectorcraft_geom::FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + 0.001, + ) + .map_err(|e| e.to_string())?; + out.extend(kept.to_bezpath()); + } + // Some callers deliberately retain geometry even when the source has no paint. Keep that + // geometry clip-able as linework instead of silently deleting it. + if has_stroke || (!has_fill && !has_stroke) { + let polygons: Vec<Vec<Point>> = + flatten_contours(region)?.into_iter().filter(|(points, closed)| *closed && points.len() >= 3).map(|(points, _)| points).collect(); + for (mut points, closed) in flatten_contours(path)? { + if closed + && points.len() > 1 + && points.first().zip(points.last()).is_some_and(|(first, last)| first.distance(*last) > 1e-9) + && let Some(first) = points.first().copied() + { + points.push(first); + } + for piece in clip_polyline(&points, &polygons, work_left, output_left)? { + let Some((&first, rest)) = piece.split_first() else { + continue; + }; + out.move_to(first); + for &point in rest { + out.line_to(point); + } + } + } + } + Ok(out) +} + +const MAX_CLIPPED_POINTS: usize = 500_000; +const MAX_CLIP_WORK: usize = 5_000_000; + +fn flatten_contours(path: &BezPath) -> Result<Vec<(Vec<Point>, bool)>, String> { + flatten_contours_with_limits(path, MAX_SVG_SEGMENTS, MAX_CLIPPED_POINTS) +} + +fn flatten_contours_with_limits(path: &BezPath, max_segments: usize, max_points: usize) -> Result<Vec<(Vec<Point>, bool)>, String> { + if path.elements().len() > max_segments { + return Err("path exceeds the SVG segment limit".into()); + } + let bounds = path.bounding_box(); + let tolerance = (bounds.width().max(bounds.height()) * 2e-4).max(1e-3); + let mut contours: Vec<(Vec<Point>, bool)> = Vec::new(); + let mut total = 0usize; + vectorcraft_geom::flatten(path.iter(), tolerance, |el| { + total = total.saturating_add(1); + if total > max_points { + return; + } + match el { + PathEl::MoveTo(point) => contours.push((vec![point], false)), + PathEl::LineTo(point) => { + if let Some((points, _)) = contours.last_mut() { + points.push(point); + } + } + PathEl::ClosePath => { + let start = if let Some((points, closed)) = contours.last_mut() { + if let Some(first) = points.first().copied() + && points.last().is_some_and(|last| last.distance(first) > 1e-9) + { + points.push(first); + } + *closed = true; + points.first().copied() + } else { + None + }; + if let Some(start) = start { + contours.push((vec![start], false)); + } + } + PathEl::QuadTo(..) | PathEl::CurveTo(..) => {} + } + }); + if total > max_points { + return Err(format!("path is too detailed (over {max_points} points)")); + } + for (points, _) in &mut contours { + points.dedup_by(|a, b| a.distance(*b) < 1e-9); + } + contours.retain(|(points, _)| points.len() > 1); + Ok(contours) +} + +fn clip_polyline(points: &[Point], polygons: &[Vec<Point>], work_left: &mut usize, output_left: &mut usize) -> Result<Vec<Vec<Point>>, String> { + let mut out: Vec<Vec<Point>> = Vec::new(); + let mut current: Vec<Point> = Vec::new(); + let mut ts = Vec::new(); + for segment in points.windows(2) { + let (a, b) = (segment[0], segment[1]); + ts.clear(); + ts.push(0.0); + crossings(polygons, a, b, &mut ts, work_left)?; + ts.push(1.0); + ts.sort_by(f64::total_cmp); + for pair in ts.windows(2) { + let (t0, t1) = (pair[0], pair[1]); + if t1 - t0 < 1e-12 { + continue; + } + if inside_even_odd(polygons, a.lerp(b, (t0 + t1) / 2.0), work_left)? { + let (p0, p1) = (a.lerp(b, t0), a.lerp(b, t1)); + if current.last().is_none_or(|last| last.distance(p0) > 1e-9) { + if current.len() > 1 { + out.push(std::mem::take(&mut current)); + } + current.clear(); + push_clip_point(&mut current, p0, output_left)?; + } + push_clip_point(&mut current, p1, output_left)?; + } else if current.len() > 1 { + out.push(std::mem::take(&mut current)); + } else { + current.clear(); + } + } + } + if current.len() > 1 { + out.push(current); + } + Ok(out) +} + +fn crossings(polygons: &[Vec<Point>], a: Point, b: Point, out: &mut Vec<f64>, work_left: &mut usize) -> Result<(), String> { + let direction = b - a; + for polygon in polygons { + for index in 0..polygon.len() { + charge_clip_work(work_left)?; + let (Some(p), Some(q)) = (polygon.get(index), polygon.get((index + 1) % polygon.len())) else { + continue; + }; + let edge = *q - *p; + let denominator = direction.cross(edge); + if denominator.abs() < 1e-15 { + continue; + } + let offset = *p - a; + let t = offset.cross(edge) / denominator; + let u = offset.cross(direction) / denominator; + if t > 0.0 && t < 1.0 && (0.0..1.0).contains(&u) { + out.push(t); + } + } + } + Ok(()) +} + +fn inside_even_odd(polygons: &[Vec<Point>], point: Point, work_left: &mut usize) -> Result<bool, String> { + let mut odd = false; + for polygon in polygons { + for index in 0..polygon.len() { + charge_clip_work(work_left)?; + let (Some(a), Some(b)) = (polygon.get(index), polygon.get((index + 1) % polygon.len())) else { + continue; + }; + let edge = *b - *a; + let relative = point - *a; + let length_squared = edge.dot(edge); + let edge_length = length_squared.sqrt(); + if edge_length <= f64::EPSILON { + if relative.x.hypot(relative.y) <= 1e-9 { + return Ok(true); + } + continue; + } + let tolerance = 1e-9 * edge_length.max(1.0); + let projection = relative.dot(edge); + let projection_tolerance = tolerance * edge_length; + if edge.cross(relative).abs() <= projection_tolerance + && projection >= -projection_tolerance + && projection <= length_squared + projection_tolerance + { + return Ok(true); + } + if (a.y > point.y) != (b.y > point.y) && point.x < a.x + (point.y - a.y) / (b.y - a.y) * (b.x - a.x) { + odd = !odd; + } + } + } + Ok(odd) +} + +fn charge_clip_work(work_left: &mut usize) -> Result<(), String> { + *work_left = work_left.checked_sub(1).ok_or_else(|| "clip-path work limit exceeded".to_string())?; + Ok(()) +} + +fn push_clip_point(points: &mut Vec<Point>, point: Point, output_left: &mut usize) -> Result<(), String> { + *output_left = output_left.checked_sub(1).ok_or_else(|| "clip-path output point limit exceeded".to_string())?; + points.push(point); + Ok(()) +} + pub const MAX_SVG_BYTES: usize = 16 * 1024 * 1024; pub const MAX_SVG_NODES: usize = 100_000; pub const MAX_SVG_DEPTH: usize = 128; @@ -151,7 +425,7 @@ pub(crate) const MAX_CSS_SELECTOR_CHECKS: usize = 5_000_000; /// presentation-property cascade. Curves stay curves: nothing is flattened. /// /// Each shape carries its stroke paint as written and the `clip-path` regions that apply to it; -/// parsing the colour and cutting the shape down to its clips are the caller's. +/// [`Imported::clipped_path`] returns its geometry with those clips applied. /// /// What cannot be represented is skipped with a line in [`Imported::warnings`]: `<text>` (no /// fonts here), masks and filters (the art comes unmasked and unfiltered), ignored CSS at-rules @@ -420,6 +694,9 @@ fn import_node<'a, 'input, K: Kind>( kind: state.kind.clone(), label: label(node), stroke: stroke_paint(&style), + has_fill: style.get("fill").is_none_or(|value| value != "none"), + has_stroke: style.get("stroke").is_some_and(|value| value != "none"), + fill_rule: if style.get("fill-rule").is_some_and(|value| value == "evenodd") { FillRule::EvenOdd } else { FillRule::NonZero }, clips: state.clips.clone(), layer: state.layer.as_deref().map(str::to_string), }); @@ -854,7 +1131,8 @@ fn ellipse_path(cx: f64, cy: f64, rx: f64, ry: f64) -> BezPath { pub const MAX_CSS_BYTES: usize = 1024 * 1024; const MAX_CSS_RULES: usize = 10_000; const MAX_CSS_PROPERTIES: usize = 32; -const SUPPORTED_STYLE_PROPERTIES: &[&str] = &["display", "visibility", "fill", "stroke", "stroke-width", "color", "clip-path", "mask", "filter"]; +const SUPPORTED_STYLE_PROPERTIES: &[&str] = + &["display", "visibility", "fill", "fill-rule", "stroke", "stroke-width", "color", "clip-path", "mask", "filter"]; /// Whether the cascade tracks `property`: the properties above and [`Kind::PROPERTIES`]. fn supported(extra: &[&str], property: &str) -> bool { @@ -1644,7 +1922,6 @@ fn svg_error(path_name: &str, message: &str) -> Error { #[cfg(test)] mod tests { use super::*; - use kurbo::Shape as _; /// A cutter's two kinds, set by `data-kind` or by class. #[derive(Debug, Clone, Copy, Default, PartialEq)] @@ -1967,6 +2244,64 @@ mod tests { assert!(got.shapes[4].clips.is_empty()); } + #[test] + fn clipped_paths_apply_piece_unions_fill_rules_and_nested_regions() { + let got = read( + r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> + <defs> + <clipPath id="pieces"><rect width="5" height="10"/><rect x="10" width="5" height="10"/></clipPath> + <clipPath id="ring"><path d="M0 0H20V20H0Z M5 5H15V15H5Z" clip-rule="evenodd"/></clipPath> + <clipPath id="left"><rect width="15" height="10"/></clipPath> + <clipPath id="right"><rect x="10" width="10" height="10"/></clipPath> + <clipPath id="empty"/> + </defs> + <rect id="piece-union" width="20" height="10" clip-path="url(#pieces)"/> + <rect id="evenodd-ring" width="20" height="20" clip-path="url(#ring)"/> + <g clip-path="url(#left)"><line id="nested-open" x1="0" y1="5" x2="20" y2="5" stroke="black" clip-path="url(#right)"/></g> + <line id="open" x1="0" y1="5" x2="20" y2="5" stroke="black" clip-path="url(#left)"/> + <line id="boundary" x1="15" y1="2" x2="15" y2="8" stroke="black" clip-path="url(#pieces)"/> + <path id="unpainted" d="M0 5H20" data-kind="engrave" fill="none" stroke="none" clip-path="url(#left)"/> + <rect id="empty-result" width="20" height="10" clip-path="url(#empty)"/> + </svg>"##, + ); + + let clipped = |label: &str| { + let shape = got.shapes.iter().find(|shape| shape.label == label).unwrap(); + got.clipped_path(shape).unwrap() + }; + let union = clipped(r#"<rect id="piece-union">"#); + assert_eq!(union.bounding_box(), kurbo::Rect::new(0.0, 0.0, 15.0, 10.0)); + assert_eq!(union.elements().iter().filter(|el| matches!(el, PathEl::ClosePath)).count(), 2); + + let ring = clipped(r#"<rect id="evenodd-ring">"#); + assert_eq!(ring.bounding_box(), kurbo::Rect::new(0.0, 0.0, 20.0, 20.0)); + assert_eq!(ring.elements().iter().filter(|el| matches!(el, PathEl::ClosePath)).count(), 2); + + let nested = clipped(r#"<line id="nested-open">"#); + assert!(near(nested.bounding_box().x0, 10.0) && near(nested.bounding_box().x1, 15.0)); + let open = clipped(r#"<line id="open">"#); + assert!(near(open.bounding_box().x0, 0.0) && near(open.bounding_box().x1, 15.0)); + let boundary = clipped(r#"<line id="boundary">"#); + assert!(near(boundary.bounding_box().x0, 15.0) && near(boundary.bounding_box().x1, 15.0)); + let unpainted = clipped(r#"<path id="unpainted">"#); + assert!(near(unpainted.bounding_box().x0, 0.0) && near(unpainted.bounding_box().x1, 15.0)); + assert!(clipped(r#"<rect id="empty-result">"#).elements().is_empty()); + + let mut invalid = got.clone(); + invalid.shapes[0].clips.push(usize::MAX); + assert!(invalid.clipped_path(&invalid.shapes[0]).is_err()); + } + + #[test] + fn clipped_path_flattening_enforces_segment_and_point_bounds() { + let mut path = kurbo::BezPath::new(); + path.move_to(kurbo::Point::ZERO); + path.line_to(kurbo::Point::new(1.0, 0.0)); + path.line_to(kurbo::Point::new(2.0, 0.0)); + assert!(flatten_contours_with_limits(&path, 2, 100).is_err()); + assert!(flatten_contours_with_limits(&path, 100, 2).is_err()); + } + #[test] fn clip_paths_that_cannot_be_applied_warn_and_leave_the_shape_unclipped() { for (svg, needle) in [ diff --git a/crates/svg/src/tree.rs b/crates/svg/src/tree.rs index 20dcd61cd..86a6d0ab1 100644 --- a/crates/svg/src/tree.rs +++ b/crates/svg/src/tree.rs @@ -139,11 +139,31 @@ pub fn parse_text(svg: &str, limits: &Limits, options: &usvg::Options<'_>) -> Re preflight(svg, limits)?.parse(options) } +/// Read the root SVG's unitless width and height without constructing a rendering tree. +/// +/// Lengths with units, percentages, missing dimensions, and non-SVG roots return `Ok(None)`; +/// malformed or over-limit XML returns the same bounded parsing error as [`parse_text`]. +pub fn root_unitless_size(svg: &str, limits: &Limits) -> Result<Option<(f64, f64)>, Error> { + let checked = preflight(svg, limits)?; + let root = checked.xml.root_element(); + if root.tag_name().name() != "svg" { + return Ok(None); + } + let Some((width, height)) = + root.attribute("width").and_then(|value| value.parse::<f64>().ok()).zip(root.attribute("height").and_then(|value| value.parse::<f64>().ok())) + else { + return Ok(None); + }; + Ok(Some((width, height))) +} + /// SVG text after shared byte, entity, attribute, XML and expansion-depth checks. /// Keep it opaque so consumers use the same checked tree and don't reparse XML locally. pub struct Preflight<'s> { xml: roxmltree::Document<'s>, depth: usize, + /// [`height`]: the nesting usvg converts, references followed. + height: usize, } impl Preflight<'_> { @@ -169,7 +189,7 @@ pub fn preflight<'s>(svg: &'s str, limits: &Limits) -> Result<Preflight<'s>, Err attribute_work: limits.attribute_work, xml_nodes: limits.xml_nodes, }; - let (xml, _depth, depth) = crate::preflight::parse_text_with_depth(svg, &preflight_limits).map_err(|e| match e { + let (xml, _, depth) = crate::preflight::parse_text_with_depth(svg, &preflight_limits).map_err(|e| match e { crate::preflight::Error::Text(e) => Error::Text(e), crate::preflight::Error::Entities => Error::Entities, crate::preflight::Error::EntityMarkup => Error::EntityMarkup, @@ -177,25 +197,10 @@ pub fn preflight<'s>(svg: &'s str, limits: &Limits) -> Result<Preflight<'s>, Err crate::preflight::Error::TooWide(attributes) => Error::TooWide(attributes), crate::preflight::Error::Xml(msg) => Error::Xml(msg), })?; - if height(&xml, limits.tree_depth)?.is_none() { + let Some(height) = height(&xml, limits.tree_depth)? else { return Err(Error::TooDeep(limits.tree_depth)); - } - Ok(Preflight { xml, depth }) -} - -/// Reads finite numeric root `width` and `height` values without interpreting physical units. -pub fn root_unitless_size(svg: &str, limits: &Limits) -> Result<Option<(f64, f64)>, Error> { - let checked = preflight(svg, limits)?; - let root = checked.xml.root_element(); - if root.tag_name().name() != "svg" { - return Ok(None); - } - let Some((width, height)) = - root.attribute("width").and_then(|value| value.parse::<f64>().ok()).zip(root.attribute("height").and_then(|value| value.parse::<f64>().ok())) - else { - return Ok(None); }; - Ok(Some((width, height))) + Ok(Preflight { xml, depth, height }) } /// Dimensions of an SVG viewport in SVG user units. @@ -374,6 +379,7 @@ struct Used { raster_limit: AtomicUsize, invalid_svg: AtomicUsize, svg_limit: AtomicUsize, + svg_resource_limit: AtomicUsize, } /// What resolving one drawing's embedded images used or refused. @@ -395,6 +401,10 @@ pub struct ImageUsage { pub invalid_svg_images: usize, /// Embedded SVG data refused by byte or nesting limits. pub svg_limit_images: usize, + /// Subset of `svg_limit_images` refused by unpacked byte or embedded-document-chain limits. + /// XML/tree-depth omissions and invalid or corrupt data do not set this counter. Consumers + /// can reject resource overruns while still allowing an optional, over-deep child to be omitted. + pub svg_resource_limit_images: usize, } /// A data-URL resolver and the accounting for the one drawing it serves. @@ -422,6 +432,7 @@ impl ImageResolver { raster_limit: AtomicUsize::new(0), invalid_svg: AtomicUsize::new(0), svg_limit: AtomicUsize::new(0), + svg_resource_limit: AtomicUsize::new(0), }), } } @@ -437,6 +448,16 @@ impl ImageResolver { self.used.xml_depth.store(depth, Ordering::Relaxed); } + /// Account for malformed image data URLs before usvg discards them without calling + /// its image resolver. Call once for the outer document, before `parse_text`. + /// Nested SVGs are checked automatically. The scan shares the normal XML limits and + /// streaming-validates URL encoding without allocating another decoded image buffer. + pub fn check_document(&self, svg: &str) -> Result<(), Error> { + let checked = preflight(svg, &self.limits)?; + account_invalid_data_urls(&checked.xml, &self.used); + Ok(()) + } + /// Snapshot accounting after parsing has finished. pub fn usage(&self) -> ImageUsage { ImageUsage { @@ -448,6 +469,28 @@ impl ImageResolver { raster_limit_images: self.used.raster_limit.load(Ordering::Relaxed), invalid_svg_images: self.used.invalid_svg.load(Ordering::Relaxed), svg_limit_images: self.used.svg_limit.load(Ordering::Relaxed), + svg_resource_limit_images: self.used.svg_resource_limit.load(Ordering::Relaxed), + } + } +} + +// usvg's data-URL decoder returns before resolve_data for invalid base64. Count +// these omissions separately, including feImage, without reading linked resources. +fn account_invalid_data_urls(xml: &roxmltree::Document<'_>, used: &Used) { + for node in xml.descendants().filter(|n| n.is_element() && matches!(n.tag_name().name(), "image" | "feImage")) { + let href = node.attribute(("http://www.w3.org/1999/xlink", "href")).or_else(|| node.attribute("href")); + let Some(href) = href else { continue }; + let url = match data_url::DataUrl::process(href) { + Ok(url) => url, + // Use the parser's normalized scheme recognition, including whitespace. + Err(data_url::DataUrlError::NoComma) => { + used.invalid_raster.fetch_add(1, Ordering::Relaxed); + continue; + } + Err(data_url::DataUrlError::NotADataUrl) => continue, + }; + if url.decode(|_| Ok::<(), std::convert::Infallible>(())).is_err() { + used.invalid_raster.fetch_add(1, Ordering::Relaxed); } } } @@ -497,6 +540,24 @@ fn raster_image(used: &Used, limits: &Limits, data: Arc<Vec<u8>>, format: craft_ } } drop(seen); + // A valid header is not proof of valid pixels. resvg can silently omit a damaged + // image later; decode now under explicit limits so omission accounting is honest. + let decode_limits = craft_image_codecs::Limits::new(width, height, pixels, limits.embedded_raster_pixels.saturating_mul(8)); + let options = craft_image_codecs::DecodeOptions { limits: decode_limits, keep_orientation: true }; + if let Err(error) = craft_image_codecs::decode_as_with(format, &data, &options) { + // No tree retains this allocation on failure. Forget its address before it + // can be reused, but keep the pixel charge for the decode work already spent. + used.raster_data.lock().unwrap_or_else(PoisonError::into_inner).remove(&pointer); + match error { + craft_image_codecs::CodecError::LimitExceeded(_) => { + used.raster_limit.fetch_add(1, Ordering::Relaxed); + } + _ => { + used.invalid_raster.fetch_add(1, Ordering::Relaxed); + } + } + return None; + } Some(match format { craft_image_codecs::Format::Png => usvg::ImageKind::PNG(data), craft_image_codecs::Format::Jpeg => usvg::ImageKind::JPEG(data), @@ -510,6 +571,7 @@ fn raster_image(used: &Used, limits: &Limits, data: Arc<Vec<u8>>, format: craft_ fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<'_>) -> Option<usvg::ImageKind> { if used.depth.load(Ordering::Relaxed) >= limits.embedded_depth { used.svg_limit.fetch_add(1, Ordering::Relaxed); + used.svg_resource_limit.fetch_add(1, Ordering::Relaxed); return None; } let left = limits.embedded_bytes.saturating_sub(used.bytes.load(Ordering::Relaxed)); @@ -517,19 +579,33 @@ fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<' Ok(text) => text, // What a refused document unpacked before it was refused was work too: it uses up what // is left, so the next image can't repeat it. - Err(svgz::Error::TooLarge(_)) => { + Err(error) => { used.bytes.fetch_add(left, Ordering::Relaxed); used.svg_limit.fetch_add(1, Ordering::Relaxed); - return None; - } - Err(_) => { - used.invalid_svg.fetch_add(1, Ordering::Relaxed); + if matches!(error, svgz::Error::TooLarge(_)) { + used.svg_resource_limit.fetch_add(1, Ordering::Relaxed); + } return None; } }; + // The raw/inflated bytes can fit while UTF-16/Latin-1 decoding expands + // beyond the aggregate allowance. A refusal consumes the remaining work. + if text.len() > left { + used.bytes.fetch_add(left, Ordering::Relaxed); + used.svg_limit.fetch_add(1, Ordering::Relaxed); + used.svg_resource_limit.fetch_add(1, Ordering::Relaxed); + return None; + } used.bytes.fetch_add(text.len(), Ordering::Relaxed); let checked = match preflight(&text, limits) { Ok(checked) => checked, + // Decoding UTF-16 or Latin-1 can exceed the text cap after the + // raw/inflated bytes fitted. This is a resource refusal, not invalid XML. + Err(Error::Text(svgz::Error::TooLarge(_))) => { + used.svg_limit.fetch_add(1, Ordering::Relaxed); + used.svg_resource_limit.fetch_add(1, Ordering::Relaxed); + return None; + } Err(Error::TooDeep(_)) => { used.svg_limit.fetch_add(1, Ordering::Relaxed); return None; @@ -539,7 +615,8 @@ fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<' return None; } }; - let xml_depth = checked.depth(); + // The nesting usvg converts, references followed, not the source depth alone. + let xml_depth = checked.height; let total_depth = used.xml_depth.load(Ordering::Relaxed).checked_add(xml_depth); let Some(total_depth) = total_depth.filter(|depth| *depth <= limits.tree_depth) else { used.svg_limit.fetch_add(1, Ordering::Relaxed); @@ -548,6 +625,7 @@ fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<' let previous_depth = used.xml_depth.swap(total_depth, Ordering::Relaxed); let depth = used.depth.fetch_add(1, Ordering::Relaxed).saturating_add(1); used.svg_depth.fetch_max(depth, Ordering::Relaxed); + account_invalid_data_urls(&checked.xml, used); let tree = checked.parse(options); used.xml_depth.store(previous_depth, Ordering::Relaxed); used.depth.fetch_sub(1, Ordering::Relaxed); diff --git a/crates/svg/src/tree/draw.rs b/crates/svg/src/tree/draw.rs index 2b5c40ca8..f83653284 100644 --- a/crates/svg/src/tree/draw.rs +++ b/crates/svg/src/tree/draw.rs @@ -24,6 +24,8 @@ use std::collections::HashMap; use usvg::Transform; +#[cfg(feature = "tree-render")] +pub use resvg; #[cfg(feature = "tree-render")] pub use resvg::tiny_skia; @@ -39,7 +41,7 @@ const MAX_PATTERN_DEPTH: usize = 8; /// Embedded SVG images inside embedded SVG images. Each draws on a pixmap of the enclosing /// layer, which the live-bytes check charges, so deep chains of small images are harmless and /// chains of big ones stop at the budget long before this. -const MAX_IMAGE_DEPTH: usize = 32; +const MAX_IMAGE_DEPTH: usize = 24; /// Nested isolated groups, patterns, embedded images and filter images followed. It keeps this /// walk, and resvg's own recursion, far from a stack overflow; real drawings stay under a few dozen. const MAX_DEPTH: usize = 200; diff --git a/crates/svg/src/tree/tests.rs b/crates/svg/src/tree/tests.rs index 751e7726b..2708ae0f4 100644 --- a/crates/svg/src/tree/tests.rs +++ b/crates/svg/src/tree/tests.rs @@ -81,7 +81,8 @@ fn every_limit_refuses_the_file_past_it() { let chain: String = (0..20).map(|i| format!("<g id='g{i}'><use xlink:href='#g{}'/></g>", i + 1)).collect(); let uses = svg(&format!("<defs>{chain}<rect id='g20' width='1' height='1'/></defs><use xlink:href='#g0'/>")); assert!(!guard::deeper_than(&uses, 24)); - assert_eq!(try_parse(&uses, &shallow()).err(), Some(Error::TooDeep(24))); + let referenced_depth = Limits { tree_depth: 24, ..shallow() }; + assert_eq!(try_parse(&uses, &referenced_depth).err(), Some(Error::TooDeep(24))); // Attributes on one element. let wide = svg(&format!("<g{}/>", (0..40).map(|i| format!(" a{i}='1'")).collect::<String>())); assert!(try_parse(&wide, &Limits { attributes: 40, ..shallow() }).is_ok()); @@ -244,6 +245,195 @@ fn embedded_svgs_are_read_within_their_budgets() { assert_eq!(found(&svg(r#"<image width="5" height="5" xlink:href="/etc/passwd.svg"/>"#), shallow()), [false; 0]); } +mod resource_limit_usage { + use super::*; + + fn data_image(bytes: &[u8]) -> String { + let encoded: String = bytes.iter().map(|byte| format!("%{byte:02X}")).collect(); + format!(r#"<image width="5" height="5" xlink:href="data:image/svg+xml,{encoded}"/>"#) + } + + fn packed(text: &str, gzip: bool) -> Vec<u8> { + if gzip { svgz::compress(text.as_bytes()) } else { text.as_bytes().to_vec() } + } + + /// The outer document has its own generous text allowance, so tiny resolver limits + /// test the public embedded admission contract rather than rejecting the outer XML. + fn resolved(text: &str, limits: Limits, outer_depth: usize) -> (Vec<bool>, ImageUsage) { + let resolver = ImageResolver::new(limits); + resolver.set_document_depth(outer_depth); + let options = usvg::Options { image_href_resolver: resolver.resolver(), ..Default::default() }; + let tree = parse(text.as_bytes(), &shallow(), &options).unwrap(); + let mut found = Vec::new(); + images(tree.root(), &mut found); + (found, resolver.usage()) + } + + fn expanding_encoded_children() -> Vec<(&'static str, Vec<u8>)> { + let latin = + format!("<?xml version='1.0' encoding='ISO-8859-1'?>{}", svg(&format!("<title>{}</title><rect width='1' height='1'/>", "é".repeat(100)))); + let latin = latin.chars().map(|c| u8::try_from(u32::from(c)).unwrap()).collect(); + let wide = svg(&format!("<title>{}</title><rect width='1' height='1'/>", "ࠀ".repeat(400))); + let mut little = vec![0xff, 0xfe]; + little.extend(wide.encode_utf16().flat_map(u16::to_le_bytes)); + let mut big = vec![0xfe, 0xff]; + big.extend(wide.encode_utf16().flat_map(u16::to_be_bytes)); + vec![("Latin-1", latin), ("UTF-16LE", little), ("UTF-16BE", big)] + } + + #[test] + fn decoded_text_expansion_is_a_resource_refusal_for_plain_and_gzip_children() { + for (encoding, raw) in expanding_encoded_children() { + let decoded = svgz::decode(&raw).unwrap(); + let cap = raw.len(); + assert!(decoded.len() > cap, "{encoding} fixture must expand after inflation"); + for gzip in [false, true] { + let data = if gzip { svgz::compress(&raw) } else { raw.clone() }; + assert_eq!(svgz::inflate(&data, cap).unwrap().len(), cap, "raw bytes fit exactly"); + assert_eq!(svgz::text(&data, cap).unwrap().len(), decoded.len(), "decoding itself succeeds"); + let limits = Limits { bytes: cap, embedded_bytes: decoded.len(), ..shallow() }; + assert!(matches!(preflight(&decoded, &limits), Err(Error::Text(svgz::Error::TooLarge(n))) if n == cap)); + let image = data_image(&data); + let (found, usage) = resolved(&svg(&image), limits, 1); + assert!(found.is_empty(), "{encoding}, gzip {gzip}"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (1, 1, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len(), "spent decoded work remains charged"); + let (found, usage) = resolved(&svg(&format!("{image}{image}")), limits, 1); + assert!(found.is_empty()); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (2, 2, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len(), "a refused sibling cannot repeat exhausted work"); + } + } + } + + #[test] + fn decoded_text_expansion_respects_aggregate_bytes_even_when_each_child_fits() { + for (encoding, raw) in expanding_encoded_children() { + let decoded = svgz::decode(&raw).unwrap(); + let limits = Limits { bytes: decoded.len(), embedded_bytes: raw.len(), ..shallow() }; + assert!(decoded.len() > limits.embedded_bytes); + preflight(&decoded, &limits).unwrap(); // The independent per-image cap allows this complete XML. + for gzip in [false, true] { + let data = if gzip { svgz::compress(&raw) } else { raw.clone() }; + assert_eq!(svgz::inflate(&data, limits.embedded_bytes).unwrap().len(), raw.len()); + let image = data_image(&data); + let (found, usage) = resolved(&svg(&image), limits, 1); + assert!(found.is_empty(), "{encoding}, gzip {gzip}"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (1, 1, 0)); + assert_eq!(usage.embedded_svg_bytes, limits.embedded_bytes, "refusal consumes exactly the remaining allowance"); + let (found, usage) = resolved(&svg(&format!("{image}{image}")), limits, 1); + assert!(found.is_empty()); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (2, 2, 0)); + assert_eq!(usage.embedded_svg_bytes, limits.embedded_bytes, "a later child cannot repeat exhausted work"); + let (found, usage) = resolved(&svg(&image), Limits { embedded_bytes: decoded.len(), ..limits }, 1); + assert_eq!(found, [true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (0, 0, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len()); + } + } + } + + #[test] + fn decoded_text_expansion_at_the_cap_is_valid_and_malformed_xml_stays_invalid() { + for (encoding, raw) in expanding_encoded_children() { + let decoded = svgz::decode(&raw).unwrap(); + for gzip in [false, true] { + let data = if gzip { svgz::compress(&raw) } else { raw.clone() }; + let limits = Limits { bytes: decoded.len(), embedded_bytes: decoded.len(), ..shallow() }; + let (found, usage) = resolved(&svg(&data_image(&data)), limits, 1); + assert_eq!(found, [true], "{encoding}, gzip {gzip}"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (0, 0, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len()); + // Preserve the declared/BOM encoding when making the XML malformed; + // re-encoding Latin-1 text as UTF-8 would test a second expansion instead. + let closing_bytes = if encoding == "Latin-1" { 6 } else { 12 }; + let malformed = &raw[..raw.len() - closing_bytes]; + let data = if gzip { svgz::compress(malformed) } else { malformed.to_vec() }; + let (found, usage) = resolved(&svg(&data_image(&data)), limits, 1); + assert!(found.is_empty()); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (0, 0, 1)); + } + } + } + + #[test] + fn embedded_chain_caps_are_explicit_resource_refusals_for_plain_and_gzip_children() { + for gzip in [false, true] { + let inner = svg("<rect width='1' height='1'/>"); + let middle = svg(&data_image(&packed(&inner, gzip))); + let outer = svg(&data_image(&packed(&middle, gzip))); + let (found, usage) = resolved(&outer, Limits { embedded_depth: 1, ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!(usage.embedded_svg_depth, 1); + assert_eq!(usage.svg_limit_images, 1, "strict consumers still see the existing limit flag"); + assert_eq!(usage.svg_resource_limit_images, 1, "a chain cap must not become a successful partial bounded preview"); + let (found, usage) = resolved(&outer, Limits { embedded_depth: 2, ..shallow() }, 1); + assert_eq!(found, [true, true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn embedded_per_image_byte_caps_are_resource_refusals_for_plain_and_gzip_children() { + let inner = svg("<rect width='1' height='1'/>"); + for gzip in [false, true] { + let outer = svg(&data_image(&packed(&inner, gzip))); + let (_, usage) = resolved(&outer, Limits { bytes: inner.len() - 1, embedded_bytes: inner.len() * 3, ..shallow() }, 1); + assert_eq!(usage.embedded_svg_count, 0); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (1, 1)); + let (found, usage) = resolved(&outer, Limits { bytes: inner.len(), ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn aggregate_embedded_bytes_are_resource_refusals_even_when_each_child_fits() { + let inner = svg("<rect width='1' height='1'/>"); + for gzip in [false, true] { + let image = data_image(&packed(&inner, gzip)); + let outer = svg(&format!("{image}{image}")); + let cap = inner.len() * 2 - 1; + let (found, usage) = resolved(&outer, Limits { embedded_bytes: cap, ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!(usage.embedded_svg_bytes, cap, "a refused child still spends the remaining work allowance"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (1, 1)); + let (found, usage) = resolved(&outer, Limits { embedded_bytes: inner.len() * 2, ..shallow() }, 1); + assert_eq!(found, [true, true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn combined_xml_depth_omissions_remain_distinct_from_resource_refusals() { + let inner = svg("<rect width='1' height='1'/>"); + for gzip in [false, true] { + let image = data_image(&packed(&inner, gzip)); + let outer = svg(&format!("{}{}{}", "<g>".repeat(4), image, "</g>".repeat(4))); + let (found, usage) = resolved(&outer, Limits { tree_depth: 6, ..shallow() }, 5); + assert!(found.is_empty()); + assert_eq!(usage.svg_limit_images, 1, "strict consumers must continue to reject this omission"); + assert_eq!(usage.svg_resource_limit_images, 0, "non-strict consumers may omit this child without disguising a byte/chain overrun"); + let (found, usage) = resolved(&svg(&image), Limits { tree_depth: 6, ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn invalid_and_corrupt_children_do_not_claim_a_resource_limit() { + let mut corrupt = svgz::compress(svg("<rect width='1' height='1'/>").as_bytes()); + let crc = corrupt.len() - 8; + corrupt[crc] ^= 1; + for data in [b"not XML".to_vec(), corrupt] { + let (found, usage) = resolved(&svg(&data_image(&data)), shallow(), 1); + assert!(found.is_empty()); + assert!(usage.invalid_svg_images > 0 || usage.svg_limit_images > 0, "strict consumers still observe unreadable content"); + assert_eq!(usage.svg_resource_limit_images, 0); + } + } +} + mod draw_checks { use super::*; @@ -302,3 +492,95 @@ mod draw_checks { assert!(!refusal.memory && refusal.message.contains("clip-paths"), "{refusal:?}"); } } + +mod invalid_image_accounting { + use super::*; + + fn usage(body: &str, limits: Limits) -> (Vec<bool>, ImageUsage) { + let text = svg(body); + let resolver = ImageResolver::new(limits); + resolver.check_document(&text).unwrap(); + let options = usvg::Options { image_href_resolver: resolver.resolver(), ..Default::default() }; + let tree = parse_text(&text, &limits, &options).unwrap(); + let mut found = Vec::new(); + images(tree.root(), &mut found); + (found, resolver.usage()) + } + + fn png() -> Vec<u8> { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType, encode}; + let image = Image::new(1, 1, ChannelLayout::Rgba, SampleType::U8).unwrap(); + encode(&image, Format::Png, &EncodeOptions::default()).unwrap() + } + + fn image(data: &[u8]) -> String { + let encoded: String = data.iter().map(|b| format!("%{b:02X}")).collect(); + format!(r#"<image width="1" height="1" xlink:href="data:image/png,{encoded}"/>"#) + } + + #[test] + fn malformed_base64_is_counted_before_usvg_discards_it() { + let bad = r#"<image width="1" height="1" xlink:href="data:image/png;base64,A"/>"#; + let (found, report) = usage(bad, shallow()); + assert!(found.is_empty()); + assert_eq!(report.invalid_raster_images, 1); + let (found, report) = usage(&embed(&svg(bad)), shallow()); + assert_eq!(found, [true]); + assert_eq!(report.invalid_raster_images, 1); + } + + #[test] + fn malformed_data_url_without_comma_is_counted() { + for href in ["data:image/png;base64", " data:image/png;base64", "da&#x9;ta:image/png;base64", "da&#xA;ta:image/png;base64"] { + let bad = format!(r#"<image width="1" height="1" xlink:href="{href}"/>"#); + let (found, report) = usage(&bad, shallow()); + assert!(found.is_empty(), "{href}"); + assert_eq!(report.invalid_raster_images, 1, "{href}"); + let (found, report) = usage(&embed(&svg(&bad)), shallow()); + assert_eq!(found, [true], "{href}"); + assert_eq!(report.invalid_raster_images, 1, "{href}"); + } + } + + #[test] + fn failed_decode_forgets_address_but_preserves_spent_budget() { + let valid = png(); + let idat = valid.windows(4).position(|b| b == b"IDAT").unwrap(); + let invalid = Arc::new(valid[..idat + 4].to_vec()); + let pointer = Arc::as_ptr(&invalid) as usize; + let limits = Limits { embedded_raster_pixels: 3, ..shallow() }; + let resolver = ImageResolver::new(limits); + let used = &resolver.used; + let format = craft_image_codecs::Format::Png; + assert!(raster_image(used, &limits, invalid, format).is_none()); + assert!(!used.raster_data.lock().unwrap().contains(&pointer)); + assert_eq!(resolver.usage().raster_pixels, 1); + let first_data = Arc::new(valid.clone()); + let first = raster_image(used, &limits, first_data.clone(), format).unwrap(); + assert_eq!(resolver.usage().raster_pixels, 2); + let repeated = raster_image(used, &limits, first_data, format).unwrap(); + assert_eq!(resolver.usage().raster_pixels, 2); + let second = raster_image(used, &limits, Arc::new(valid.clone()), format).unwrap(); + assert_eq!(resolver.usage().raster_pixels, 3); + assert!(raster_image(used, &limits, Arc::new(valid), format).is_none()); + assert_eq!(resolver.usage().raster_limit_images, 1); + drop((first, repeated, second)); + } + + #[test] + fn corrupt_pixels_do_not_pass_a_valid_header_probe() { + let valid = png(); + let (found, report) = usage(&image(&valid), shallow()); + assert_eq!(found, [false]); + assert_eq!(report.invalid_raster_images, 0); + let idat = valid.windows(4).position(|b| b == b"IDAT").unwrap(); + let corrupt = &valid[..idat + 4]; + assert_eq!(craft_image_codecs::probe_allocation_size(corrupt).unwrap(), (1, 1)); + let (found, report) = usage(&image(corrupt), shallow()); + assert!(found.is_empty()); + assert_eq!(report.invalid_raster_images, 1); + let (found, report) = usage(&image(&valid), Limits { embedded_raster_pixels: 0, ..shallow() }); + assert!(found.is_empty()); + assert_eq!(report.raster_limit_images, 1); + } +} diff --git a/crates/texture/Cargo.toml b/crates/texture/Cargo.toml new file mode 100644 index 000000000..78868dd87 --- /dev/null +++ b/crates/texture/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-texture" +description = "Bounded linear float image planes and texture sampling" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[features] +default = [] +parallel = ["dep:rayon"] + +[lints] +workspace = true + +[dependencies] +rayon = { workspace = true, optional = true } +thiserror = { workspace = true } diff --git a/crates/texture/README.md b/crates/texture/README.md new file mode 100644 index 000000000..a41b42666 --- /dev/null +++ b/crates/texture/README.md @@ -0,0 +1,77 @@ +# craft-texture + +Linear float image planes and texture sampling. An `Image` is a gray (1 channel) or RGBA plane of +`f32`, row-major with the top row first, shared copy-on-write through an `Arc`. Values are stored +as given, so HDR values above 1 and negative values are kept. The crate has no UI, does no file or +network I/O and has no `unsafe` code. + +- **Construction.** `try_filled`, `try_generate`, `try_generate_uv` and `from_data` check the size + against `Limits` (longest side, pixel count, bytes) before allocating and return an + `ImageError`. `from_data` also checks that the buffer holds width × height × channels floats. + `filled`, `generate`, `generate_uv` and `gray` clamp each side to `1..=MAX_SIDE` (8192). + A plane is never larger than `isize::MAX` bytes (2 GiB minus one byte on `wasm32`), even with + raised limits: the `try_` forms return `ImageError::TooLarge` for a larger one, and `map`, + `to_color` and `to_kind` clamp each side to `1..=MAX_SIDE` and map the top-left part instead. + `try_map`, `try_to_kind`, `try_resize` and `try_to_rgba8_display` reserve their pixel buffer + first and return `ImageError::OutOfMemory` when that reservation fails. They still make small + allocations that are not fallible: the `Arc` around a new image's buffer, and the boxed + resampler of `try_resize`. The forms without `try_` allocate like `Vec`. A failed infallible + allocation ends the process. +- **Sampling.** `sample` (bilinear) and `sample_nearest` take normalized `(u, v)` with `(0, 0)` at + the upper-left corner and `v` increasing downward, as glTF 2.0 section 3.8.3 defines them + (<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>). `tile` picks repeat (glTF + `REPEAT`) or clamp to edge (`CLAMP_TO_EDGE`) for both axes. The texel coordinate, the wrapping + and the bilinear weights follow the Vulkan specification, sections 20.4.1, 20.6.1 and 20.6.3 + (<https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#textures-texel-filtering>). + Repeat keeps its period at any finite coordinate. A NaN or infinite coordinate gives + `[0, 0, 0, 1]`. Bilinear sums are taken in `f64` and clamped to the `f32` range, so finite + texels give a finite sample. +- **Other operations.** `get` reads one texel, `map`, `to_gray`, `to_color` and `to_kind` convert, + `resize` box-averages whole-factor shrinks and samples bilinearly otherwise, and + `to_rgba8_display` encodes 8-bit sRGB RGBA. `linear_to_srgb`, `srgb_to_linear` and `luminance` + (Rec. 709) are scalar helpers. `resource_key` and `split_resource_key` tag a bitmap name with + its color space. + +Mirrored repeat, mip chains, height to normal, channel packing, decoding and texture-set +recognition are not in the crate yet. + +## Cargo features + +No default features. + +| Feature | Provides | Pulls in | +|---|---|---| +| `parallel` | generated images and display conversion fill rows on several threads; the results are the same | `rayon` | + +Without `parallel` the crate builds for `wasm32-unknown-unknown`. + +## Limits + +| Field | Default | Checked by | +|---|---|---| +| `max_side` | 8192 | every `try_` constructor and `from_data` | +| `max_pixels` | 2^26 (8192 × 8192) | the same | +| `max_bytes` | 1 GiB (an 8192 × 8192 RGBA plane) | the same | + +## Origin + +| Part | Source | +|---|---| +| `Image`, `Kind`, sampling, resizing, conversions, sRGB helpers, resource keys and the six tests `sample_survives_huge_coordinates`, `resource_keys_round_trip`, `sample_wraps_and_clamps`, `resize_box_and_bilinear`, `hostile_sizes_are_clamped`, `conversions` | MaterialCraft `crates/image/src/lib.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) | +| `Limits`, the `try_` constructors, `from_data`, private fields with getters, the `parallel` feature | written here | + +## Migration + +| App | Status | +|---|---| +| MaterialCraft | `materialcraft-image` is the source. The app switches to this crate in its own pull request. | +| EffectCraft | Its texture sampling moves into this crate later, with mirrored repeat. | + +For MaterialCraft: + +| `materialcraft-image` | craft-texture | +| --- | --- | +| `image.w`, `image.h`, `image.kind`, `image.data` | `width()`, `height()`, `kind()`, `data()` and `shared_data()` | +| `Image { w, h, kind, data }` built by hand | `Image::from_data(w, h, kind, data, &Limits::default())` | +| `rayon` always on | the `parallel` feature | +| `linear_to_srgb(NaN)` returned −0.055 | it returns NaN | diff --git a/crates/texture/src/lib.rs b/crates/texture/src/lib.rs new file mode 100644 index 000000000..2aaef3e8b --- /dev/null +++ b/crates/texture/src/lib.rs @@ -0,0 +1,895 @@ +//! # craft-texture +//! +//! Linear float image planes and texture sampling. An [`Image`] is a grayscale (1 channel) or +//! color (RGBA) plane of `f32`, row-major with the top row first, shared copy-on-write through an +//! `Arc` so a copy costs a reference count. Values are stored as given: HDR values above 1, +//! negative values and non-finite values are kept. +//! +//! Sampling takes normalized `(u, v)` with `(0, 0)` at the upper-left corner and `v` increasing +//! downward, as glTF 2.0 section 3.8.3 defines texture coordinates +//! (<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>). The `tile` argument picks the +//! wrap mode of both axes: repeat (glTF `REPEAT`, 10497) or clamp to edge (`CLAMP_TO_EDGE`, 33071). +//! [`Image::sample_nearest`] and [`Image::sample`] (bilinear) use the texel coordinates, wrapping +//! and weights of the Vulkan specification, sections 20.4.1, 20.6.1 and 20.6.3 +//! (<https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#textures-texel-filtering>). +//! +//! Sizes are bounded. [`Limits`] caps the side, the pixel count and the bytes, and the `try_` +//! constructors return an [`ImageError`] before allocating anything over them. A plane is also +//! never larger than `isize::MAX` bytes, the most a `Vec` can hold on the target: `isize::MAX` is +//! 2 GiB minus one byte on 32-bit targets such as `wasm32`. The `try_` forms return +//! [`ImageError::TooLarge`] for a plane over that bound, also when the caller raised the limits +//! past it. The constructors without `try_` clamp each side to `1..=MAX_SIDE`, and [`Image::map`] +//! clamps the same way when its result would be over the bound. Every operation that allocates a +//! pixel buffer has a `try_` form that reserves that buffer first and returns +//! [`ImageError::OutOfMemory`] when the reservation fails. The `try_` forms still make small +//! allocations that are not fallible: the `Arc` that holds a new image's buffer, and the boxed +//! resampler of [`Image::try_resize`]. The forms without `try_` allocate like `Vec`. A failed +//! infallible allocation ends the process. Rows are generated on several threads only with the +//! `parallel` feature. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::sync::Arc; + +#[cfg(feature = "parallel")] +use rayon::prelude::*; + +/// Largest side the clamping constructors make, and the default [`Limits::max_side`]. +pub const MAX_SIDE: u32 = 8192; + +/// Whether an image holds one channel or four. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + Gray, + Color, +} + +impl Kind { + pub fn channels(self) -> usize { + match self { + Kind::Gray => 1, + Kind::Color => 4, + } + } +} + +/// Why an image could not be made. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum ImageError { + /// A side is zero or longer than [`Limits::max_side`]. + #[error("image size {0}x{1} has a zero side or a side over the limit")] + BadSize(u32, u32), + /// The pixel count or the byte count is over [`Limits`], or the byte count is over + /// `isize::MAX`, the largest allocation the target allows. + #[error("image size {0}x{1} needs more pixels or bytes than the limits or the target allow")] + TooLarge(u32, u32), + /// The float buffer does not hold width × height × channels values. + #[error("image data holds {found} floats where {expected} are needed")] + BadDataLength { expected: usize, found: usize }, + /// Memory for the pixels could not be reserved. + #[error("not enough memory for a {0}x{1} image")] + OutOfMemory(u32, u32), +} + +/// Caps on the size of an image, checked before anything is allocated. +/// `#[non_exhaustive]`: start from [`Limits::default`] and set the fields you change. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub struct Limits { + /// Longest side in pixels. Default [`MAX_SIDE`]. + pub max_side: u32, + /// Most pixels (width × height). Default 2^26, which is 8192 × 8192. + pub max_pixels: u64, + /// Most bytes of float data (pixels × channels × 4). Default 1 GiB, an 8192 × 8192 color plane. + pub max_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_side: MAX_SIDE, max_pixels: 1 << 26, max_bytes: 1 << 30 } + } +} + +/// The largest allocation in bytes that a `Vec` can make on the target. +const MAX_ALLOC_BYTES: u64 = isize::MAX as u64; + +/// Bytes of float data in a `w × h` image of `kind`, or `None` when the count overflows `u64`. +fn checked_byte_len(w: u32, h: u32, kind: Kind) -> Option<u64> { + u64::from(w).checked_mul(u64::from(h))?.checked_mul(kind.channels() as u64)?.checked_mul(size_of::<f32>() as u64) +} + +impl Limits { + /// The number of floats a `w × h` image of `kind` holds, or the error the limits give for that + /// size. A size whose bytes are over `isize::MAX` is [`ImageError::TooLarge`] whatever the + /// limits are. Nothing is allocated. + pub fn check(&self, w: u32, h: u32, kind: Kind) -> Result<usize, ImageError> { + self.check_within(w, h, kind, MAX_ALLOC_BYTES) + } + + /// [`Limits::check`] with `max_alloc_bytes` as the largest allocation the target allows. + fn check_within(&self, w: u32, h: u32, kind: Kind, max_alloc_bytes: u64) -> Result<usize, ImageError> { + if w == 0 || h == 0 || w > self.max_side || h > self.max_side { + return Err(ImageError::BadSize(w, h)); + } + let too_large = ImageError::TooLarge(w, h); + let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(|| too_large.clone())?; + let floats = pixels.checked_mul(kind.channels() as u64).ok_or_else(|| too_large.clone())?; + let bytes = floats.checked_mul(size_of::<f32>() as u64).ok_or_else(|| too_large.clone())?; + if pixels > self.max_pixels || bytes > self.max_bytes || bytes > max_alloc_bytes { + return Err(too_large); + } + usize::try_from(floats).map_err(|_| too_large) + } +} + +/// A gray or RGBA plane of linear `f32`. Width and height are at least 1, and the data holds +/// exactly width × height × channels floats. +#[derive(Clone, Debug)] +pub struct Image { + w: u32, + h: u32, + kind: Kind, + /// Row-major, `kind.channels()` floats per pixel. + data: Arc<Vec<f32>>, +} + +/// Images are equal when their size, kind and floats are equal. Floats compare as `f32` does, so +/// an image holding NaN is unequal to every image, its clones included. +impl PartialEq for Image { + fn eq(&self, o: &Image) -> bool { + self.w == o.w && self.h == o.h && self.kind == o.kind && self.data == o.data + } +} + +/// Clamp a requested size into `1..=MAX_SIDE` on each side. +pub fn clamp_size(w: u32, h: u32) -> (u32, u32) { + (w.clamp(1, MAX_SIDE), h.clamp(1, MAX_SIDE)) +} + +/// The size and float count of an image of `kind` requested at `w × h` without a limit check: +/// `w × h` when its bytes fit in `max_alloc_bytes`, otherwise each side clamped to +/// `1..=MAX_SIDE`, and 1 × 1 when even the clamped size does not fit. Nothing is allocated. +fn bounded_size(w: u32, h: u32, kind: Kind, max_alloc_bytes: u64) -> (u32, u32, usize) { + let floats = |w: u32, h: u32| { + let bytes = checked_byte_len(w, h, kind).filter(|&bytes| bytes <= max_alloc_bytes)?; + usize::try_from(bytes / size_of::<f32>() as u64).ok() + }; + if let Some(len) = floats(w, h) { + return (w, h, len); + } + let (w, h) = clamp_size(w, h); + match floats(w, h) { + Some(len) => (w, h, len), + None => (1, 1, kind.channels()), + } +} + +/// Integer texel index `i` on an axis of `n >= 1` texels: `i mod n` when repeating, otherwise +/// clamped to `0..=n - 1`. +#[inline] +fn wrap(i: i64, n: u32, tile: bool) -> usize { + let n = i64::from(n.max(1)); + if tile { i.rem_euclid(n) as usize } else { i.clamp(0, n - 1) as usize } +} + +/// The largest `f32` below 1. +const BELOW_ONE: f32 = 1.0 - f32::EPSILON / 2.0; + +/// A normalized coordinate brought into a range whose texel indices fit in `i64`: its fractional +/// part, below 1, when repeating, since the repeat period is 1, and `-1..=2` when clamping, where +/// every value outside `0..=1` already selects an edge texel. `None` for NaN and infinity. +#[inline] +fn reduce(t: f32, tile: bool) -> Option<f32> { + if !t.is_finite() { + return None; + } + Some(if tile { t.rem_euclid(1.0).min(BELOW_ONE) } else { t.clamp(-1.0, 2.0) }) +} + +/// Fill `data` row by row with `f(x, y)`, keeping the first `c` channels of each result. +fn fill<F: Fn(u32, u32) -> [f32; 4] + Sync>(data: &mut [f32], w: u32, c: usize, f: &F) { + let row_len = (w as usize).max(1) * c; + let fill_row = |(y, row): (usize, &mut [f32])| { + for (x, px) in row.chunks_exact_mut(c).enumerate() { + let p = f(x as u32, y as u32); + px.copy_from_slice(&p[..c]); + } + }; + #[cfg(feature = "parallel")] + data.par_chunks_mut(row_len).enumerate().for_each(fill_row); + #[cfg(not(feature = "parallel"))] + data.chunks_mut(row_len).enumerate().for_each(fill_row); +} + +impl Image { + /// An image of `w × h`, or of the clamped size [`bounded_size`] gives when its bytes would be + /// over `isize::MAX`. `f` is called only for pixels inside the size that was made. + fn build<F: Fn(u32, u32) -> [f32; 4] + Sync>(w: u32, h: u32, kind: Kind, f: F) -> Image { + let (w, h, len) = bounded_size(w, h, kind, MAX_ALLOC_BYTES); + let mut data = vec![0.0f32; len]; + fill(&mut data, w, kind.channels(), &f); + Image { w, h, kind, data: Arc::new(data) } + } + + /// An image checked against `limits`, with its memory reserved before any pixel is generated. + fn try_build<F: Fn(u32, u32) -> [f32; 4] + Sync>(w: u32, h: u32, kind: Kind, limits: &Limits, f: F) -> Result<Image, ImageError> { + let len = limits.check(w, h, kind)?; + let mut data = Vec::new(); + data.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(w, h))?; + data.resize(len, 0.0); + fill(&mut data, w, kind.channels(), &f); + Ok(Image { w, h, kind, data: Arc::new(data) }) + } + + /// A constant image, each side clamped to `1..=MAX_SIDE`. + pub fn filled(w: u32, h: u32, kind: Kind, v: [f32; 4]) -> Image { + let (w, h) = clamp_size(w, h); + Image::build(w, h, kind, |_, _| v) + } + + /// A constant image, or an error when the size is outside `limits` or memory runs out. + pub fn try_filled(w: u32, h: u32, kind: Kind, v: [f32; 4], limits: &Limits) -> Result<Image, ImageError> { + Image::try_build(w, h, kind, limits, |_, _| v) + } + + /// Generate every pixel with `f(x, y)` (pixel indices), each side clamped to `1..=MAX_SIDE`. + pub fn generate(w: u32, h: u32, kind: Kind, f: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { + let (w, h) = clamp_size(w, h); + Image::build(w, h, kind, f) + } + + /// Generate every pixel with `f(x, y)`, or return an error when the size is outside `limits` + /// or memory runs out. + pub fn try_generate(w: u32, h: u32, kind: Kind, limits: &Limits, f: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Result<Image, ImageError> { + Image::try_build(w, h, kind, limits, f) + } + + /// Generate from normalized coordinates at the pixel centers, `(x + 0.5) / w` and + /// `(y + 0.5) / h`, each side clamped to `1..=MAX_SIDE` first. + pub fn generate_uv(w: u32, h: u32, kind: Kind, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Image { + let (w, h) = clamp_size(w, h); + let (iw, ih) = (1.0 / w as f32, 1.0 / h as f32); + Image::build(w, h, kind, |x, y| f((x as f32 + 0.5) * iw, (y as f32 + 0.5) * ih)) + } + + /// [`Image::generate_uv`] for a size checked against `limits`. + pub fn try_generate_uv(w: u32, h: u32, kind: Kind, limits: &Limits, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Result<Image, ImageError> { + let (iw, ih) = (1.0 / w.max(1) as f32, 1.0 / h.max(1) as f32); + Image::try_build(w, h, kind, limits, |x, y| f((x as f32 + 0.5) * iw, (y as f32 + 0.5) * ih)) + } + + /// A gray image generated with `f(x, y)`, each side clamped to `1..=MAX_SIDE`. + pub fn gray(w: u32, h: u32, f: impl Fn(u32, u32) -> f32 + Sync) -> Image { + Image::generate(w, h, Kind::Gray, |x, y| [f(x, y), 0.0, 0.0, 0.0]) + } + + /// An image over existing row-major data, checked against `limits` and against the length + /// width × height × channels. The data is not copied. + pub fn from_data(w: u32, h: u32, kind: Kind, data: impl Into<Arc<Vec<f32>>>, limits: &Limits) -> Result<Image, ImageError> { + let expected = limits.check(w, h, kind)?; + let data = data.into(); + if data.len() != expected { + return Err(ImageError::BadDataLength { expected, found: data.len() }); + } + Ok(Image { w, h, kind, data }) + } + + pub fn width(&self) -> u32 { + self.w + } + + pub fn height(&self) -> u32 { + self.h + } + + pub fn kind(&self) -> Kind { + self.kind + } + + /// The row-major floats, `channels()` per pixel. + pub fn data(&self) -> &[f32] { + self.data.as_slice() + } + + /// The shared buffer behind [`Image::data`]. + pub fn shared_data(&self) -> &Arc<Vec<f32>> { + &self.data + } + + pub fn channels(&self) -> usize { + self.kind.channels() + } + + pub fn is_gray(&self) -> bool { + self.kind == Kind::Gray + } + + /// The pixel at integer coordinates (wrapped or clamped), as RGBA (gray → `[v, v, v, 1]`). + #[inline] + pub fn get(&self, x: i64, y: i64, tile: bool) -> [f32; 4] { + let (x, y) = (wrap(x, self.w, tile), wrap(y, self.h, tile)); + let i = y * self.w as usize + x; + match self.kind { + Kind::Gray => { + let v = self.data.get(i).copied().unwrap_or(0.0); + [v, v, v, 1.0] + } + Kind::Color => { + let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + [s[0], s[1], s[2], s[3]] + } + } + } + + /// The gray value, or the Rec. 709 luminance of a color image. + #[inline] + pub fn get_gray(&self, x: i64, y: i64, tile: bool) -> f32 { + let p = self.get(x, y, tile); + match self.kind { + Kind::Gray => p[0], + Kind::Color => luminance(p), + } + } + + /// Bilinear sample at normalized `(u, v)`; pixel centers sit at `(i + 0.5) / w`. The texel + /// coordinate is `u × w − 0.5`; its floor and the next index are wrapped or clamped, and the + /// four texels are weighted `(1 − α)(1 − β)`, `α(1 − β)`, `(1 − α)β` and `αβ` by the fractional + /// parts `α` and `β`. A texel with weight 0 does not enter the sum, so an infinite neighbor + /// leaves a sample at a texel center unchanged. NaN or infinite coordinates give `[0, 0, 0, 1]`. + #[inline] + pub fn sample(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + return [0.0, 0.0, 0.0, 1.0]; + }; + let fx = u * self.w as f32 - 0.5; + let fy = v * self.h as f32 - 0.5; + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - x0, fy - y0); + let (x0, y0) = (x0 as i64, y0 as i64); + let taps = [((1.0 - tx) * (1.0 - ty), x0, y0), (tx * (1.0 - ty), x0 + 1, y0), ((1.0 - tx) * ty, x0, y0 + 1), (tx * ty, x0 + 1, y0 + 1)]; + // Summed in f64: the rounded weights can add up to slightly more than 1, which would + // overflow a finite HDR value near `f32::MAX` in f32. A finite sum is clamped to the f32 + // range; an infinite texel still gives an infinite or NaN sample. + let mut o = [0.0f64; 4]; + for (weight, x, y) in taps { + if weight == 0.0 { + continue; + } + let p = self.get(x, y, tile); + for (o, p) in o.iter_mut().zip(p) { + *o += f64::from(weight) * f64::from(p); + } + } + o.map(|v| if v.is_finite() { v.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32 } else { v as f32 }) + } + + #[inline] + pub fn sample_gray(&self, u: f32, v: f32, tile: bool) -> f32 { + let p = self.sample(u, v, tile); + match self.kind { + Kind::Gray => p[0], + Kind::Color => luminance(p), + } + } + + /// Nearest sample at normalized `(u, v)`: the texel `floor(u × w)`, wrapped or clamped. NaN or + /// infinite coordinates give `[0, 0, 0, 1]`. + #[inline] + pub fn sample_nearest(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + return [0.0, 0.0, 0.0, 1.0]; + }; + let (x, y) = ((u * self.w as f32).floor() as i64, (v * self.h as f32).floor() as i64); + // A repeated coordinate is below 1, so its texel is below the size even where `u × w` + // rounds up to it. + let (x, y) = if tile { (x.min(i64::from(self.w) - 1), y.min(i64::from(self.h) - 1)) } else { (x, y) }; + self.get(x, y, tile) + } + + /// Map every pixel (as RGBA) to a new image of `kind`, same size. When a result of that size + /// would be over `isize::MAX` bytes, which only an image allowed by raised [`Limits`] can + /// reach, each side is clamped to `1..=MAX_SIDE` and the result maps the top-left part of this + /// image. [`Image::try_map`] returns [`ImageError::TooLarge`] instead. + pub fn map(&self, kind: Kind, f: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Image { + Image::build(self.w, self.h, kind, |x, y| f(self.get(i64::from(x), i64::from(y), false))) + } + + /// [`Image::map`] with the new image checked against `limits` and its memory reserved first. + pub fn try_map(&self, kind: Kind, limits: &Limits, f: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Result<Image, ImageError> { + Image::try_build(self.w, self.h, kind, limits, |x, y| f(self.get(i64::from(x), i64::from(y), false))) + } + + /// [`Image::to_kind`] with the result checked against `limits`, also when the kind is + /// unchanged, and the memory of a new image reserved first. + pub fn try_to_kind(&self, kind: Kind, limits: &Limits) -> Result<Image, ImageError> { + limits.check(self.w, self.h, kind)?; + match (self.kind, kind) { + (Kind::Gray, Kind::Gray) | (Kind::Color, Kind::Color) => Ok(self.clone()), + (Kind::Color, Kind::Gray) => self.try_map(Kind::Gray, limits, |p| [luminance(p), 0.0, 0.0, 0.0]), + (Kind::Gray, Kind::Color) => self.try_map(Kind::Color, limits, |p| p), + } + } + + /// This image as grayscale (luminance of a color image), same size. + pub fn to_gray(&self) -> Image { + match self.kind { + Kind::Gray => self.clone(), + Kind::Color => self.map(Kind::Gray, |p| [luminance(p), 0.0, 0.0, 0.0]), + } + } + + /// This image as RGBA (gray copied to RGB, alpha 1). A gray image goes through + /// [`Image::map`], so a result over `isize::MAX` bytes is clamped as `map` describes. + pub fn to_color(&self) -> Image { + match self.kind { + Kind::Color => self.clone(), + Kind::Gray => self.map(Kind::Color, |p| p), + } + } + + /// [`Image::to_gray`] or [`Image::to_color`]. + pub fn to_kind(&self, kind: Kind) -> Image { + match kind { + Kind::Gray => self.to_gray(), + Kind::Color => self.to_color(), + } + } + + /// Resample to `w × h`, each side clamped to `1..=MAX_SIDE`: a box average when both sides + /// shrink by whole factors, otherwise bilinear samples at the new pixel centers. + pub fn resize(&self, w: u32, h: u32, tile: bool) -> Image { + let (w, h) = clamp_size(w, h); + if w == self.w && h == self.h { + return self.clone(); + } + Image::build(w, h, self.kind, self.resampler(w, h, tile)) + } + + /// [`Image::resize`] without the clamp: the new size is checked against `limits`, also when it + /// equals the current size, and its memory reserved first. + pub fn try_resize(&self, w: u32, h: u32, tile: bool, limits: &Limits) -> Result<Image, ImageError> { + limits.check(w, h, self.kind)?; + if w == self.w && h == self.h { + return Ok(self.clone()); + } + Image::try_build(w, h, self.kind, limits, self.resampler(w, h, tile)) + } + + /// The pixel function of a resample to `w × h`, both at least 1. + fn resampler(&self, w: u32, h: u32, tile: bool) -> Box<dyn Fn(u32, u32) -> [f32; 4] + Sync + '_> { + let (w, h) = (w.max(1), h.max(1)); + if w <= self.w && h <= self.h && self.w.is_multiple_of(w) && self.h.is_multiple_of(h) { + let (fx, fy) = (i64::from(self.w / w), i64::from(self.h / h)); + let inv = 1.0 / (fx * fy) as f64; + return Box::new(move |x, y| { + // Summed in f64, so finite HDR values near `f32::MAX` average without overflow. + let mut s = [0.0f64; 4]; + for j in 0..fy { + for i in 0..fx { + let p = self.get(i64::from(x) * fx + i, i64::from(y) * fy + j, tile); + for (s, p) in s.iter_mut().zip(p) { + *s += f64::from(p); + } + } + } + s.map(|v| (v * inv) as f32) + }); + } + let (iw, ih) = (1.0 / w as f32, 1.0 / h as f32); + Box::new(move |x, y| self.sample((x as f32 + 0.5) * iw, (y as f32 + 0.5) * ih, tile)) + } + + /// Raw float access for gray images (`None` for color). + pub fn gray_data(&self) -> Option<&[f32]> { + (self.kind == Kind::Gray).then_some(self.data.as_slice()) + } + + /// 8-bit sRGB-encoded RGBA for display (gray shown as is; color through the sRGB curve). + /// Values are clamped to `0..=1` first; NaN becomes 0. The result has 4 bytes per pixel, never + /// more than the float data's own bytes. + pub fn to_rgba8_display(&self) -> Vec<u8> { + let mut out = vec![0u8; self.display_len()]; + self.fill_display(&mut out); + out + } + + /// [`Image::to_rgba8_display`] with its memory reserved first. + pub fn try_to_rgba8_display(&self) -> Result<Vec<u8>, ImageError> { + let len = self.display_len(); + let mut out = Vec::new(); + out.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(self.w, self.h))?; + out.resize(len, 0); + self.fill_display(&mut out); + Ok(out) + } + + /// Bytes of the display copy: 4 per pixel, never more than the float data's own bytes. + fn display_len(&self) -> usize { + self.data.len() / self.channels() * 4 + } + + fn fill_display(&self, out: &mut [u8]) { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let pixel = |(i, px): (usize, &mut [u8])| match self.kind { + Kind::Gray => { + let v = q(self.data.get(i).copied().unwrap_or(0.0)); + px.copy_from_slice(&[v, v, v, 255]); + } + Kind::Color => { + let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + px.copy_from_slice(&[q(linear_to_srgb(s[0])), q(linear_to_srgb(s[1])), q(linear_to_srgb(s[2])), q(s[3])]); + } + }; + #[cfg(feature = "parallel")] + out.par_chunks_mut(4).enumerate().for_each(pixel); + #[cfg(not(feature = "parallel"))] + out.chunks_mut(4).enumerate().for_each(pixel); + } + + /// Mean of each channel (as RGBA), e.g. for tests and auto levels. A NaN or infinite pixel + /// makes its channel's mean non-finite. + pub fn mean(&self) -> [f32; 4] { + let c = self.channels(); + let n = f64::from(self.w) * f64::from(self.h); + let mut s = [0f64; 4]; + for px in self.data.chunks(c) { + for (k, v) in px.iter().enumerate() { + s[k] += f64::from(*v); + } + } + if c == 1 { + let m = (s[0] / n) as f32; + return [m, m, m, 1.0]; + } + s.map(|v| (v / n) as f32) + } + + /// Minimum and maximum over all channels (alpha excluded). NaN values are skipped; `(0, 0)` + /// when every value is NaN. + pub fn range(&self) -> (f32, f32) { + let c = self.channels(); + let mut lo = f32::INFINITY; + let mut hi = f32::NEG_INFINITY; + for px in self.data.chunks(c) { + for v in px.iter().take(c.min(3)) { + lo = lo.min(*v); + hi = hi.max(*v); + } + } + if lo > hi { (0.0, 0.0) } else { (lo, hi) } + } +} + +/// Rec. 709 luminance of a linear RGB(A) pixel. +#[inline] +pub fn luminance(p: [f32; 4]) -> f32 { + 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2] +} + +/// The sRGB encoding of a linear value. NaN stays NaN. +#[inline] +pub fn linear_to_srgb(v: f32) -> f32 { + if v.is_nan() || v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } +} + +/// The linear value of an sRGB-encoded value. NaN stays NaN. +#[inline] +pub fn srgb_to_linear(v: f32) -> f32 { + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +/// Encode the bitmap name and its requested color space without ambiguity. +/// Plain sRGB names remain readable by simple resource callbacks. +pub fn resource_key(name: &str, linear: bool) -> String { + if linear { + format!("\u{1}L{name}") + } else if name.starts_with('\u{1}') { + format!("\u{1}S{name}") + } else { + name.to_string() + } +} + +/// Split a key made by [`resource_key`] into its name and data-map flag. +pub fn split_resource_key(key: &str) -> (&str, bool) { + if let Some(name) = key.strip_prefix("\u{1}L") { + (name, true) + } else if let Some(name) = key.strip_prefix("\u{1}S") { + (name, false) + } else { + (key, false) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sample_survives_huge_coordinates() { + let img = Image::gray(8, 8, |x, _| x as f32); + for u in [1.0e30_f32, -1.0e30, f32::MAX, f32::MIN] { + for tile in [true, false] { + let p = img.sample(u, u, tile); + assert!(p.iter().all(|c| c.is_finite())); + } + } + } + + #[test] + fn resource_keys_round_trip() { + for name in ["n", "", "\u{1}Lnormal", "\u{1}Sn", "n\u{1}linear"] { + for linear in [false, true] { + assert_eq!(split_resource_key(&resource_key(name, linear)), (name, linear)); + } + } + } + + #[test] + fn sample_wraps_and_clamps() { + let img = Image::gray(4, 1, |x, _| x as f32); + assert_eq!(img.get(-1, 0, true)[0], 3.0); + assert_eq!(img.get(-1, 0, false)[0], 0.0); + // Halfway between the last and the (wrapped) first pixel. + assert!((img.sample(1.0, 0.5, true)[0] - 1.5).abs() < 1e-5); + } + + #[test] + fn resize_box_and_bilinear() { + let img = Image::gray(4, 4, |x, _| if x < 2 { 0.0 } else { 1.0 }); + let small = img.resize(2, 2, true); + assert_eq!(small.data.as_slice(), &[0.0, 1.0, 0.0, 1.0]); + let big = small.resize(8, 8, false); + assert_eq!(big.w, 8); + assert!(big.data[0] < big.data[7]); + } + + #[test] + fn hostile_sizes_are_clamped() { + let img = Image::filled(0, u32::MAX, Kind::Gray, [0.5; 4]); + assert_eq!((img.w, img.h), (1, MAX_SIDE)); + assert_eq!(img.sample(f32::NAN, 0.0, true), [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn conversions() { + let c = Image::filled(2, 2, Kind::Color, [1.0, 1.0, 1.0, 1.0]); + assert!((c.to_gray().data[0] - 1.0).abs() < 1e-5); + assert_eq!(c.to_rgba8_display()[0], 255); + } + + /// Texel values 0, 5 and 1: the blend of the last and first texels (0.5) differs from the + /// middle texel (5), so a wrong repeat period shows. + fn stripe() -> Image { + Image::gray(3, 1, |x, _| [0.0, 5.0, 1.0][x as usize]) + } + + #[test] + fn repeat_keeps_its_period_at_large_coordinates() { + let img = stripe(); + // Every whole number repeats u = 0, which falls halfway between the last and first texels. + let at_zero = img.sample(0.0, 0.5, true)[0]; + assert!((at_zero - 0.5).abs() < 1e-6); + for u in [1.0e9_f32, -1.0e9, 4.0e9, 3.0e12] { + assert_eq!(img.sample(u, 0.5, true)[0], at_zero, "bilinear u = {u}"); + assert_eq!(img.sample_nearest(u, 0.5, true)[0], 0.0, "nearest u = {u}"); + } + assert_eq!(img.sample_nearest(1.0e19, 0.5, true)[0], 0.0); + assert_eq!(img.sample_nearest(-1.0e19, 0.5, true)[0], 0.0); + } + + #[test] + fn clamp_selects_the_edges_at_large_coordinates() { + let img = stripe(); + for u in [2.0_f32, 1.0e9, 1.0e19, f32::MAX] { + assert_eq!(img.sample(u, 0.5, false)[0], 1.0); + assert_eq!(img.sample_nearest(u, 0.5, false)[0], 1.0); + } + for u in [-1.0_f32, -1.0e9, -1.0e19, f32::MIN] { + assert_eq!(img.sample(u, 0.5, false)[0], 0.0); + assert_eq!(img.sample_nearest(u, 0.5, false)[0], 0.0); + } + } + + #[test] + fn nearest_follows_the_texel_floor() { + let img = Image::gray(4, 1, |x, _| x as f32); + // floor(u × 4): u = 1.0 repeats to texel 0 and clamps to texel 3. + assert_eq!(img.sample_nearest(0.24, 0.5, true)[0], 0.0); + assert_eq!(img.sample_nearest(0.25, 0.5, true)[0], 1.0); + assert_eq!(img.sample_nearest(1.0, 0.5, true)[0], 0.0); + assert_eq!(img.sample_nearest(1.0, 0.5, false)[0], 3.0); + assert_eq!(img.sample_nearest(-0.01, 0.5, true)[0], 3.0); + } + + #[test] + fn bilinear_weights_follow_the_fractional_texel_coordinate() { + // u × 4 − 0.5 = 1.25: texel 1 weighted 0.75 and texel 2 weighted 0.25. + let img = Image::gray(4, 1, |x, _| [0.0, 2.0, 6.0, 0.0][x as usize]); + assert!((img.sample(1.75 / 4.0, 0.5, false)[0] - 3.0).abs() < 1e-6); + // Two axes: the four texels of a 2 × 2 image at the image center weigh a quarter each. + let sq = Image::gray(2, 2, |x, y| [1.0, 3.0, 5.0, 11.0][(y * 2 + x) as usize]); + assert!((sq.sample(0.5, 0.5, false)[0] - 5.0).abs() < 1e-6); + } + + #[test] + fn small_negative_coordinates_repeat_to_the_last_texel() { + let img = Image::gray(4, 1, |x, _| x as f32); + for u in [-1.0e-8_f32, -1.0e-30, -f32::MIN_POSITIVE] { + assert_eq!(img.sample_nearest(u, 0.5, true)[0], 3.0, "u = {u}"); + assert!((img.sample(u, 0.5, true)[0] - 1.5).abs() < 1e-5, "u = {u}"); + } + let wide = Image::gray(MAX_SIDE, 1, |x, _| x as f32); + assert_eq!(wide.sample_nearest(-1.0e-8, 0.5, true)[0], (MAX_SIDE - 1) as f32); + } + + #[test] + fn bilinear_ignores_zero_weight_texels_and_does_not_overflow() { + let l = Limits::default(); + let Ok(img) = Image::from_data(2, 1, Kind::Gray, vec![1.0, f32::INFINITY], &l) else { panic!("valid 2 x 1 image") }; + // The center of texel 0 gives texel 0, though its neighbor is infinite. + assert_eq!(img.sample(0.25, 0.5, false)[0], 1.0); + let Ok(hdr) = Image::from_data(2, 1, Kind::Gray, vec![f32::MAX, -f32::MAX], &l) else { panic!("valid 2 x 1 image") }; + assert_eq!(hdr.sample(0.5, 0.5, false)[0], 0.0); + // Rounded weights can sum past 1; a constant image of the largest float stays finite. + let max = Image::filled(2, 2, Kind::Gray, [f32::MAX; 4]); + let t = 0.5 + 2.0_f32.powi(-24); + for tile in [false, true] { + assert!(max.sample(0.250_012_5, t, tile)[0].is_finite(), "tile = {tile}"); + assert_eq!(max.sample(t, t, tile)[0], f32::MAX, "tile = {tile}"); + } + } + + #[test] + fn equality_does_not_depend_on_buffer_sharing() { + let img = Image::filled(2, 1, Kind::Gray, [f32::NAN; 4]); + let rebuilt = Image::filled(2, 1, Kind::Gray, [f32::NAN; 4]); + // NaN pixels compare unequal as floats do, whether or not the buffer is shared. + assert_ne!(img, rebuilt); + assert_ne!(img, img.clone()); + let finite = Image::filled(2, 1, Kind::Gray, [0.5; 4]); + assert_eq!(finite, finite.clone()); + assert_eq!(finite, Image::filled(2, 1, Kind::Gray, [0.5; 4])); + } + + #[test] + fn box_shrink_averages_large_hdr_values() { + let img = Image::filled(2, 2, Kind::Color, [f32::MAX, -f32::MAX, 1.0, 1.0]); + assert_eq!(img.resize(1, 1, false).data(), &[f32::MAX, -f32::MAX, 1.0, 1.0]); + } + + #[test] + fn fallible_operations_check_the_limits() { + let img = Image::gray(4, 4, |x, y| (x + 4 * y) as f32); + let l = Limits::default(); + assert_eq!(img.try_resize(2, 2, true, &l), Ok(img.resize(2, 2, true))); + assert_eq!(img.try_resize(7, 3, false, &l), Ok(img.resize(7, 3, false))); + assert_eq!(img.try_resize(0, 2, false, &l), Err(ImageError::BadSize(0, 2))); + let small = Limits { max_bytes: 100, ..Limits::default() }; + assert_eq!(img.try_resize(8, 8, false, &small), Err(ImageError::TooLarge(8, 8))); + assert_eq!(img.try_to_kind(Kind::Color, &small), Err(ImageError::TooLarge(4, 4))); + assert_eq!(img.try_to_kind(Kind::Color, &l), Ok(img.to_color())); + assert_eq!(img.try_to_kind(Kind::Gray, &small), Ok(img.clone())); + assert_eq!(img.try_map(Kind::Gray, &l, |p| [p[0] * 2.0; 4]), Ok(img.map(Kind::Gray, |p| [p[0] * 2.0; 4]))); + assert_eq!(img.try_to_rgba8_display(), Ok(img.to_rgba8_display())); + } + + #[test] + fn unchanged_results_are_checked_against_the_limits() { + let img = Image::gray(4, 4, |x, y| (x + 4 * y) as f32); + let tiny = Limits { max_pixels: 8, ..Limits::default() }; + assert_eq!(img.try_resize(4, 4, false, &tiny), Err(ImageError::TooLarge(4, 4))); + assert_eq!(img.try_to_kind(Kind::Gray, &tiny), Err(ImageError::TooLarge(4, 4))); + let narrow = Limits { max_side: 3, ..Limits::default() }; + assert_eq!(img.try_resize(4, 4, false, &narrow), Err(ImageError::BadSize(4, 4))); + } + + #[test] + fn generate_uv_spans_the_clamped_size() { + let img = Image::generate_uv(MAX_SIDE + 100, 1, Kind::Gray, |u, _| [u, 0.0, 0.0, 0.0]); + assert_eq!(img.w, MAX_SIDE); + let last = img.data[MAX_SIDE as usize - 1]; + assert!((last - (MAX_SIDE as f32 - 0.5) / MAX_SIDE as f32).abs() < 1e-6, "{last}"); + } + + #[test] + fn checked_sizes_reject_zero_and_long_sides() { + let l = Limits::default(); + assert_eq!(Image::try_filled(0, 4, Kind::Gray, [0.0; 4], &l), Err(ImageError::BadSize(0, 4))); + assert_eq!(Image::try_filled(4, 0, Kind::Color, [0.0; 4], &l), Err(ImageError::BadSize(4, 0))); + assert_eq!(Image::from_data(0, 1, Kind::Gray, Vec::new(), &l), Err(ImageError::BadSize(0, 1))); + assert_eq!(Image::try_generate(MAX_SIDE + 1, 1, Kind::Gray, &l, |_, _| [0.0; 4]), Err(ImageError::BadSize(MAX_SIDE + 1, 1))); + assert!(Image::try_filled(3, 2, Kind::Color, [0.25; 4], &l).is_ok_and(|i| i.data().len() == 24 && i.width() == 3)); + } + + #[test] + fn checked_sizes_respect_the_pixel_and_byte_limits() { + let l = Limits { max_bytes: 1000, ..Limits::default() }; + assert_eq!(l.check(15, 16, Kind::Gray), Ok(240)); + assert_eq!(l.check(16, 16, Kind::Gray), Err(ImageError::TooLarge(16, 16))); + assert_eq!(Image::try_filled(8, 8, Kind::Color, [0.0; 4], &l), Err(ImageError::TooLarge(8, 8))); + let l = Limits { max_pixels: 100, ..Limits::default() }; + assert_eq!(l.check(10, 10, Kind::Color), Ok(400)); + assert_eq!(l.check(10, 11, Kind::Gray), Err(ImageError::TooLarge(10, 11))); + // The default limits accept a full 8192 × 8192 color plane and nothing longer. + assert_eq!(Limits::default().check(MAX_SIDE, MAX_SIDE, Kind::Color), Ok(1 << 28)); + } + + #[test] + fn checked_sizes_do_not_overflow() { + let open = Limits { max_side: u32::MAX, max_pixels: u64::MAX, max_bytes: u64::MAX }; + assert_eq!(open.check(u32::MAX, u32::MAX, Kind::Color), Err(ImageError::TooLarge(u32::MAX, u32::MAX))); + assert_eq!(open.check(u32::MAX, u32::MAX, Kind::Gray), Err(ImageError::TooLarge(u32::MAX, u32::MAX))); + } + + /// `isize::MAX` on a 32-bit target such as `wasm32`. + const BOUND_32: u64 = i32::MAX as u64; + + #[test] + fn checked_sizes_respect_target_isize_bound() { + let open = Limits { max_side: u32::MAX, max_pixels: u64::MAX, max_bytes: u64::MAX }; + // 16,385 × 8,192 gray is 512 MiB and 16 KiB; its color form is over 2 GiB. + assert_eq!(open.check_within(16_385, 8_192, Kind::Gray, BOUND_32), Ok(16_385 * 8_192)); + assert_eq!(open.check_within(16_385, 8_192, Kind::Color, BOUND_32), Err(ImageError::TooLarge(16_385, 8_192))); + assert_eq!(open.check_within(MAX_SIDE, MAX_SIDE, Kind::Color, BOUND_32), Ok(1 << 28)); + } + + #[test] + fn infallible_expansion_clamps_at_target_bound() { + assert_eq!(bounded_size(16_385, 8_192, Kind::Gray, BOUND_32), (16_385, 8_192, 16_385 * 8_192)); + assert_eq!(bounded_size(16_385, 8_192, Kind::Color, BOUND_32), (MAX_SIDE, MAX_SIDE, 1 << 28)); + assert_eq!(bounded_size(MAX_SIDE, MAX_SIDE, Kind::Color, BOUND_32), (MAX_SIDE, MAX_SIDE, 1 << 28)); + assert_eq!(bounded_size(3, 2, Kind::Color, BOUND_32), (3, 2, 24)); + // A bound below even the clamped size gives one pixel. + assert_eq!(bounded_size(16_385, 8_192, Kind::Color, 64), (1, 1, 4)); + assert_eq!(bounded_size(u32::MAX, u32::MAX, Kind::Gray, MAX_ALLOC_BYTES), (MAX_SIDE, MAX_SIDE, 1 << 26)); + } + + #[test] + fn checked_byte_len_rejects_arithmetic_overflow() { + assert_eq!(checked_byte_len(u32::MAX, u32::MAX, Kind::Color), None); + assert_eq!(checked_byte_len(u32::MAX, u32::MAX, Kind::Gray), None); + assert_eq!(checked_byte_len(MAX_SIDE, MAX_SIDE, Kind::Color), Some(1 << 30)); + } + + #[test] + fn from_data_checks_the_length() { + let l = Limits::default(); + assert_eq!(Image::from_data(2, 2, Kind::Color, vec![0.0], &l), Err(ImageError::BadDataLength { expected: 16, found: 1 })); + assert_eq!(Image::from_data(2, 2, Kind::Color, vec![0.0; 17], &l), Err(ImageError::BadDataLength { expected: 16, found: 17 })); + let img = Image::from_data(2, 1, Kind::Gray, vec![-2.0, 3.5], &l); + assert!(img.is_ok_and(|i| i.get(0, 0, false)[0] == -2.0 && i.get(1, 0, false)[0] == 3.5)); + } + + #[test] + fn non_finite_pixels_have_defined_results() { + let l = Limits::default(); + let img = Image::from_data(1, 1, Kind::Color, vec![f32::NAN, f32::INFINITY, -1.0, 2.0], &l); + let Ok(img) = img else { panic!("valid 1 x 1 image") }; + assert_eq!(img.to_rgba8_display(), vec![0, 255, 0, 255]); + let g = Image::from_data(3, 1, Kind::Gray, vec![f32::NAN, -4.0, 8.0], &l); + let Ok(g) = g else { panic!("valid 3 x 1 image") }; + assert_eq!(g.range(), (-4.0, 8.0)); + assert!(g.mean()[0].is_nan()); + } + + #[test] + fn srgb_encoding_keeps_nan() { + assert!(linear_to_srgb(f32::NAN).is_nan()); + assert!(srgb_to_linear(f32::NAN).is_nan()); + assert_eq!(linear_to_srgb(0.0), 0.0); + assert!((linear_to_srgb(1.0) - 1.0).abs() < 1e-6); + assert!((srgb_to_linear(linear_to_srgb(0.5)) - 0.5).abs() < 1e-6); + } + + #[test] + fn whole_factor_shrink_stays_exact_with_custom_limits() { + let l = Limits { max_side: 16, ..Limits::default() }; + let img = Image::try_generate(4, 2, Kind::Color, &l, |x, y| [x as f32, y as f32, 0.0, 1.0]); + let Ok(img) = img else { panic!("valid 4 x 2 image") }; + let half = img.resize(2, 1, false); + assert_eq!(half.data(), &[0.5, 0.5, 0.0, 1.0, 2.5, 0.5, 0.0, 1.0]); + assert_eq!(img.to_gray().width(), 4); + } +} diff --git a/crates/timeline/src/fcpxml.rs b/crates/timeline/src/fcpxml.rs index 198574718..4a255ba43 100644 --- a/crates/timeline/src/fcpxml.rs +++ b/crates/timeline/src/fcpxml.rs @@ -125,6 +125,16 @@ struct Asset { has_audio: bool, } +// Bound semantic resource chains separately from XML syntax: flat media resources can +// reference one another without adding any XML nesting. +const MAX_MEDIA_DEPTH: usize = 64; +const MAX_XML_DEPTH: usize = 128; +// Retrying truncated resources is useful at shallower depths, but must remain bounded. +const MAX_REIMPORTS: usize = 4096; +// A hostile document may reference the same large cached graph repeatedly. Bound total +// reachability work, not just one walk, and refuse reuse when safety cannot be established. +const MAX_CACHE_EDGES: usize = 1_000_000; + struct Imp<'a, 'c, 'r> { b: Builder<'c>, opts: &'a ImportOptions<'a>, @@ -135,6 +145,13 @@ struct Imp<'a, 'c, 'r> { media_nodes: HashMap<String, Node<'a>>, media_items: HashMap<String, ItemId>, media_active: HashSet<String>, + depth_hits: usize, + // Depths at which a cached resource was truncated. A retry may improve neither limit + // at the expense of the other, and reuses the same item so earlier references stay valid. + media_truncated_at: HashMap<String, (usize, usize)>, + reimports_left: usize, + cache_edges_left: usize, + depth: usize, effects: HashMap<String, String>, } @@ -186,6 +203,11 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result<I media_nodes: HashMap::new(), media_items: HashMap::new(), media_active: HashSet::new(), + depth_hits: 0, + media_truncated_at: HashMap::new(), + reimports_left: MAX_REIMPORTS, + cache_edges_left: MAX_CACHE_EDGES, + depth: 0, effects: HashMap::new(), }; if let Some(res) = child(root, "resources") { @@ -229,7 +251,7 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result<I "project" => { if let Some(s) = child(c, "sequence") { let name = c.attribute("name").unwrap_or("Project"); - let id = imp.sequence(s, name, Some(bin)); + let id = imp.sequence(s, name, Some(bin), None); imp.b.top.push(id); } } @@ -244,7 +266,7 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result<I } for p in children(root, "project") { if let Some(s) = child(p, "sequence") { - let id = imp.sequence(s, p.attribute("name").unwrap_or("Project"), None); + let id = imp.sequence(s, p.attribute("name").unwrap_or("Project"), None, None); imp.b.top.push(id); } } @@ -308,34 +330,100 @@ impl<'a> Imp<'a, '_, '_> { Some(a) } + /// A rebuilt item retains its ID. A cached ancestor that already points to it must + /// not be inserted underneath it, even when the resource names are not directly active. + fn cache_reaches_active(&mut self, root: ItemId) -> bool { + let active: HashSet<ItemId> = self.media_active.iter().filter_map(|id| self.media_items.get(id).copied()).collect(); + if active.is_empty() { + return false; + } + let mut seen = HashSet::from([root]); + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + if active.contains(&id) { + return true; + } + let Some(seq) = self.b.p.sequence(id) else { continue }; + for item in seq.all_tracks().flat_map(|track| &track.items) { + if self.cache_edges_left == 0 { + return true; + } + self.cache_edges_left -= 1; + if active.contains(&item.item) { + return true; + } + if seen.insert(item.item) { + pending.push(item.item); + } + } + } + false + } + /// Nested sequence from a `<media>` resource. fn media(&mut self, id: &str) -> Option<ItemId> { - if let Some(i) = self.media_items.get(id) { - return Some(*i); - } - let n = *self.media_nodes.get(id)?; - let s = child(n, "sequence")?; - if !self.media_active.insert(id.into()) { + // Check before the cache: a truncated resource may already have an item while it + // is being rebuilt, but a back-edge must never turn that item into a self-cycle. + if self.media_active.contains(id) { self.report.warn(format!("recursive FCPXML media resource {id:?} ignored")); return None; } + let depth = self.media_active.len(); + let mut again = None; + if let Some(i) = self.media_items.get(id).copied() { + // Imported with a nested one cut off: import it again (into the same item) where that + // one now fits. + let shallower = self + .media_truncated_at + .get(id) + .is_some_and(|&(media, xml)| depth <= media && self.depth <= xml && (depth < media || self.depth < xml)) + && !self.media_active.contains(id); + if !shallower || self.reimports_left == 0 { + if self.cache_reaches_active(i) { + self.depth_hits += 1; + self.report.warn(format!( + "FCPXML cached media {id:?} could form a recursive graph or exceeds the cache traversal budget; imported as a gap" + )); + return None; + } + return Some(i); + } + self.reimports_left -= 1; + again = Some(i); + } + let n = *self.media_nodes.get(id)?; + let s = child(n, "sequence")?; + // The active set is the current nesting chain: a long acyclic chain of compound clips + // would otherwise recurse once per resource. + if depth >= MAX_MEDIA_DEPTH { + self.depth_hits += 1; + self.report.warn(format!("FCPXML media resource {id:?} is nested too deeply; imported as a gap")); + return None; + } + self.media_active.insert(id.into()); // Mark the resource before descending: a compound clip can reference itself through a // ref-clip before a completed sequence is available to cache. let name = n.attribute("name").unwrap_or("Compound Clip").to_string(); - let item = self.sequence(s, &name, None); + let hits_before = self.depth_hits; + let item = self.sequence(s, &name, None, again); self.media_active.remove(id); self.media_items.insert(id.into(), item); + if self.depth_hits > hits_before { + self.media_truncated_at.insert(id.into(), (depth, self.depth)); + } else { + self.media_truncated_at.remove(id); + } Some(item) } - fn sequence(&mut self, s: Node<'a>, name: &str, bin: Option<BinId>) -> ItemId { + fn sequence(&mut self, s: Node<'a>, name: &str, bin: Option<BinId>, reuse: Option<ItemId>) -> ItemId { let (rate, w, h) = s.attribute("format").and_then(|f| self.formats.get(f)).copied().unwrap_or((FrameRate::default(), 1920, 1080)); let df = s.attribute("tcFormat") == Some("DF"); let mut settings = settings_for(rate, w, h, df); if let Some(sr) = s.attribute("audioRate").and_then(parse_audio_rate) { settings.sample_rate = sr; } - let id = self.b.reserve_sequence(name, settings.clone(), bin); + let id = reuse.unwrap_or_else(|| self.b.reserve_sequence(name, settings.clone(), bin)); let mut seq = empty_sequence(settings); let tc_start = attr_time(s, "tcStart").unwrap_or(Tick::ZERO); seq.start_timecode = rate.frame_at(tc_start); @@ -353,7 +441,19 @@ impl<'a> Imp<'a, '_, '_> { /// Lay out a storyline. `origin` maps the storyline's offsets to timeline time /// (`timeline = origin + offset`). `lane` is the storyline's lane (0 = primary). + /// Refuses nesting past [`MAX_XML_DEPTH`]. fn storyline(&mut self, seq: &mut Sequence, ctx: &Ctx, spine: Node<'a>, origin: Tick, lane: i32, primary: bool) { + if self.depth >= MAX_XML_DEPTH { + self.depth_hits += 1; + self.report.warn(format!("XML storylines are nested too deeply (more than {MAX_XML_DEPTH}); deeper clips were skipped")); + return; + } + self.depth += 1; + self.storyline_inner(seq, ctx, spine, origin, lane, primary); + self.depth -= 1; + } + + fn storyline_inner(&mut self, seq: &mut Sequence, ctx: &Ctx, spine: Node<'a>, origin: Tick, lane: i32, primary: bool) { // (timeline start, timeline end, video clip on this storyline's track) let mut laid: Vec<(Tick, Tick, Option<ClipId>)> = Vec::new(); let mut transitions: Vec<(usize, Node)> = Vec::new(); @@ -421,7 +521,20 @@ impl<'a> Imp<'a, '_, '_> { } /// Lay out one storyline element at timeline time `t0`. Returns (timeline end, video clip). + /// Refuses nesting past [`MAX_XML_DEPTH`]. fn element(&mut self, seq: &mut Sequence, ctx: &Ctx, el: Node<'a>, t0: Tick, lane: i32, primary: bool) -> (Tick, Option<ClipId>) { + if self.depth >= MAX_XML_DEPTH { + self.depth_hits += 1; + self.report.warn(format!("XML elements are nested too deeply (more than {MAX_XML_DEPTH}); deeper clips were skipped")); + return (t0, None); + } + self.depth += 1; + let out = self.element_inner(seq, ctx, el, t0, lane, primary); + self.depth -= 1; + out + } + + fn element_inner(&mut self, seq: &mut Sequence, ctx: &Ctx, el: Node<'a>, t0: Tick, lane: i32, primary: bool) -> (Tick, Option<ClipId>) { let tag = el.name(); let dur = attr_time(el, "duration").unwrap_or(Tick::ZERO); let local_start = attr_time(el, "start").unwrap_or(Tick::ZERO); diff --git a/crates/timeline/tests/it/fcpxml.rs b/crates/timeline/tests/it/fcpxml.rs index 59baf660f..65dc6827b 100644 --- a/crates/timeline/tests/it/fcpxml.rs +++ b/crates/timeline/tests/it/fcpxml.rs @@ -503,3 +503,114 @@ fn relative_media_urls_are_percent_decoded() { let boats = &p.sequence(only_seq(&imp)).unwrap().video_tracks[0].items[1]; assert_eq!(media_key(p, boats.item), "/proj/media/boats b.mov"); } + +// Parity regressions from FilmCraft e6df318 (including #4799), adapted to the neutral model. +#[test] +fn media_cut_off_by_the_depth_limit_is_complete_when_reached_higher_up() { + // m0 … m64 nest one inside the next. Project A reaches m63 at the depth limit, so m64 is left + // out of it; project B refers to m63 directly, where m64 fits, and must not get the cut-off copy. + let mut media = String::new(); + for i in 0..64 { + media.push_str(&format!( + r#"<media id="m{i}" name="M{i}"><sequence format="r1"><spine><ref-clip ref="m{}" offset="0s" start="0s" duration="1s"/></spine></sequence></media>"#, + i + 1 + )); + } + media.push_str(r#"<media id="m64" name="M64"><sequence format="r1"><spine/></sequence></media>"#); + let xml = format!( + r#"<fcpxml version="1.10"><resources><format id="r1" frameDuration="1/24s" width="1920" height="1080"/>{media}</resources> + <library><event> + <project name="A"><sequence format="r1"><spine><ref-clip ref="m0" offset="0s" start="0s" duration="1s"/></spine></sequence></project> + <project name="B"><sequence format="r1"><spine><ref-clip ref="m63" offset="0s" start="0s" duration="1s"/></spine></sequence></project> + </event></library></fcpxml>"# + ); + let (imp, rep) = import(xml.as_bytes(), Format::Fcpxml, None).unwrap(); + assert!(rep.mentions("nested too deeply"), "{rep:?}"); + let m63 = imp.project.items.values().find(|i| i.name == "M63").and_then(|i| imp.project.sequence(i.id)).unwrap(); + assert_eq!(m63.video_tracks[0].items.len(), 1, "M63 keeps its nested M64"); +} + +#[test] +fn media_cut_off_by_xml_layout_is_complete_when_revisited_at_the_same_media_depth() { + // Both references have media-chain depth zero, but the first is reached through connected + // clips. Its resource must not remain cached as complete after the XML-layout guard fires. + for depth in [125, 126] { + let nested = format!( + "{}<ref-clip lane=\"1\" ref=\"m0\" offset=\"0s\" duration=\"1s\"/>{}", + "<gap lane=\"1\" offset=\"0s\" duration=\"1s\">".repeat(depth), + "</gap>".repeat(depth) + ); + let xml = format!( + r#"<fcpxml version="1.10"><resources> + <format id="r1" frameDuration="1/24s" width="1920" height="1080"/> + <media id="m0" name="M0"><sequence format="r1"><spine> + <ref-clip ref="m1" offset="0s" duration="1s"/> + </spine></sequence></media> + <media id="m1" name="M1"><sequence format="r1"><spine/></sequence></media> + </resources><library><event> + <project name="A"><sequence format="r1"><spine>{nested}</spine></sequence></project> + <project name="B"><sequence format="r1"><spine> + <ref-clip ref="m0" offset="0s" duration="1s"/> + </spine></sequence></project> + </event></library></fcpxml>"# + ); + let (imp, rep) = import(xml.as_bytes(), Format::Fcpxml, None).unwrap(); + assert!(rep.mentions("XML") && rep.mentions("nested"), "{rep:?}"); + let m0 = imp.project.items.values().find(|i| i.name == "M0").and_then(|i| imp.project.sequence(i.id)).unwrap(); + assert_eq!(m0.video_tracks[0].items.len(), 1, "M0 keeps its nested M1 after the shallower revisit"); + } +} + +#[test] +fn flat_resource_chain_is_bounded_even_when_xml_is_shallow() { + let mut media = String::new(); + for i in 0..512 { + media.push_str(&format!( + r#"<media id="m{i}" name="M{i}"><sequence><spine><ref-clip ref="m{}" duration="1s"/></spine></sequence></media>"#, + i + 1 + )); + } + let xml = format!( + r#"<fcpxml version="1.10"><resources>{media}</resources><project name="P"><sequence><spine><ref-clip ref="m0" duration="1s"/></spine></sequence></project></fcpxml>"# + ); + let (imp, rep) = import(xml.as_bytes(), Format::Fcpxml, None).unwrap(); + assert!(rep.mentions("nested too deeply"), "{rep:?}"); + assert!(imp.project.items.len() <= 65, "the flat resource graph is not expanded beyond the semantic limit"); +} + +#[test] +fn shallower_retry_does_not_link_a_cached_ancestor_back_to_the_rebuilt_item() { + let mut media = String::new(); + for i in 0..64 { + media.push_str(&format!( + r#"<media id="m{i}" name="M{i}"><sequence><spine><ref-clip ref="m{}" duration="1s"/></spine></sequence></media>"#, + (i + 1) % 64 + )); + } + let xml = format!( + r#"<fcpxml version="1.10"><resources>{media}</resources> + <project name="A"><sequence><spine><ref-clip ref="m0" duration="1s"/></spine></sequence></project> + <project name="B"><sequence><spine><ref-clip ref="m62" duration="1s"/></spine></sequence></project></fcpxml>"# + ); + let (imp, rep) = import(xml.as_bytes(), Format::Fcpxml, None).unwrap(); + assert!(rep.mentions("cached media"), "{rep:?}"); + // Check the final graph, not just the resource-name recursion stack during import. + fn visit(p: &Project, id: ItemId, active: &mut std::collections::HashSet<ItemId>, done: &mut std::collections::HashSet<ItemId>) { + if done.contains(&id) { + return; + } + assert!(active.insert(id), "cached media introduced a cycle at {id:?}"); + if let Some(seq) = p.sequence(id) { + for item in seq.all_tracks().flat_map(|track| &track.items) { + visit(p, item.item, active, done); + } + } + active.remove(&id); + done.insert(id); + } + let mut active = std::collections::HashSet::new(); + let mut done = std::collections::HashSet::new(); + for id in imp.project.items.keys() { + visit(&imp.project, *id, &mut active, &mut done); + } +} diff --git a/crates/ui/src/combo/tests.rs b/crates/ui/src/combo/tests.rs index 90e1afb15..fbef2413a 100644 --- a/crates/ui/src/combo/tests.rs +++ b/crates/ui/src/combo/tests.rs @@ -170,6 +170,7 @@ fn scene(ui: &mut egui::Ui, ours: bool) { } fn render(ours: bool, hover: Option<&str>, open: Option<&str>) -> image::RgbaImage { + let _gpu = crate::gpu_test_lock(); // Two of the combo boxes have no label: the scene compares looks, not names. let mut h = Harness::builder().with_size(egui::vec2(480.0, 700.0)).with_accessibility_check(false).build_ui(move |ui| scene(ui, ours)); h.run(); diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index e5a2d06c2..bbdd912ac 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -27,3 +27,14 @@ pub mod text; pub mod theme; pub use combo::ComboBox; + +/// Lets one unit test at a time hold a wgpu renderer. Each renderer creates its own Vulkan instance +/// and device. When one test uses its device while a test on another thread creates or destroys +/// one, the Vulkan loader now and then crashes the test binary with SIGSEGV. Take the lock before +/// building the harness (`let _gpu = crate::gpu_test_lock();`), so it is released after the harness +/// is dropped. A test that failed while holding it does not block the others. +#[cfg(test)] +pub(crate) fn gpu_test_lock() -> std::sync::MutexGuard<'static, ()> { + static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} diff --git a/crates/ui/src/tabs/dialog.rs b/crates/ui/src/tabs/dialog.rs index 292cbb4cf..e4820b042 100644 --- a/crates/ui/src/tabs/dialog.rs +++ b/crates/ui/src/tabs/dialog.rs @@ -123,6 +123,7 @@ mod tests { #[test] fn selected_tab_erases_a_baseline_centered_on_its_bottom_edge() { + let _gpu = crate::gpu_test_lock(); let mut h = egui_kittest::Harness::builder().with_size(Vec2::new(120.0, 80.0)).wgpu().build_ui(|ui| { ui.painter().rect_filled(ui.max_rect(), 0.0, Color32::WHITE); let rect = Rect::from_min_size(egui::pos2(10.0, 10.0), Vec2::new(100.0, 26.0)); diff --git a/crates/ui/tests/visual_regression.rs b/crates/ui/tests/visual_regression.rs index 532c9dfc7..87edb8b4f 100644 --- a/crates/ui/tests/visual_regression.rs +++ b/crates/ui/tests/visual_regression.rs @@ -9,6 +9,7 @@ mod fixtures; use std::path::PathBuf; +use std::sync::{Mutex, MutexGuard, PoisonError}; use egui::{Color32, Context, Event, FullOutput, Modifiers, PointerButton, Pos2, RawInput, Rect, Response, TextureId, Ui}; use egui_kittest::{TestRenderer, wgpu::WgpuTestRenderer}; @@ -28,6 +29,17 @@ struct Capture { meshes: Option<Vec<Mesh>>, } +/// Lets one test at a time hold a wgpu renderer. Each renderer creates its own Vulkan instance and +/// device. When one test uses its device while a test on another thread creates or destroys one, +/// the Vulkan loader now and then crashes the test binary with SIGSEGV. +static GPU_LOCK: Mutex<()> = Mutex::new(()); + +/// Take this before creating a renderer (`let _gpu = gpu_lock();`), so it is released after the +/// renderer is dropped. A test that failed while holding it does not block the others. +fn gpu_lock() -> MutexGuard<'static, ()> { + GPU_LOCK.lock().unwrap_or_else(PoisonError::into_inner) +} + fn context(theme: Theme, scale: f32) -> Context { let ctx = Context::default(); ctx.set_theme(theme.egui()); @@ -184,6 +196,7 @@ impl Artifacts { #[test] fn rendered_controls_match_independent_reference_pixels_and_meshes() { + let _gpu = gpu_lock(); let mut renderer = WgpuTestRenderer::new(); let mut artifacts = Artifacts::new("controls"); let mut count = 0; @@ -213,6 +226,7 @@ fn rendered_controls_match_independent_reference_pixels_and_meshes() { #[test] fn visual_comparisons_detect_color_spacing_and_stroke_mutations() { + let _gpu = gpu_lock(); let mut renderer = WgpuTestRenderer::new(); let mut artifacts = Artifacts::new("negative-controls"); let mut count = 0; @@ -241,6 +255,7 @@ fn toolbar_fitting_matches_literal_group_and_overflow_positions() { use craft_ui::layout::fit_toolbar; use egui::{Align, Layout, Stroke, StrokeKind, UiBuilder, pos2, vec2}; + let _gpu = gpu_lock(); let mut renderer = WgpuTestRenderer::new(); let mut artifacts = Artifacts::new("toolbar"); let mut count = 0; @@ -295,6 +310,7 @@ fn widget_palette_renders_all_five_states_with_existing_borders_and_expansion() use craft_ui::theme::WidgetPalette; use egui::{CornerRadius, Stroke, StrokeKind, pos2, vec2}; + let _gpu = gpu_lock(); let mut renderer = WgpuTestRenderer::new(); let mut artifacts = Artifacts::new("widget-palette"); for theme in [Theme::Light, Theme::Dark] { diff --git a/crates/update/src/self_update.rs b/crates/update/src/self_update.rs index 5356db4fa..a20f466ce 100644 --- a/crates/update/src/self_update.rs +++ b/crates/update/src/self_update.rs @@ -157,9 +157,11 @@ const CARGO_CACHE_MARKER: &str = "CACHEDIR.TAG"; /// `build.build-dir` set, `.rustc_info.json` and those subdirectories live elsewhere and the /// profile directory has only Cargo's `.cargo-lock` file, which is accepted too. /// `CACHEDIR.TAG` alone isn't Cargo-specific (the same signature marks any cache directory), so -/// it only corroborates that profile layout. +/// it only corroborates that profile layout. Extracted nextest archives retain their +/// `nextest/binaries-metadata.json` inventory rather than Cargo cache files; those are +/// also build trees, even when the archive is unpacked outside its original target directory. fn is_development_build(exe: &Path, opted_in: bool) -> bool { - !opted_in && exe.ancestors().skip(1).any(is_cargo_build_dir) + !opted_in && exe.ancestors().skip(1).any(|dir| is_cargo_build_dir(dir) || is_nextest_binary(dir, exe)) } /// Whether `dir` is a Cargo target root (by its rustc-info cache marker) or a profile output @@ -182,6 +184,35 @@ fn is_cargo_build_dir(dir: &Path) -> bool { profile_parent.parent().is_some_and(|root| root.join(CARGO_CACHE_MARKER).is_file()) } +// An archive inventory identifies only its listed binaries, not every installation below +// its extraction directory. Bound the metadata read and refuse symlink markers. +fn is_nextest_binary(root: &Path, exe: &Path) -> bool { + use std::io::Read; + const LIMIT: u64 = 1024 * 1024; + let marker = root.join("nextest/binaries-metadata.json"); + let Ok(metadata) = std::fs::symlink_metadata(&marker) else { return false }; + if !metadata.file_type().is_file() || metadata.len() > LIMIT { + return false; + } + let Ok(file) = std::fs::File::open(&marker) else { return false }; + let mut bytes = Vec::new(); + if file.take(LIMIT + 1).read_to_end(&mut bytes).is_err() || bytes.len() as u64 > LIMIT { + return false; + } + let Ok(inventory) = serde_json::from_slice::<serde_json::Value>(&bytes) else { return false }; + let Some(build) = inventory.get("rust-build-meta") else { return false }; + let Some(target) = build.get("target-directory").and_then(|v| v.as_str()) else { return false }; + let original = build.get("build-directory").and_then(|v| v.as_str()).unwrap_or(target); + let Some(binaries) = inventory.get("rust-binaries").and_then(|v| v.as_object()) else { return false }; + binaries.values().any(|binary| { + let Some(path) = binary.get("binary-path").and_then(|v| v.as_str()) else { return false }; + let Ok(relative) = Path::new(path).strip_prefix(original) else { return false }; + !relative.as_os_str().is_empty() + && relative.components().all(|part| matches!(part, std::path::Component::Normal(_))) + && root.join(relative) == exe + }) +} + /// Whether this installed copy can update itself. [`release_installs`] says whether a given /// release has a file to update it from. pub fn is_self_updating(app: &App) -> bool { @@ -3786,6 +3817,42 @@ mod tests { } } + #[test] + fn nextest_archive_binaries_do_not_update_themselves() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("relocated-artifacts"); + let exe = root.join("debug/build/artcraft-launcher-native/hash/out/artcraft_launcher_native-hash"); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, "ELF").unwrap(); + let metadata = root.join("nextest/binaries-metadata.json"); + std::fs::create_dir_all(metadata.parent().unwrap()).unwrap(); + // Names alone are not evidence of a Cargo build tree. + assert!(!is_development_build(&exe, false)); + std::fs::write(&metadata, "{}").unwrap(); + assert!(!is_development_build(&exe, false), "empty inventory is not evidence"); + let inventory = serde_json::json!({ + "rust-build-meta": {"target-directory": "/original/target"}, + "rust-binaries": {"launcher": {"binary-path": "/original/target/debug/build/artcraft-launcher-native/hash/out/artcraft_launcher_native-hash"}} + }); + std::fs::write(&metadata, inventory.to_string()).unwrap(); + assert!(is_development_build(&exe, false)); + assert_eq!(current_at(&crate::suite::LAUNCHER, &exe, false), None); + assert!(!is_development_build(&exe, true), "explicit developer opt-in remains available"); + let installed = root.join("bin/artcraft-launcher"); + assert!(!is_development_build(&installed, false), "an unlisted descendant installation is not a test binary"); + std::fs::remove_file(&metadata).unwrap(); + std::fs::create_dir(&metadata).unwrap(); + assert!(!is_development_build(&exe, false), "metadata must be a file"); + #[cfg(unix)] + { + std::fs::remove_dir(&metadata).unwrap(); + let external = dir.path().join("inventory.json"); + std::fs::write(&external, inventory.to_string()).unwrap(); + std::os::unix::fs::symlink(external, &metadata).unwrap(); + assert!(!is_development_build(&exe, false), "symlink inventory is not evidence"); + } + } + /// A Cargo build tree is not recognised by names: an installed copy in a folder literally /// called `target` stays an installed copy. #[test] diff --git a/crates/video/Cargo.toml b/crates/video/Cargo.toml index e5bbf1c94..c3ebfd722 100644 --- a/crates/video/Cargo.toml +++ b/crates/video/Cargo.toml @@ -52,6 +52,8 @@ vp9-encode = ["craft-media/isobmff"] av1 = ["av1-decode", "av1-encode"] av1-decode = [] av1-encode = ["craft-media/isobmff"] +# Tiled AV1 fallback for frames that exceed the clean-room encoder's single-tile limits. +av1-large-encode = ["av1-encode", "dep:rav1e"] # Decode and encode across worker threads (rayon) in the codecs that support it. threads = ["dep:rayon"] @@ -60,6 +62,9 @@ craft-media = { workspace = true } thiserror = { workspace = true } rayon = { workspace = true, optional = true } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +rav1e = { version = "0.8", default-features = false, optional = true } + [dev-dependencies] craft-media-testkit = { workspace = true } # The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test. diff --git a/crates/video/README.md b/crates/video/README.md index 74b8c6414..248e922b3 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -21,11 +21,11 @@ No codec feature is on by default. | `dnx` | [`dnx`](src/dnx/README.md) | Avid DNxHD / DNxHR (SMPTE ST 2019-1 VC-3): decoder and encoder | | `apv` | [`apv`](src/apv/README.md) | APV (Advanced Professional Video, RFC 9924): decoder (`apv-decode` alone) and encoder (`apv-encode` alone) | | `vp8` | `vp8` | VP8 (RFC 6386): decoder | -| `mpeg2` | [`mpeg2`](src/mpeg2/README.md) | MPEG-2 video (ITU-T H.262) and MPEG-1 video (ISO/IEC 11172-2): decoder (`mpeg2-decode` alone); MPEG-2 encoder with I and P pictures (`mpeg2-encode`, which also turns on the decoder) | +| `mpeg2` | [`mpeg2`](src/mpeg2/README.md) | MPEG-2 video (ITU-T H.262) and MPEG-1 video (ISO/IEC 11172-2): decoder (`mpeg2-decode` alone); MPEG-2 encoder with I, P and B pictures (`mpeg2-encode`, which also turns on the decoder) | | `mpeg4` | [`mpeg4`](src/mpeg4/README.md) | MPEG-4 Part 2 video (ISO/IEC 14496-2, the Xvid/DivX format): Simple profile encoder (`mpeg4-encode`) | | `prores` | `prores` | Apple ProRes (SMPTE RDD 36): decoder and encoder | | `h264` | [`h264`](src/h264/decode/README.md) | ITU-T H.264 / AVC: decoder (`h264-decode` alone) and encoder (`h264-encode` alone) | | `hevc` | [`hevc`](src/hevc/decode/README.md) | ITU-T H.265 / HEVC: decoder (`hevc-decode` alone) and encoder (`hevc-encode` alone) | | `vp9` | [`vp9`](src/vp9/decode/README.md) | VP9: decoder (`vp9-decode` alone) and encoder (`vp9-encode` alone) | -| `av1` | [`av1`](src/av1/decode/README.md) | AV1 (AOMedia Video 1): decoder (`av1-decode` alone) and encoder (`av1-encode` alone) | +| `av1` | [`av1`](src/av1/decode/README.md) | AV1 (AOMedia Video 1): decoder (`av1-decode` alone) and clean-room encoder (`av1-encode`); tiled rav1e fallback for large frames (`av1-large-encode`) | | `threads` | — | Multi-threaded slice/row parallelism via `rayon` | diff --git a/crates/video/src/av1/encode/README.md b/crates/video/src/av1/encode/README.md index aa1604706..0fd60c50f 100644 --- a/crates/video/src/av1/encode/README.md +++ b/crates/video/src/av1/encode/README.md @@ -3,6 +3,16 @@ Clean-room, pure-Rust AV1 encoder for MP4 / WebM export (layer L0, `std` only, no `unsafe`, builds for `wasm32-unknown-unknown`). +## Large frame fallback + +The optional `av1-large-encode` feature exposes `LargeEncoder`, a tiled rav1e-backed encoder for +8-bit 4:2:0 frames up to 8192 samples per side. Use it when the clean-room `Encoder`'s one-tile +limits (4096 samples per side and 2304 superblocks) would reject the frame. It supports constant +quantizer rate control. `push` returns packets available so far, which can be empty while frames +are buffered; `finish` returns delayed packets. Each packet includes its input frame number for +matching durations. The fallback is native only; the clean-room encoder remains available without +the feature and supports 8- and 10-bit input. + ## What is implemented - **Stream**: Main profile (`seq_profile` 0), 4:2:0, 8 or 10 bit, the configured colour description (BT.709 by default), diff --git a/crates/video/src/av1/encode/large.rs b/crates/video/src/av1/encode/large.rs new file mode 100644 index 000000000..8ed26d52b --- /dev/null +++ b/crates/video/src/av1/encode/large.rs @@ -0,0 +1,269 @@ +//! Tiled AV1 encoding for frames outside the clean-room encoder's single-tile limits. + +use super::{EncoderConfig, Error, Frame, Packet, RateControl}; +use rav1e::prelude::{ + ChromaSampling, ColorDescription, ColorPrimaries, Config, Context, EncoderConfig as Rav1eConfig, FrameParameters, FrameType, FrameTypeOverride, + MatrixCoefficients, PixelRange, Rational, TransferCharacteristics, +}; + +/// Tiled AV1 encoder used when a frame is too large for [`super::Encoder`]. +pub struct LargeEncoder { + ctx: Context<u8>, + width: usize, + height: usize, + seq_header: Option<Vec<u8>>, + finished: bool, +} + +/// An encoded frame and the number of the input frame it represents. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BufferedPacket { + pub input_frame_number: u64, + pub packet: Packet, +} + +impl LargeEncoder { + /// Creates a tiled 8-bit 4:2:0 encoder for dimensions up to 8192 samples per side. + pub fn new(cfg: &EncoderConfig) -> Result<Self, Error> { + Self::with_speed(cfg, 6) + } + + /// Creates the tiled encoder with a rav1e speed preset from 1 (slower) to 10 (faster). + pub fn with_speed(cfg: &EncoderConfig, speed: u8) -> Result<Self, Error> { + if cfg.width < 16 || cfg.height < 16 || cfg.width > 8192 || cfg.height > 8192 { + return Err(Error::InvalidConfig("large AV1 frame dimensions must be 16..=8192".into())); + } + if cfg.bit_depth != 8 || cfg.fps_num == 0 || cfg.fps_den == 0 { + return Err(Error::InvalidConfig("large AV1 encoding requires 8-bit input and a valid frame rate".into())); + } + let RateControl::ConstantQ(quality) = cfg.rate else { + return Err(Error::InvalidConfig("large AV1 encoding currently supports constant quantizer rate control".into())); + }; + let mut ec = Rav1eConfig::with_speed_preset(speed.clamp(1, 10)); + ec.width = cfg.width as usize; + ec.height = cfg.height as usize; + ec.time_base = Rational::new(u64::from(cfg.fps_den), u64::from(cfg.fps_num)); + ec.bit_depth = 8; + ec.chroma_sampling = ChromaSampling::Cs420; + ec.pixel_range = if cfg.full_range { PixelRange::Full } else { PixelRange::Limited }; + ec.color_description = Some(ColorDescription { + color_primaries: ColorPrimaries::BT709, + transfer_characteristics: TransferCharacteristics::BT709, + matrix_coefficients: MatrixCoefficients::BT709, + }); + ec.low_latency = true; + ec.quantizer = quality.max(1) as usize; + ec.min_quantizer = ec.quantizer.min(255) as u8; + ec.min_key_frame_interval = 1; + ec.max_key_frame_interval = cfg.keyint.clamp(1, 120) as u64; + ec.tiles = std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(2, 16); + let ctx = Config::new().with_encoder_config(ec).new_context().map_err(|e| Error::InvalidConfig(format!("rav1e: {e}")))?; + Ok(Self { ctx, width: cfg.width as usize, height: cfg.height as usize, seq_header: None, finished: false }) + } + + fn submit(&mut self, frame: &Frame<'_>, force_key: bool) -> Result<(), Error> { + if self.finished { + return Err(Error::InvalidFrame("AV1 encoder was already finished".into())); + } + if frame.y_stride < self.width + || frame.uv_stride < self.width / 2 + || frame.y.len() < frame.y_stride.saturating_mul(self.height) + || frame.u.len() < frame.uv_stride.saturating_mul(self.height / 2) + || frame.v.len() < frame.uv_stride.saturating_mul(self.height / 2) + { + return Err(Error::InvalidFrame("plane dimensions or strides do not match the configured frame".into())); + } + let mut input = self.ctx.new_frame(); + copy_plane(&mut input.planes[0], frame.y, frame.y_stride, self.width, self.height)?; + copy_plane(&mut input.planes[1], frame.u, frame.uv_stride, self.width / 2, self.height / 2)?; + copy_plane(&mut input.planes[2], frame.v, frame.uv_stride, self.width / 2, self.height / 2)?; + let params = + FrameParameters { frame_type_override: if force_key { FrameTypeOverride::Key } else { FrameTypeOverride::No }, ..Default::default() }; + self.ctx.send_frame((input, params)).map_err(|e| Error::InvalidFrame(format!("rav1e: {e}")))?; + Ok(()) + } + + fn packet(&mut self, packet: rav1e::prelude::Packet<u8>) -> Result<BufferedPacket, Error> { + let (data, seq) = sample_data(&packet.data)?; + if self.seq_header.is_none() { + self.seq_header = seq; + } + Ok(BufferedPacket { input_frame_number: packet.input_frameno, packet: Packet { data, keyframe: packet.frame_type == FrameType::KEY } }) + } + + fn drain(&mut self) -> Result<Vec<BufferedPacket>, Error> { + let mut packets = Vec::new(); + loop { + match self.ctx.receive_packet() { + Ok(packet) => packets.push(self.packet(packet)?), + Err(rav1e::prelude::EncoderStatus::Encoded) => {} + Err(rav1e::prelude::EncoderStatus::NeedMoreData) if !self.finished => return Ok(packets), + Err(rav1e::prelude::EncoderStatus::LimitReached) if self.finished => return Ok(packets), + Err(e) => return Err(Error::InvalidFrame(format!("rav1e: {e}"))), + } + } + } + + /// Submit a frame and return all packets available now, which may be empty while the encoder + /// buffers input. Call [`Self::finish`] after the last frame to retrieve delayed packets. + pub fn push(&mut self, frame: &Frame<'_>, force_key: bool) -> Result<Vec<BufferedPacket>, Error> { + self.submit(frame, force_key)?; + self.drain() + } + + /// Finish the stream and return its remaining packets. Repeated calls return no packets. + pub fn finish(&mut self) -> Result<Vec<BufferedPacket>, Error> { + if !self.finished { + self.ctx.send_frame(None).map_err(|e| Error::InvalidFrame(format!("rav1e: {e}")))?; + self.finished = true; + } + self.drain() + } + + /// Encodes one frame if a packet is immediately available. The input is accepted even if + /// rav1e needs more frames and this returns an error; new callers should use [`Self::push`]. + pub fn encode_with_key(&mut self, frame: &Frame<'_>, force_key: bool) -> Result<Packet, Error> { + self.submit(frame, force_key)?; + loop { + match self.ctx.receive_packet() { + Ok(packet) => { + return Ok(self.packet(packet)?.packet); + } + Err(rav1e::prelude::EncoderStatus::Encoded) => continue, + Err(rav1e::prelude::EncoderStatus::NeedMoreData | rav1e::prelude::EncoderStatus::LimitReached) => { + return Err(Error::InvalidFrame("rav1e did not emit a low-latency frame".into())); + } + Err(e) => return Err(Error::InvalidFrame(format!("rav1e: {e}"))), + } + } + } + + /// Returns the AV1 configuration record after the first frame has been encoded. + pub fn av1c(&self) -> Option<Vec<u8>> { + self.seq_header.as_ref().map(|obu| { + let mut config = vec![0x81, 31, 0x0c, 0]; + config.extend_from_slice(obu); + config + }) + } +} + +fn copy_plane(plane: &mut rav1e::prelude::Plane<u8>, source: &[u16], stride: usize, width: usize, height: usize) -> Result<(), Error> { + let mut packed = Vec::with_capacity(width * height); + for row in 0..height { + let start = row * stride; + let pixels = &source[start..start + width]; + if pixels.iter().any(|&value| value > u8::MAX as u16) { + return Err(Error::InvalidFrame("8-bit AV1 samples must be in 0..=255".into())); + } + packed.extend(pixels.iter().map(|&value| value as u8)); + } + plane.copy_from_raw_u8(&packed, width, 1); + Ok(()) +} + +fn sample_data(data: &[u8]) -> Result<(Vec<u8>, Option<Vec<u8>>), Error> { + let mut pos = 0usize; + let mut sample = Vec::with_capacity(data.len()); + let mut sequence = None; + while pos < data.len() { + let start = pos; + let header = data[pos]; + if header & 0x80 != 0 { + return Err(Error::InvalidFrame("rav1e emitted an invalid OBU".into())); + } + let kind = (header >> 3) & 0x0f; + pos += 1 + usize::from(header & 0x04 != 0); + let end = if header & 0x02 != 0 { + let mut size = 0usize; + let mut shift = 0usize; + loop { + let byte = *data.get(pos).ok_or_else(|| Error::InvalidFrame("truncated OBU size".into()))?; + pos += 1; + size |= usize::from(byte & 0x7f).checked_shl(shift as u32).ok_or_else(|| Error::InvalidFrame("OBU size overflow".into()))?; + if byte & 0x80 == 0 { + break; + } + shift += 7; + if shift >= usize::BITS as usize { + return Err(Error::InvalidFrame("OBU size overflow".into())); + } + } + pos.checked_add(size).filter(|end| *end <= data.len()).ok_or_else(|| Error::InvalidFrame("OBU exceeds packet bounds".into()))? + } else { + data.len() + }; + if kind == 1 && sequence.is_none() { + sequence = Some(data[start..end].to_vec()); + } + if kind != 2 && kind != 15 { + sample.extend_from_slice(&data[start..end]); + } + pos = end; + } + Ok((sample, sequence)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn buffered_frames_are_returned_with_input_numbers_and_finish_drains() { + let cfg = EncoderConfig::new(64, 48, 24, 1); + let mut encoder = LargeEncoder::with_speed(&cfg, 10).unwrap(); + assert!(encoder.av1c().is_none()); + let y = vec![96; 64 * 48]; + let uv = vec![128; 32 * 24]; + let frame = Frame { y: &y, u: &uv, v: &uv, y_stride: 64, uv_stride: 32 }; + let mut packets = Vec::new(); + for i in 0..4 { + packets.extend(encoder.push(&frame, i == 2).unwrap()); + } + packets.extend(encoder.finish().unwrap()); + assert_eq!(packets.iter().map(|p| p.input_frame_number).collect::<Vec<_>>(), [0, 1, 2, 3]); + assert!(packets[0].packet.keyframe); + assert!(packets[2].packet.keyframe, "requested key frame"); + assert!(encoder.av1c().is_some()); + #[cfg(feature = "av1-decode")] + { + let mut decoder = crate::av1::decode::Decoder::with_threads(1); + let mut frames = Vec::new(); + for packet in &packets { + frames.extend(decoder.decode(&packet.packet.data).unwrap()); + } + frames.extend(decoder.flush_result().unwrap()); + assert_eq!(frames.len(), 4); + assert!(frames.iter().all(|frame| (frame.width, frame.height) == (64, 48))); + } + assert!(encoder.finish().unwrap().is_empty()); + assert!(encoder.push(&frame, false).is_err()); + } + + #[test] + fn a_large_frame_can_be_flushed_even_when_the_first_push_is_buffered() { + let cfg = EncoderConfig::new(4112, 16, 30, 1); + let mut encoder = LargeEncoder::with_speed(&cfg, 10).unwrap(); + let y = vec![64; 4112 * 16]; + let uv = vec![128; 2056 * 8]; + let frame = Frame { y: &y, u: &uv, v: &uv, y_stride: 4112, uv_stride: 2056 }; + let mut packets = encoder.push(&frame, false).unwrap(); + packets.extend(encoder.finish().unwrap()); + assert_eq!(packets.len(), 1); + assert_eq!(packets[0].input_frame_number, 0); + assert!(packets[0].packet.keyframe); + assert!(!packets[0].packet.data.is_empty()); + assert!(encoder.av1c().is_some()); + } + + #[test] + fn invalid_frame_is_not_queued_and_empty_stream_finishes() { + let cfg = EncoderConfig::new(64, 48, 24, 1); + let mut encoder = LargeEncoder::with_speed(&cfg, 10).unwrap(); + let short = [0; 1]; + let frame = Frame { y: &short, u: &short, v: &short, y_stride: 64, uv_stride: 32 }; + assert!(encoder.push(&frame, false).is_err()); + assert!(encoder.finish().unwrap().is_empty()); + assert!(encoder.av1c().is_none()); + } +} diff --git a/crates/video/src/av1/encode/mod.rs b/crates/video/src/av1/encode/mod.rs index 0d8e2b04f..d6632a94d 100644 --- a/crates/video/src/av1/encode/mod.rs +++ b/crates/video/src/av1/encode/mod.rs @@ -20,6 +20,11 @@ mod tables; mod transform; mod writer; +#[cfg(all(feature = "av1-large-encode", not(target_arch = "wasm32")))] +mod large; +#[cfg(all(feature = "av1-large-encode", not(target_arch = "wasm32")))] +pub use large::{BufferedPacket, LargeEncoder}; + use bitw::obu; use craft_media::bitstream::BitWriter; use craft_media::isobmff::Av1Config; @@ -600,8 +605,13 @@ impl Encoder { /// Encodes one frame. pub fn encode(&mut self, frame: &Frame) -> Result<Packet, Error> { + self.encode_with_key(frame, false) + } + + /// Encodes one frame, optionally forcing a keyframe regardless of `keyint`. + pub fn encode_with_key(&mut self, frame: &Frame, force_key: bool) -> Result<Packet, Error> { self.check_frame(frame)?; - let key = self.frame_num.is_multiple_of(self.cfg.keyint.max(1) as u64); + let key = force_key || self.frame_num.is_multiple_of(self.cfg.keyint.max(1) as u64); let src = self.load_source(frame); let (frame_obu, rf) = match self.cfg.rate { RateControl::ConstantQ(q) => self.encode_frame(&src, key, q.max(1)), diff --git a/crates/video/src/h264/encode/mod.rs b/crates/video/src/h264/encode/mod.rs index e13679431..f0c684e1e 100644 --- a/crates/video/src/h264/encode/mod.rs +++ b/crates/video/src/h264/encode/mod.rs @@ -418,7 +418,7 @@ impl<P: Pixel> Core<P> { ) } - pub fn new(mut cfg: EncoderConfig) -> Result<Self, Error> { + fn new_with_extra_motion_search_starts(mut cfg: EncoderConfig, extra_motion_search_starts: bool) -> Result<Self, Error> { if cfg.width == 0 || cfg.height == 0 || !cfg.width.is_multiple_of(2) @@ -468,6 +468,7 @@ impl<P: Pixel> Core<P> { adaptive_t8: false, always_intra: false, cavlc_clamp: !cabac, + extra_motion_search_starts, depth, }, Preset::Balanced => EncParams { @@ -487,6 +488,7 @@ impl<P: Pixel> Core<P> { adaptive_t8: high, always_intra: false, cavlc_clamp: !cabac, + extra_motion_search_starts, depth, }, Preset::Quality => EncParams { @@ -506,6 +508,7 @@ impl<P: Pixel> Core<P> { adaptive_t8: high, always_intra: true, cavlc_clamp: !cabac, + extra_motion_search_starts, depth, }, }; @@ -1218,6 +1221,15 @@ pub struct Encoder { core: Cores, } +/// Starting points considered by the integer motion search. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum MotionSearchStarts { + /// Include skip, zero and co-located vectors for 16x16 searches. + Extended, + /// Use only the skip seed and neighboring partition vector, matching the earlier FilmCraft encoder. + SeedAndNeighbour, +} + enum Cores { Eight(Box<Core<u8>>), Deep(Box<Core<u16>>), @@ -1234,7 +1246,18 @@ macro_rules! core { impl Encoder { pub fn new(cfg: EncoderConfig) -> Result<Self, Error> { - let core = if cfg.bit_depth > 8 { Cores::Deep(Box::new(Core::new(cfg)?)) } else { Cores::Eight(Box::new(Core::new(cfg)?)) }; + Self::new_with_motion_search_starts(cfg, MotionSearchStarts::Extended) + } + + /// Construct an encoder with an explicit motion-search start policy. Existing callers should + /// use [`Encoder::new`], which selects [`MotionSearchStarts::Extended`]. + pub fn new_with_motion_search_starts(cfg: EncoderConfig, starts: MotionSearchStarts) -> Result<Self, Error> { + let extra = starts == MotionSearchStarts::Extended; + let core = if cfg.bit_depth > 8 { + Cores::Deep(Box::new(Core::new_with_extra_motion_search_starts(cfg, extra)?)) + } else { + Cores::Eight(Box::new(Core::new_with_extra_motion_search_starts(cfg, extra)?)) + }; Ok(Encoder { core }) } @@ -1450,7 +1473,7 @@ mod tests { /// A recycled `MbInfo` buffer must come back as all-default entries, whatever the previous picture left in it. #[test] fn recycled_mb_buffers_are_cleared() { - let mut core = Core::<u8>::new(EncoderConfig::new(64, 48, 30, 1)).unwrap(); + let mut core = Core::<u8>::new_with_extra_motion_search_starts(EncoderConfig::new(64, 48, 30, 1), true).unwrap(); let n = core.params.mbw * core.params.mbh; let mut m = core.new_mbs(); assert_eq!(m.len(), n); diff --git a/crates/video/src/h264/encode/slice.rs b/crates/video/src/h264/encode/slice.rs index b8ad0f7a9..ffb46e19c 100644 --- a/crates/video/src/h264/encode/slice.rs +++ b/crates/video/src/h264/encode/slice.rs @@ -47,6 +47,8 @@ pub struct EncParams { pub always_intra: bool, /// Maximum CAVLC level magnitude (Baseline). pub cavlc_clamp: bool, + /// Whether the 16x16 motion search tries skip, zero and co-located starts. + pub extra_motion_search_starts: bool, pub depth: Depth, } diff --git a/crates/video/src/h264/encode/slice/motion.rs b/crates/video/src/h264/encode/slice/motion.rs index 1bc4bab02..24096d73c 100644 --- a/crates/video/src/h264/encode/slice/motion.rs +++ b/crates/video/src/h264/encode/slice/motion.rs @@ -296,10 +296,14 @@ impl<'a, 'b, P: Pixel> SliceEnc<'a, 'b, P> { skip_pred = Some((y, u, v)); } // --- 16x16 search - let mut cands = vec![skip_mv, Mv::ZERO]; - let colo = r.mbs[my * f.p.mbw + mx]; - if colo.ref_idx[0][0] >= 0 { - cands.push(colo.mv[0][0]); + let mut cands = Vec::new(); + if f.p.extra_motion_search_starts { + cands.push(skip_mv); + cands.push(Mv::ZERO); + let colo = r.mbs[my * f.p.mbw + mx]; + if colo.ref_idx[0][0] >= 0 { + cands.push(colo.mv[0][0]); + } } let (mv16, mvp16, cost16) = { let (m, p, c) = self.search_part(r, &PartSearch { mx, my, part: Part::P16x16, list: 0, lam, seed: skip_mv }, src, &cands); diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index d9723a81d..0d8625bbd 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -8,7 +8,7 @@ //! | `dnx` | [`dnx`] | Avid DNxHD / DNxHR (SMPTE ST 2019-1): decoder and encoder | //! | `apv` | [`apv`] | APV (RFC 9924): decoder (`apv-decode`) and encoder (`apv-encode`) | //! | `vp8` | [`vp8`] | VP8 (RFC 6386): decoder (`vp8-decode`) and key-frame encoder (`vp8-encode`) | -//! | `mpeg2` | [`mpeg2`] | MPEG-2 video (ITU-T H.262) and MPEG-1 video: decoder (`mpeg2-decode`) and MPEG-2 I/P encoder (`mpeg2-encode`) | +//! | `mpeg2` | [`mpeg2`] | MPEG-2 video (ITU-T H.262) and MPEG-1 video: decoder (`mpeg2-decode`) and MPEG-2 I/P/B encoder (`mpeg2-encode`) | //! | `mpeg4` | [`mpeg4`] | MPEG-4 Part 2 video (ISO/IEC 14496-2, Xvid/DivX): Simple profile encoder (`mpeg4-encode`) | //! | `prores` | [`prores`] | Apple ProRes (SMPTE RDD 36): decoder and encoder | //! | `h264` | [`h264`] | ITU-T H.264 / AVC: decoder (`h264-decode`) and encoder (`h264-encode`) | diff --git a/crates/video/src/mpeg2/README.md b/crates/video/src/mpeg2/README.md index b68dc800b..069fd67bd 100644 --- a/crates/video/src/mpeg2/README.md +++ b/crates/video/src/mpeg2/README.md @@ -1,7 +1,7 @@ # MPEG-2 and MPEG-1 video decoder, MPEG-2 encoder (`craft_video::mpeg2`, features `mpeg2-decode`, `mpeg2-encode`) -Clean-room MPEG-2 video and MPEG-1 video decoder, and the first step of an MPEG-2 video encoder -(I and P pictures, see "Encoder"), in pure Rust. Depends only on +Clean-room MPEG-2 video and MPEG-1 video decoder, and the first steps of an MPEG-2 video encoder +(I, P and B pictures, see "Encoder"), in pure Rust. Depends only on `thiserror` and (optional, feature `threads`) `rayon`. Builds for `wasm32-unknown-unknown`; no `unsafe`. No GPL/LGPL code (FFmpeg, libmpeg2, libavcodec) was consulted; FFmpeg is used only as an external fixture generator and test oracle. @@ -77,8 +77,8 @@ the synthetic-stream tests confirmed against FFmpeg: ## Encoder (feature `mpeg2-encode`) -The encoder is the first step of MPEG-2 encoding in this crate, tracked in -storytold/craft-libs#1133. It writes valid MPEG-2 elementary streams, but not yet DVD or +The encoder is built in steps, tracked in storytold/craft-libs#1133: I and P pictures came in +#1136, B pictures in the second step. It writes valid MPEG-2 elementary streams, but not yet DVD or broadcast deliverables: those need the later steps listed below. ```rust @@ -86,13 +86,15 @@ use craft_video::mpeg2::{Encoder, EncoderConfig, RateControl, YuvFrame}; let mut cfg = EncoderConfig::new(720, 576, 25, 1); cfg.rate = RateControl::Abr { kbps: 6000 }; // or RateControl::Quantiser(1..=31) -cfg.gop_size = 12; // one I picture, then P pictures +cfg.gop_size = 12; // pictures from one I picture to the next +cfg.b_pictures = 2; // I B B P B B P ...; 0 for I and P only +cfg.closed_gop = true; // or open GOPs let mut enc = Encoder::new(cfg)?; for (i, f) in frames.iter().enumerate() { let frame = YuvFrame { y: &f.y, cb: &f.cb, cr: &f.cr, y_stride: 720, c_stride: 360 }; for p in enc.encode(&frame, i as i64)? { /* p.data, p.pts, p.dts, p.keyframe, p.picture_type */ } } -for p in enc.flush() { /* none yet: no B pictures */ } +for p in enc.flush() { /* the pictures held for reordering */ } es.extend_from_slice(enc.end_of_sequence()); ``` @@ -101,9 +103,18 @@ What it does: - Main Profile (4:2:0) at Low, Main, High-1440 and High Level, and 4:2:2 Profile at Main and High Level. The lowest level that holds the size, frame rate and (average) bitrate is chosen; sizes beyond High Level are refused. Any even picture size; edges are padded by repetition. -- Progressive frame pictures, I and P, in closed GOPs. Every GOP starts with a sequence header, - sequence extension and GOP header (with a time code), so every I picture is a random access - point. Packets come out in decoding order, which equals display order without B pictures. +- Progressive frame pictures, I, P and B. Every GOP starts with a sequence header, sequence + extension and GOP header (with a time code), so every I picture is a random access point. +- B pictures (0-4 between anchors) and reordering: pictures go in in display order and packets + come out in decoding order; a B picture is held until the anchor after it is coded, and + `flush` codes the last held picture as a P picture. With B pictures, `dts` is the presentation + times in decoding order one picture interval earlier, so presentation times must step evenly. + A single picture flushed before a second one gets `dts = pts - 1`. With average bitrate, a + GOP that `flush` cuts short gives back the budget of the pictures it did not get. + `low_delay` is set only without B pictures. +- GOPs are closed or open. The B pictures shown before a GOP's I picture (coded after it) predict + backward only in a closed GOP, and from the previous GOP's last anchor too in an open one. + temporal_reference counts display order from the GOP's first picture. - Forward DCT on the transpose of the decoder's IDCT basis; intra quantisation with a small dead zone, non-intra quantisation by truncation; default or custom quantiser matrices (sequence header); linear or non-linear quantiser scale; intra DC precision 8-10 bits; @@ -112,9 +123,14 @@ What it does: predictor, the previous picture's vectors), then half-sample refinement; cost SAD + λ·bits. Each macroblock is coded intra, motion-compensated with or without residual, "no MC" with residual, or skipped. The search range sets f_code (1-4). +- B pictures: a search per direction (candidates include the P picture's vectors scaled to the + B picture's distance), then forward, backward, interpolated or the skip prediction (the + previous macroblock's directions with the predictors), whichever costs least, or intra. + Interpolated predictions are averaged in the decoder's order. - Adaptive quantisation by macroblock activity (Test Model 5 §5.2.3). -- Rate control: a constant quantiser, or single-pass average bitrate with Test Model 5's - target bit allocation at picture level. Streams are signalled as variable bitrate +- Rate control: a constant quantiser (B pictures at 1.25 times it), or single-pass average + bitrate with Test Model 5's target bit allocation at picture level (B pictures weighted by + K_b = 1.4). Streams are signalled as variable bitrate (`vbv_delay` 0xFFFF, the level's maximum bitrate and VBV size in the sequence header); the VBV buffer is not modelled. - The reconstruction uses the decoder's own dequantisation, mismatch control, IDCT and motion @@ -122,7 +138,7 @@ What it does: - Slices (one per macroblock row) are coded in parallel on rayon with `threads`; the stream is identical either way. -Later steps (#1133): B pictures and reordering; CBR and VBR with a VBV guarantee; DVD presets +Later steps (#1133): CBR and VBR with a VBV guarantee; DVD presets (sizes, aspect, GOP length, 9.8 Mb/s, 23.976 soft telecine); interlaced coding (field/frame DCT, field prediction, alternate scan) and 4:2:2 High Level CBR for XDCAM HD422. MPEG-2 essence in the MXF writer and a program stream muxer belong to `craft-media`. @@ -191,9 +207,15 @@ fell to 77–150 fps). These are lower bounds. rate control converges on its target. `encode/tests.rs`: our decoder outputs exactly the encoder's reconstruction (intra only, a 30-picture P GOP, 4:2:2, linear and non-linear quantisers, quantisers 1 and 31, DC precision 8 and 10, custom matrices, odd macroblock counts, - average bitrate); quality and size follow the quantiser; repeated pictures skip; levels and - aspect in the sequence header; bad configurations and short or inconsistent planes are refused. -- `tests/mpeg2/encode.rs`: FFmpeg decodes our streams of `testsrc2` (CIF and 576-line 4:2:2) - without errors and within the decoder suite's tolerance of our reconstruction, ffprobe reports - the profile, level, pixel format and I/P picture types, and average bitrate lands within 10 % of - 800 and 2500 kbit/s targets. + average bitrate, each with and without B pictures; 1-4 B pictures with closed and open GOPs, + GOP lengths that are and are not multiples of the anchor distance, and streams that end inside + a group of B pictures); decoding order, decoding times and temporal_reference; a closed GOP + decodes from its I picture with its leading B pictures and an open one without them; B pictures + are smaller than P pictures; uneven presentation times are refused with B pictures; quality and + size follow the quantiser; repeated pictures skip; levels and aspect in the sequence header; + bad configurations and short or inconsistent planes are refused. +- `tests/mpeg2/encode.rs`: FFmpeg decodes our streams of `testsrc2` (CIF and 576-line 4:2:2; + without B pictures, with 2 and 4, closed and open GOPs) without errors and within the decoder + suite's tolerance of our reconstruction, ffprobe reports the profile, level, pixel format and + picture types in display order, and average bitrate lands within 10 % of 800 and 2500 kbit/s + targets. diff --git a/crates/video/src/mpeg2/encode/mod.rs b/crates/video/src/mpeg2/encode/mod.rs index fcd1bd8d1..af32b271d 100644 --- a/crates/video/src/mpeg2/encode/mod.rs +++ b/crates/video/src/mpeg2/encode/mod.rs @@ -1,9 +1,9 @@ //! MPEG-2 video encoder (ITU-T H.262 | ISO/IEC 13818-2), feature `mpeg2-encode`. //! -//! This is the first step of MPEG-2 encoding in this crate (storytold/craft-libs#1133): I and P -//! pictures, progressive frame pictures, 4:2:0 (Main Profile) and 4:2:2 (4:2:2 Profile), closed -//! GOPs, constant quantiser or single-pass average bitrate. B pictures, a VBV guarantee, -//! interlaced coding and DVD / broadcast presets come later. +//! MPEG-2 encoding in this crate is built in steps (storytold/craft-libs#1133). So far: I, P and B +//! pictures, progressive frame pictures, 4:2:0 (Main Profile) and 4:2:2 (4:2:2 Profile), closed or +//! open GOPs, constant quantiser or single-pass average bitrate. A VBV guarantee, interlaced +//! coding and DVD / broadcast presets come later. //! //! ```no_run //! use craft_video::mpeg2::encode::{Encoder, EncoderConfig, RateControl, YuvFrame}; @@ -36,6 +36,8 @@ mod transform; #[cfg(test)] mod tests; +use std::collections::VecDeque; + use crate::mpeg2::ChromaFormat; use crate::mpeg2::headers::{DEFAULT_INTRA, PictureType, SCAN}; use crate::mpeg2::mc::Frame; @@ -50,6 +52,10 @@ pub enum EncodeError { Config(String), #[error("bad input frame: {0}")] BadFrame(String), + /// With B pictures, presentation times must increase by a constant step (the decoding times + /// are the presentation times one step earlier). + #[error("bad presentation time: {0}")] + BadTimestamp(String), } /// aspect_ratio_information (H.262 Table 6-3). @@ -97,8 +103,15 @@ pub struct EncoderConfig { /// 4:2:0 (Main Profile) or 4:2:2 (4:2:2 Profile). pub chroma: ChromaFormat, pub aspect: AspectRatio, - /// Pictures per GOP: one I picture, then P pictures. 1 codes every picture as I. 1..=1023. + /// Pictures from one I picture to the next (display order). 1 codes every picture as I. + /// 1..=1023, and at most 1024 with `b_pictures` added. pub gop_size: u32, + /// B pictures between two anchor (I or P) pictures, 0..=4. 0 gives I and P pictures only and a + /// low-delay stream (no reordering). + pub b_pictures: u32, + /// Closed GOPs: the B pictures shown before a GOP's I picture predict from it alone, so the + /// GOP decodes on its own. Open GOPs let them predict from the previous GOP too. + pub closed_gop: bool, pub rate: RateControl, /// q_scale_type: the non-linear quantiser scale (finer steps at low quantisers). pub nonlinear_quant: bool, @@ -125,6 +138,8 @@ impl EncoderConfig { chroma: ChromaFormat::Yuv420, aspect: AspectRatio::Square, gop_size: 12, + b_pictures: 2, + closed_gop: true, rate: RateControl::Quantiser(4), nonlinear_quant: true, adaptive_quant: true, @@ -155,9 +170,12 @@ pub struct Packet { /// the picture. pub data: Vec<u8>, pub pts: i64, - /// Decoding timestamp; equal to `pts` while there are no B pictures. + /// Decoding timestamp: `pts` without B pictures; with them, the presentation times in + /// decoding order one picture interval earlier, so `dts <= pts`. A stream of one picture has + /// no interval: its `dts` is `pts - 1`. pub dts: i64, - /// An I picture starting a closed GOP (random access point). + /// An I picture (random access point; in an open GOP the B pictures after it in decoding + /// order also need the previous GOP). pub keyframe: bool, pub picture_type: PictureType, /// Average quantiser_scale of the picture's macroblocks. @@ -260,6 +278,13 @@ fn validate(cfg: &EncoderConfig) -> Result<(), EncodeError> { if !(1..=1023).contains(&cfg.gop_size) { return bad(format!("GOP size {} (1..=1023)", cfg.gop_size)); } + if cfg.b_pictures > 4 { + return bad(format!("{} B pictures between anchors (0..=4)", cfg.b_pictures)); + } + // temporal_reference (10 bits) counts a GOP's leading B pictures too + if cfg.gop_size + cfg.b_pictures > 1024 { + return bad(format!("GOP size {} with {} B pictures: more than 1024 pictures to number", cfg.gop_size, cfg.b_pictures)); + } match cfg.rate { RateControl::Quantiser(q) if !(1..=31).contains(&q) => return bad(format!("quantiser_scale_code {q} (1..=31)")), RateControl::Abr { kbps: 0 } => return bad("bitrate 0".into()), @@ -284,6 +309,26 @@ fn put_matrix(w: &mut BitWriter, m: &[u8; 64]) { } } +/// A source picture waiting for the anchor after it (a B picture). +struct Held { + src: Frame, + pts: i64, + /// Display index. + n: u64, +} + +/// A coded picture before rate control and timestamps. +struct Coded { + packet: Packet, + recon: Frame, + mvs: Vec<[i32; 2]>, + avg_q: f64, +} + +/// Quantiser ratio of B to P pictures with a constant quantiser (TM5 uses 1.4 for its rate +/// allocation; a constant quantiser keeps B pictures a little closer to the anchors). +const B_QUANT_FACTOR: f64 = 1.25; + /// A stateful encoder. Feed pictures in display order; packets come out in decoding order. pub struct Encoder { cfg: EncoderConfig, @@ -297,16 +342,32 @@ pub struct Encoder { inter_matrix: [u8; 64], /// Sequence header and sequence extension, sent before every GOP. seq_header: Vec<u8>, - /// The reconstruction of the previous picture. - reference: Option<Frame>, - prev_mvs: Vec<[i32; 2]>, - /// Pictures coded so far. + /// The reconstructions of the last two anchor pictures and their display indices: `latest` + /// is the backward reference of the B pictures held, and the forward reference of the next + /// P picture. + older: Option<(Frame, u64)>, + latest: Option<(Frame, u64)>, + /// Forward vectors of the latest anchor when it is a P picture (search candidates). + anchor_mvs: Vec<[i32; 2]>, + /// B pictures waiting for their backward reference. + held: Vec<Held>, + /// Display index of the next picture. count: u64, - /// Position of the next picture in its GOP. - gop_pos: u32, + /// Display indices of the current GOP's I picture and of its first picture in display order + /// (a leading B picture in front of the I picture, or the I picture). + gop_start: u64, + gop_first: u64, + /// The current GOP is closed: its leading B pictures predict backward only. + gop_closed: bool, + /// Presentation times not yet given to a coded picture as its decoding time, in input order. + display_pts: VecDeque<i64>, + last_pts: Option<i64>, + pts_step: Option<i64>, + /// Packets waiting for the presentation time step (the decoding time offset). + out: Vec<Packet>, rc: Option<RateCtl>, recon_capture: bool, - recon: Vec<ReconFrame>, + recon: Vec<(u64, ReconFrame)>, } impl Encoder { @@ -330,10 +391,18 @@ impl Encoder { intra_matrix: cfg.intra_matrix.unwrap_or(DEFAULT_INTRA), inter_matrix: cfg.non_intra_matrix.unwrap_or([16; 64]), seq_header: Vec::new(), - reference: None, - prev_mvs: Vec::new(), + older: None, + latest: None, + anchor_mvs: Vec::new(), + held: Vec::new(), count: 0, - gop_pos: 0, + gop_start: 0, + gop_first: 0, + gop_closed: true, + display_pts: VecDeque::new(), + last_pts: None, + pts_step: None, + out: Vec::new(), rc, recon_capture: false, recon: Vec::new(), @@ -367,13 +436,32 @@ impl Encoder { self.recon_capture = on; } + /// The reconstructions captured so far, in display order. pub fn take_recon(&mut self) -> Vec<ReconFrame> { - std::mem::take(&mut self.recon) + let mut r = std::mem::take(&mut self.recon); + r.sort_by_key(|(n, _)| *n); + r.into_iter().map(|(_, f)| f).collect() } - /// Pictures held for reordering (none yet: there are no B pictures). + /// Code the pictures held for reordering (the last of them becomes a P picture) and return + /// every packet not yet returned. The next picture starts a new GOP. pub fn flush(&mut self) -> Vec<Packet> { - Vec::new() + let mut out = Vec::new(); + if let Some(last) = self.held.pop() { + self.code_anchor(last, PictureType::P, &mut out); + } + // the GOP ends here: its budget covered `gop_size` pictures, so take back the share of + // those that never came, or every flushed GOP would raise the bitrate of the next + if self.latest.is_some() { + let missing = u64::from(self.cfg.gop_size).saturating_sub(self.count - self.gop_start); + if let Some(rc) = self.rc.as_mut() { + rc.end_gop(missing as u32); + } + } + self.older = None; + self.latest = None; + self.anchor_mvs.clear(); + self.release(out, true) } fn sequence_header_bytes(&self) -> Vec<u8> { @@ -406,16 +494,15 @@ impl Encoder { w.put((bit_rate >> 18) as u32 & 0xFFF, 12); w.bit(true); // marker_bit w.put((vbv >> 10) as u32 & 0xFF, 8); - w.bit(true); // low_delay: no B pictures + w.bit(c.b_pictures == 0); // low_delay: no B pictures, no reordering w.put(0, 2); // frame_rate_extension_n w.put(0, 5); // frame_rate_extension_d w.finish() } - /// group_of_pictures_header with the time code of picture `self.count`. - fn gop_header(&self, w: &mut BitWriter) { + /// group_of_pictures_header with the time code of display picture `n`. + fn gop_header(&self, w: &mut BitWriter, n: u64, closed: bool) { let fps = u64::from(self.cfg.fps_num.div_ceil(self.cfg.fps_den)).max(1); - let n = self.count; let secs = n / fps; w.start_code(0xB8); w.bit(false); // drop_frame_flag @@ -424,24 +511,40 @@ impl Encoder { w.bit(true); // marker_bit w.put((secs % 60) as u32, 6); w.put((n % fps) as u32, 6); - w.bit(true); // closed_gop + w.bit(closed); // closed_gop w.bit(false); // broken_link } - fn picture_header(&self, w: &mut BitWriter, intra: bool) { + fn picture_header(&self, w: &mut BitWriter, ptype: PictureType, temporal_reference: u64) { w.start_code(0x00); - w.put(self.gop_pos & 0x3FF, 10); // temporal_reference: display order within the GOP - w.put(if intra { 1 } else { 2 }, 3); + w.put((temporal_reference & 0x3FF) as u32, 10); // display order within the GOP + w.put( + match ptype { + PictureType::P => 2, + PictureType::B => 3, + _ => 1, + }, + 3, + ); w.put(0xFFFF, 16); // vbv_delay: variable bitrate - if !intra { - w.bit(false); // full_pel_forward_vector - w.put(7, 3); // forward_f_code (MPEG-2: in the extension) + for dir in [PictureType::P, PictureType::B] { + if ptype == dir || ptype == PictureType::B { + // full_pel_{forward,backward}_vector and {forward,backward}_f_code: MPEG-2 + // carries them in the extension + w.bit(false); + w.put(7, 3); + } } w.bit(false); // extra_bit_picture w.start_code(0xB5); w.put(8, 4); // picture coding extension - let fc = if intra { 15 } else { u32::from(self.f_code) }; - for v in [fc, fc, 15, 15] { + let fc = u32::from(self.f_code); + let f_codes = match ptype { + PictureType::P => [fc, fc, 15, 15], + PictureType::B => [fc; 4], + _ => [15; 4], + }; + for v in f_codes { w.put(v, 4); } w.put(u32::from(self.cfg.intra_dc_bits - 8), 2); @@ -502,28 +605,113 @@ impl Encoder { acts.iter().map(|&a| qcode_for(nl, base * (2.0 * a + avg) / (a + 2.0 * avg))).collect() } - /// Encode one picture. Returns the packets that became ready (one per picture for now). + /// With B pictures, presentation times must step by a constant amount, and the decoding + /// times (one step earlier) must fit in an `i64`. Checked before any state changes. + fn check_pts(&self, pts: i64) -> Result<Option<i64>, EncodeError> { + if self.cfg.b_pictures == 0 { + return Ok(None); + } + let no_dts = |pts: i64, step: i64| EncodeError::BadTimestamp(format!("{pts}: no decoding time {step} earlier")); + let Some(last) = self.last_pts else { + // flushed before a second picture, this one decodes at `pts - 1` (see `release`) + return if pts == i64::MIN { Err(no_dts(pts, 1)) } else { Ok(None) }; + }; + let step = pts.checked_sub(last).filter(|&d| d > 0).ok_or_else(|| EncodeError::BadTimestamp(format!("{pts} after {last}")))?; + match self.pts_step { + Some(s) if s != step => Err(EncodeError::BadTimestamp(format!("{pts} after {last}: step {step}, earlier {s}"))), + // the earliest decoding time is the earlier picture's time less the step + None if last.checked_sub(step).is_none() => Err(no_dts(last, step)), + _ => Ok(Some(step)), + } + } + + /// Encode one picture (display order). Returns the packets that became ready, in decoding + /// order: with B pictures, a B picture is held until the anchor after it is coded. pub fn encode(&mut self, frame: &YuvFrame, pts: i64) -> Result<Vec<Packet>, EncodeError> { let src = self.load(frame)?; - let reference = if self.gop_pos == 0 { None } else { self.reference.take() }; - let intra = reference.is_none(); + if let Some(step) = self.check_pts(pts)? { + self.pts_step = Some(step); + } + self.last_pts = Some(pts); + let n = self.count; + self.count += 1; + self.display_pts.push_back(pts); + let held = Held { src, pts, n }; + let mut out = Vec::new(); + let m = u64::from(self.cfg.b_pictures) + 1; + if self.latest.is_none() || n - self.gop_start >= u64::from(self.cfg.gop_size) { + self.code_anchor(held, PictureType::I, &mut out); + } else if (n - self.gop_start).is_multiple_of(m) { + self.code_anchor(held, PictureType::P, &mut out); + } else { + self.held.push(held); + } + Ok(self.release(out, false)) + } + + /// Code an anchor picture, then the B pictures held in front of it. + fn code_anchor(&mut self, h: Held, ptype: PictureType, out: &mut Vec<Packet>) { + let intra = ptype == PictureType::I; if intra { - self.gop_pos = 0; + self.gop_start = h.n; + self.gop_first = self.held.first().map_or(h.n, |b| b.n); + self.gop_closed = self.cfg.closed_gop || self.held.is_empty(); + let n = u64::from(self.cfg.gop_size); + let m = u64::from(self.cfg.b_pictures) + 1; + let np = (n - 1) / m; if let Some(rc) = self.rc.as_mut() { - rc.start_gop(self.cfg.gop_size); + rc.start_gop(np as u32, (n - 1 - np) as u32); } } + let fwd = if intra { None } else { self.latest.as_ref().map(|r| &r.0) }; + let cand: &[[i32; 2]] = if intra { &[] } else { &self.anchor_mvs }; + let c = self.code_picture(&h, ptype, (fwd, None), [cand, &[]]); + let (recon, mvs) = self.finish(c, h.n, out); + self.older = self.latest.take(); + self.latest = Some((recon, h.n)); + self.anchor_mvs = if intra { Vec::new() } else { mvs }; + for b in std::mem::take(&mut self.held) { + self.code_b(b, out); + } + } + + /// Code a B picture between the two latest anchors. The leading B pictures of a closed GOP + /// (shown before its I picture) predict backward only. + fn code_b(&mut self, b: Held, out: &mut Vec<Packet>) { + let Some((bwd, bn)) = self.latest.as_ref() else { return }; + let leading = b.n < self.gop_start; + let fwd = self.older.as_ref().filter(|_| !(leading && self.gop_closed)); + // search candidates: the latest anchor's vectors (which span the two anchors) scaled to + // this picture's distance from each + let span = self.older.as_ref().map_or(1, |o| bn.saturating_sub(o.1).max(1)) as i64; + let scaled = |d: i64| -> Vec<[i32; 2]> { + self.anchor_mvs.iter().map(|v| [(i64::from(v[0]) * d / span) as i32, (i64::from(v[1]) * d / span) as i32]).collect() + }; + let cf = fwd.map_or(Vec::new(), |f| scaled(b.n as i64 - f.1 as i64)); + let cb = scaled(b.n as i64 - *bn as i64); + let c = self.code_picture(&b, PictureType::B, (fwd.map(|f| &f.0), Some(bwd)), [&cf, &cb]); + self.finish(c, b.n, out); + } + + /// Code one picture with the given references and search candidates. + fn code_picture(&self, h: &Held, ptype: PictureType, (fwd, bwd): (Option<&Frame>, Option<&Frame>), cand: [&[[i32; 2]]; 2]) -> Coded { let base = match (&self.rc, self.cfg.rate) { - (Some(rc), _) => rc.qscale(intra), - (None, RateControl::Quantiser(q)) => f64::from(qscale(self.cfg.nonlinear_quant, q)), + (Some(rc), _) => rc.qscale(ptype), + (None, RateControl::Quantiser(q)) => { + let qs = f64::from(qscale(self.cfg.nonlinear_quant, q)); + if ptype == PictureType::B { qs * B_QUANT_FACTOR } else { qs } + } (None, _) => 8.0, }; - let mb_qcode = self.mb_quant(&src, base); + let src = &h.src; + let mb_qcode = self.mb_quant(src, base); let mut recon = Frame::new(src.w, src.h, src.cw, src.ch); let ctx = PicCtx { - src: &src, - reference: reference.as_ref(), - prev_mvs: &self.prev_mvs, + ptype, + src, + fwd, + bwd, + cand, mb_w: self.mb_w, shx: self.shx, shy: self.shy, @@ -536,11 +724,12 @@ impl Encoder { mb_qcode: &mb_qcode, }; let rows = encode_rows(&ctx, &mut recon, self.cfg.threads); + let intra = ptype == PictureType::I; let mut w = BitWriter::new(); if intra { - self.gop_header(&mut w); + self.gop_header(&mut w, self.gop_first, self.gop_closed); } - self.picture_header(&mut w, intra); + self.picture_header(&mut w, ptype, h.n - self.gop_first); let mut data = if intra { self.seq_header.clone() } else { Vec::new() }; data.extend_from_slice(&w.finish()); let mut qsum = 0u64; @@ -551,18 +740,47 @@ impl Encoder { mvs.extend_from_slice(&r.mvs); } let avg_q = qsum as f64 / (self.mb_w * self.mb_h).max(1) as f64; + let packet = Packet { data, pts: h.pts, dts: h.pts, keyframe: intra, picture_type: ptype, quantiser_scale: avg_q as f32 }; + Coded { packet, recon, mvs, avg_q } + } + + /// Account for a coded picture (display index `n`): rate control, its decoding time, the + /// reconstruction capture. Returns the reconstruction and the picture's vectors. + fn finish(&mut self, c: Coded, n: u64, out: &mut Vec<Packet>) -> (Frame, Vec<[i32; 2]>) { + let Coded { mut packet, recon, mvs, avg_q } = c; if let Some(rc) = self.rc.as_mut() { - rc.update(intra, data.len() as u64 * 8, avg_q); + rc.update(packet.picture_type, packet.data.len() as u64 * 8, avg_q); } + // the k-th coded picture decodes at the k-th presentation time (less the offset that + // `release` subtracts); one time is queued per input picture + packet.dts = self.display_pts.pop_front().unwrap_or(packet.pts); if self.recon_capture { - self.recon.push(self.crop(&recon)); + self.recon.push((n, self.crop(&recon))); } - self.reference = Some(recon); - self.prev_mvs = mvs; - self.count += 1; - self.gop_pos = (self.gop_pos + 1) % self.cfg.gop_size; - let picture_type = if intra { PictureType::I } else { PictureType::P }; - Ok(vec![Packet { data, pts, dts: pts, keyframe: intra, picture_type, quantiser_scale: avg_q as f32 }]) + out.push(packet); + (recon, mvs) + } + + /// Hand out packets once their decoding times are known: with B pictures they are the + /// presentation times one step earlier, so packets wait for the second picture's time. + fn release(&mut self, out: Vec<Packet>, flushing: bool) -> Vec<Packet> { + self.out.extend(out); + if self.cfg.b_pictures == 0 { + return std::mem::take(&mut self.out); + } + if self.pts_step.is_none() && !flushing { + return Vec::new(); + } + // A lone picture flushed before a second one set the step decodes one unit early, the + // smallest step there is: if encoding goes on, the next picture decodes at this one's + // presentation time whatever the step turns out to be, and that must be later. + let off = self.pts_step.unwrap_or(1); + let mut res = std::mem::take(&mut self.out); + for p in &mut res { + // `check_pts` refused the times this would not fit for + p.dts = p.dts.saturating_sub(off); + } + res } fn crop(&self, f: &Frame) -> ReconFrame { diff --git a/crates/video/src/mpeg2/encode/motion.rs b/crates/video/src/mpeg2/encode/motion.rs index a7bedc80b..8242faafe 100644 --- a/crates/video/src/mpeg2/encode/motion.rs +++ b/crates/video/src/mpeg2/encode/motion.rs @@ -47,7 +47,7 @@ impl Search<'_> { } /// A half-sample vector the bitstream can carry whose prediction stays inside the reference. - fn valid(&self, mv: [i32; 2]) -> bool { + pub(crate) fn valid(&self, mv: [i32; 2]) -> bool { let f = 1i32 << self.f_code.saturating_sub(1); let (ox, oy) = self.origin(); let size = [self.reference.w as i32, self.reference.h as i32]; @@ -58,7 +58,8 @@ impl Search<'_> { }) } - fn mv_cost(&self, mv: [i32; 2]) -> u32 { + /// λ·(bits of `mv` against the predictor). + pub(crate) fn mv_cost(&self, mv: [i32; 2]) -> u32 { let t = enc_tables(); let bits: u32 = (0..2).map(|c| t.motion_bits(wrap_delta(mv[c], self.pmv[c], self.f_code), self.f_code)).sum(); self.lambda * bits diff --git a/crates/video/src/mpeg2/encode/picture.rs b/crates/video/src/mpeg2/encode/picture.rs index e7bb84b7e..0be5dbafd 100644 --- a/crates/video/src/mpeg2/encode/picture.rs +++ b/crates/video/src/mpeg2/encode/picture.rs @@ -1,11 +1,11 @@ //! Slices and macroblocks of one frame picture (H.262 §6.2.4-§6.2.6), with a reconstruction //! that matches the decoder exactly. One slice per macroblock row; slices only depend on the -//! reference picture, so rows can be coded in parallel. +//! reference pictures, so rows can be coded in parallel. -use crate::mpeg2::headers::SCAN; +use crate::mpeg2::headers::{PictureType, SCAN}; use crate::mpeg2::mc::{Block, Frame, predict}; use crate::mpeg2::slice::NON_LINEAR_Q; -use crate::mpeg2::vlc::{MB_FWD, MB_INTRA, MB_PATTERN, MB_QUANT}; +use crate::mpeg2::vlc::{MB_BWD, MB_FWD, MB_INTRA, MB_PATTERN, MB_QUANT}; use super::bitwriter::BitWriter; use super::motion::Search; @@ -35,12 +35,17 @@ pub(crate) fn qcode_for(nonlinear: bool, qs: f64) -> u8 { /// What every slice of one picture shares (read-only). pub(crate) struct PicCtx<'a> { + /// I, P or B. + pub ptype: PictureType, /// The padded source picture. pub src: &'a Frame, - /// The reconstructed previous picture (P pictures); `None` codes an I picture. - pub reference: Option<&'a Frame>, - /// Vectors of the previous picture (motion search candidates), one per macroblock. - pub prev_mvs: &'a [[i32; 2]], + /// The reconstructed reference pictures: forward (P and B pictures) and backward (B + /// pictures). A B picture without a forward reference (the leading B pictures of a closed + /// GOP) predicts backward only. + pub fwd: Option<&'a Frame>, + pub bwd: Option<&'a Frame>, + /// Motion search candidates per macroblock, forward and backward (empty: none). + pub cand: [&'a [[i32; 2]]; 2], pub mb_w: usize, pub shx: u32, pub shy: u32, @@ -166,11 +171,22 @@ impl MbPix { struct SliceSt { qcode: u8, dc: [i32; 3], - pmv: [i32; 2], + /// Motion vector predictors, forward and backward. + pmv: [[i32; 2]; 2], /// Skipped macroblocks not yet covered by an address increment. skipped: usize, - /// The vector of the macroblock to the left (motion search candidate). - left_mv: [i32; 2], + /// The vectors of the macroblock to the left (motion search candidates). + left_mv: [[i32; 2]; 2], + /// Prediction directions (`MB_FWD` / `MB_BWD`) of the previous macroblock, or `MB_INTRA`: + /// a skipped macroblock in a B picture repeats them. + last_dirs: i16, +} + +/// A B macroblock's prediction: its directions and a vector per direction. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct BPred { + dirs: i16, + mvs: [[i32; 2]; 2], } /// One macroblock being coded. @@ -188,7 +204,7 @@ pub(crate) fn encode_row(ctx: &PicCtx, row: usize, out: &mut RowPlanes) -> RowOu let q0 = ctx.mb_qcode.get(row * ctx.mb_w).copied().unwrap_or(1); w.put(u32::from(q0), 5); w.bit(false); // extra_bit_slice - let mut st = SliceSt { qcode: q0, dc: [ctx.dc_reset(); 3], pmv: [0; 2], skipped: 0, left_mv: [0; 2] }; + let mut st = SliceSt { qcode: q0, dc: [ctx.dc_reset(); 3], pmv: [[0; 2]; 2], skipped: 0, left_mv: [[0; 2]; 2], last_dirs: MB_INTRA }; let mut ro = RowOut { bytes: Vec::new(), mvs: vec![[0; 2]; ctx.mb_w], stats: RowStats::default() }; for mbx in 0..ctx.mb_w { macroblock(ctx, &mut st, &mut w, (mbx, row), out, &mut ro); @@ -205,31 +221,105 @@ fn macroblock(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, (mbx, mby): (us let qs = qscale(ctx.nonlinear, qcode); ro.stats.qsum += qs as u64; let planes = (ctx.src.w, ctx.src.cw); - let Some(reference) = ctx.reference else { - intra_mb(ctx, st, w, &mb).put(out, mbx, ctx.cmb(), planes); - ro.stats.intra += 1; - return; + let lambda = ((qs * 3 + 4) / 8).max(1) as u32; + let rec = match (ctx.ptype, ctx.fwd) { + (PictureType::P, Some(reference)) => { + let search = Search { reference, src: &src.y, mbx, mby, f_code: ctx.f_code, range: ctx.search, pmv: st.pmv[0], lambda }; + let found = search.run(&candidates(ctx, st, addr, 0)); + if intra_cost(&src.y).saturating_add(INTRA_BIAS) < found.sad { + None + } else { + let (rec, skipped) = inter_mb(ctx, st, w, &mb, reference, found.mv); + ro.stats.skipped += skipped as u32; + ro.mvs[mbx] = found.mv; + st.left_mv[0] = found.mv; + Some(rec) + } + } + (PictureType::B, _) if ctx.bwd.is_some() => b_decision(ctx, st, &mb, lambda).map(|pred| { + let (rec, skipped) = b_mb(ctx, st, w, &mb, pred); + ro.stats.skipped += skipped as u32; + st.left_mv = pred.mvs; + rec + }), + _ => None, }; - let mut candidates = vec![st.left_mv, st.pmv]; + let rec = rec.unwrap_or_else(|| { + ro.stats.intra += 1; + st.left_mv = [[0; 2]; 2]; + intra_mb(ctx, st, w, &mb) + }); + rec.put(out, mbx, ctx.cmb(), planes); +} + +/// Motion search candidates for direction `s` of macroblock `addr`: the left neighbour's vector, +/// the predictor, and the co-located and neighbouring candidates of the picture. +fn candidates(ctx: &PicCtx, st: &SliceSt, addr: usize, s: usize) -> Vec<[i32; 2]> { + let mut c = vec![st.left_mv[s], st.pmv[s]]; for a in [Some(addr), addr.checked_sub(ctx.mb_w), Some(addr + 1), Some(addr + ctx.mb_w)].into_iter().flatten() { - if let Some(&v) = ctx.prev_mvs.get(a) { - candidates.push(v); + if let Some(&v) = ctx.cand[s].get(a) { + c.push(v); } } - let lambda = ((qs * 3 + 4) / 8).max(1) as u32; - let search = Search { reference, src: &src.y, mbx, mby, f_code: ctx.f_code, range: ctx.search, pmv: st.pmv, lambda }; - let found = search.run(&candidates); - if intra_cost(&src.y).saturating_add(INTRA_BIAS) < found.sad { - intra_mb(ctx, st, w, &mb).put(out, mbx, ctx.cmb(), planes); - ro.stats.intra += 1; - st.left_mv = [0; 2]; - return; + c +} + +/// Luma SAD of a prediction against the source. +fn sad(a: &[u8; 256], b: &[u8; 256]) -> u32 { + a.iter().zip(b).map(|(x, y)| u32::from(x.abs_diff(*y))).sum() +} + +/// Choose a B macroblock's prediction: forward, backward or interpolated, from a motion search +/// per direction, or the skip prediction (the previous macroblock's directions with the +/// predictors). `None`: code it intra. +fn b_decision(ctx: &PicCtx, st: &SliceSt, mb: &MbIn, lambda: u32) -> Option<BPred> { + let addr = mb.mby * ctx.mb_w + mb.mbx; + let mut found = [None, None]; + for (s, r) in [ctx.fwd, ctx.bwd].into_iter().enumerate() { + if let Some(reference) = r { + let search = + Search { reference, src: &mb.src.y, mbx: mb.mbx, mby: mb.mby, f_code: ctx.f_code, range: ctx.search, pmv: st.pmv[s], lambda }; + let f = search.run(&candidates(ctx, st, addr, s)); + found[s] = Some((f.mv, f.sad, search.mv_cost(f.mv))); + } } - let (rec, skipped) = inter_mb(ctx, st, w, &mb, reference, found.mv); - rec.put(out, mbx, ctx.cmb(), planes); - ro.stats.skipped += skipped as u32; - ro.mvs[mbx] = found.mv; - st.left_mv = found.mv; + let mut best: Option<(BPred, u32)> = None; + let mut consider = |pred: BPred, cost: u32| { + if best.is_none_or(|(_, c)| cost < c) { + best = Some((pred, cost)); + } + }; + for (s, dir) in [(0, MB_FWD), (1, MB_BWD)] { + if let Some((mv, sad, bits)) = found[s] { + let mut mvs = [[0; 2]; 2]; + mvs[s] = mv; + consider(BPred { dirs: dir, mvs }, sad.saturating_add(bits)); + } + } + if let (Some((f, _, bits_f)), Some((b, _, bits_b))) = (found[0], found[1]) { + let pred = BPred { dirs: MB_FWD | MB_BWD, mvs: [f, b] }; + let p = predict_b(ctx, pred, mb.mbx, mb.mby); + consider(pred, sad(&p.y, &mb.src.y).saturating_add(bits_f).saturating_add(bits_b)); + } + // the skip prediction costs no vector bits; the predictors came from the macroblock to the + // left, so they must be checked to stay inside the reference from here + let edge = mb.mbx == 0 || mb.mbx + 1 == ctx.mb_w; + if !edge && st.last_dirs & MB_INTRA == 0 && st.last_dirs != 0 { + let pred = BPred { dirs: st.last_dirs, mvs: st.pmv }; + let usable = [(0, MB_FWD, ctx.fwd), (1, MB_BWD, ctx.bwd)].into_iter().all(|(s, dir, r)| { + st.last_dirs & dir == 0 + || r.is_some_and(|reference| { + let search = + Search { reference, src: &mb.src.y, mbx: mb.mbx, mby: mb.mby, f_code: ctx.f_code, range: ctx.search, pmv: st.pmv[s], lambda }; + search.valid(st.pmv[s]) + }) + }); + if usable { + consider(pred, sad(&predict_b(ctx, pred, mb.mbx, mb.mby).y, &mb.src.y)); + } + } + let (pred, cost) = best?; + (intra_cost(&mb.src.y).saturating_add(INTRA_BIAS) >= cost).then_some(pred) } /// Σ |sample − block mean| over the four luma blocks: the cost of coding them intra. @@ -270,8 +360,12 @@ fn put_coefficients(w: &mut BitWriter, t: &EncTables, levels: &[i32; 64], table: t.dct_eob[table].put(w); } -fn put_mb_type(w: &mut BitWriter, t: &EncTables, predicted: bool, flags: i16) { - let table = if predicted { &t.mbtype_p } else { &t.mbtype_i }; +fn put_mb_type(w: &mut BitWriter, t: &EncTables, ptype: PictureType, flags: i16) { + let table = match ptype { + PictureType::P => &t.mbtype_p, + PictureType::B => &t.mbtype_b, + _ => &t.mbtype_i, + }; if let Some(c) = table.get(flags as usize).copied().flatten() { c.put(w); } @@ -283,12 +377,13 @@ fn intra_mb(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, mb: &MbIn) -> MbP let quant = mb.qcode != st.qcode; put_increment(w, t, st.skipped + 1); st.skipped = 0; - put_mb_type(w, t, ctx.reference.is_some(), if quant { MB_INTRA | MB_QUANT } else { MB_INTRA }); + put_mb_type(w, t, ctx.ptype, if quant { MB_INTRA | MB_QUANT } else { MB_INTRA }); if quant { w.put(u32::from(mb.qcode), 5); st.qcode = mb.qcode; } - st.pmv = [0; 2]; + st.pmv = [[0; 2]; 2]; + st.last_dirs = MB_INTRA; let qs = qscale(ctx.nonlinear, st.qcode); let dc_mult = 8 >> ctx.dc_prec; let dc_max = (1 << (8 + ctx.dc_prec)) - 1; @@ -321,28 +416,16 @@ fn intra_mb(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, mb: &MbIn) -> MbP /// whether it was skipped. fn inter_mb(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, mb: &MbIn, reference: &Frame, mv: [i32; 2]) -> (MbPix, bool) { let t = enc_tables(); - let mut rec = predict_mb(ctx, reference, mv, mb.mbx, mb.mby); + let mut rec = predict_mb(ctx, Some(reference), mv, mb.mbx, mb.mby); let qs = qscale(ctx.nonlinear, mb.qcode); - let (cbw, _) = ctx.cmb(); - let n = ctx.blocks(); - let mut levels = [[0i32; 64]; 8]; - let mut cbp = 0u32; - for i in 0..n { - let (s, p) = (mb.src.block(i, cbw), rec.block(i, cbw)); - let f = fdct(&std::array::from_fn(|k| s[k] - p[k])); - for pos in 0..64 { - levels[i][pos] = quant_inter(f[pos], ctx.inter_matrix[pos], qs); - } - if levels[i].iter().any(|&l| l != 0) { - cbp |= 1 << (n - 1 - i); - } - } + let (levels, cbp) = residual(ctx, mb, &rec, qs); st.dc = [ctx.dc_reset(); 3]; + st.last_dirs = MB_FWD; // the first and last macroblock of a slice are always coded let edge = mb.mbx == 0 || mb.mbx + 1 == ctx.mb_w; if mv == [0, 0] && cbp == 0 && !edge { st.skipped += 1; - st.pmv = [0; 2]; + st.pmv = [[0; 2]; 2]; return (rec, true); } put_increment(w, t, st.skipped + 1); @@ -358,44 +441,140 @@ fn inter_mb(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, mb: &MbIn, refere if quant { flags |= MB_QUANT; } - put_mb_type(w, t, true, flags); + put_mb_type(w, t, PictureType::P, flags); if quant { w.put(u32::from(mb.qcode), 5); st.qcode = mb.qcode; } if flags & MB_FWD != 0 { for c in 0..2 { - t.put_motion(w, wrap_delta(mv[c], st.pmv[c], ctx.f_code), ctx.f_code); + t.put_motion(w, wrap_delta(mv[c], st.pmv[0][c], ctx.f_code), ctx.f_code); } - st.pmv = mv; + st.pmv[0] = mv; } else { - st.pmv = [0; 2]; // "No MC" resets the predictors - } - if cbp != 0 { - if n == 8 { - t.cbp[(cbp >> 2) as usize].put(w); - w.put(cbp & 3, 2); - } else { - t.cbp[cbp as usize].put(w); - } - for i in 0..n { - if cbp & (1 << (n - 1 - i)) != 0 { - put_coefficients(w, t, &levels[i], 0, 0); - rec.store(i, cbw, &reconstruct(&levels[i], ctx.inter_matrix, qs, false, 0), true); - } - } + st.pmv = [[0; 2]; 2]; // "No MC" resets the predictors } + put_residual(ctx, w, &levels, cbp, &mut rec, qs); (rec, false) } -/// The frame prediction of a macroblock from `f` with vector `mv`, formed as the decoder forms -/// it (§7.6.4: chroma vectors are the luma ones halved towards zero). -fn predict_mb(ctx: &PicCtx, f: &Frame, mv: [i32; 2], mbx: usize, mby: usize) -> MbPix { - let (cbw, cbh) = ctx.cmb(); +/// Quantised residual of every block of `mb` against `pred`, and the coded_block_pattern. +fn residual(ctx: &PicCtx, mb: &MbIn, pred: &MbPix, qs: i32) -> ([[i32; 64]; 8], u32) { + let (cbw, _) = ctx.cmb(); + let n = ctx.blocks(); + let mut levels = [[0i32; 64]; 8]; + let mut cbp = 0u32; + for i in 0..n { + let (s, p) = (mb.src.block(i, cbw), pred.block(i, cbw)); + let f = fdct(&std::array::from_fn(|k| s[k] - p[k])); + for pos in 0..64 { + levels[i][pos] = quant_inter(f[pos], ctx.inter_matrix[pos], qs); + } + if levels[i].iter().any(|&l| l != 0) { + cbp |= 1 << (n - 1 - i); + } + } + (levels, cbp) +} + +/// Write coded_block_pattern and the coded blocks, adding their reconstruction to `rec`. +fn put_residual(ctx: &PicCtx, w: &mut BitWriter, levels: &[[i32; 64]; 8], cbp: u32, rec: &mut MbPix, qs: i32) { + if cbp == 0 { + return; + } + let t = enc_tables(); + let (cbw, _) = ctx.cmb(); + let n = ctx.blocks(); + if n == 8 { + t.cbp[(cbp >> 2) as usize].put(w); + w.put(cbp & 3, 2); + } else { + t.cbp[cbp as usize].put(w); + } + for i in 0..n { + if cbp & (1 << (n - 1 - i)) != 0 { + put_coefficients(w, t, &levels[i], 0, 0); + rec.store(i, cbw, &reconstruct(&levels[i], ctx.inter_matrix, qs, false, 0), true); + } + } +} + +/// Code a B macroblock with prediction `pred` (or skip it); returns its reconstruction and +/// whether it was skipped. +fn b_mb(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, mb: &MbIn, pred: BPred) -> (MbPix, bool) { + let t = enc_tables(); + let mut rec = predict_b(ctx, pred, mb.mbx, mb.mby); + let qs = qscale(ctx.nonlinear, mb.qcode); + let (levels, cbp) = residual(ctx, mb, &rec, qs); + st.dc = [ctx.dc_reset(); 3]; + // a skipped B macroblock repeats the previous one's directions with the predictors as its + // vectors (§7.6.6.3); the first and last macroblock of a slice are always coded + let edge = mb.mbx == 0 || mb.mbx + 1 == ctx.mb_w; + let same = |s: usize, dir: i16| pred.dirs & dir == 0 || pred.mvs[s] == st.pmv[s]; + if cbp == 0 && !edge && st.last_dirs & MB_INTRA == 0 && pred.dirs == st.last_dirs && same(0, MB_FWD) && same(1, MB_BWD) { + st.skipped += 1; + return (rec, true); + } + put_increment(w, t, st.skipped + 1); + st.skipped = 0; + let quant = cbp != 0 && mb.qcode != st.qcode; + let mut flags = pred.dirs; + if cbp != 0 { + flags |= MB_PATTERN; + } + if quant { + flags |= MB_QUANT; + } + put_mb_type(w, t, PictureType::B, flags); + if quant { + w.put(u32::from(mb.qcode), 5); + st.qcode = mb.qcode; + } + for (s, dir) in [(0, MB_FWD), (1, MB_BWD)] { + if pred.dirs & dir != 0 { + for c in 0..2 { + t.put_motion(w, wrap_delta(pred.mvs[s][c], st.pmv[s][c], ctx.f_code), ctx.f_code); + } + st.pmv[s] = pred.mvs[s]; + } + } + st.last_dirs = pred.dirs; + put_residual(ctx, w, &levels, cbp, &mut rec, qs); + (rec, false) +} + +/// The prediction of a B macroblock: forward, backward, or the average of both, formed in the +/// decoder's order (forward first, then the backward prediction averaged in). +fn predict_b(ctx: &PicCtx, pred: BPred, mbx: usize, mby: usize) -> MbPix { let mut p = MbPix { y: [0; 256], c: [[0; 256]; 2] }; + let mut avg = false; + for (s, dir, r) in [(0, MB_FWD, ctx.fwd), (1, MB_BWD, ctx.bwd)] { + if pred.dirs & dir != 0 { + if let Some(f) = r { + predict_into(ctx, &mut p, f, pred.mvs[s], (mbx, mby), avg); + } + avg = true; + } + } + p +} + +/// The frame prediction of a macroblock from `f` with vector `mv` (gray without a reference). +fn predict_mb(ctx: &PicCtx, f: Option<&Frame>, mv: [i32; 2], mbx: usize, mby: usize) -> MbPix { + let mut p = MbPix { y: [128; 256], c: [[128; 256]; 2] }; + if let Some(f) = f { + predict_into(ctx, &mut p, f, mv, (mbx, mby), false); + } + p +} + +/// Form the frame prediction from `f` with vector `mv` into `p`, or average it with what `p` +/// holds, as the decoder forms it (§7.6.4: chroma vectors are the luma ones halved towards zero). +fn predict_into(ctx: &PicCtx, p: &mut MbPix, f: &Frame, mv: [i32; 2], (mbx, mby): (usize, usize), avg: bool) { + let (cbw, cbh) = ctx.cmb(); let blk = Block { x: (mbx * 16) as i32 + (mv[0] >> 1), y: (mby * 16) as i32 + (mv[1] >> 1), hx: mv[0] & 1 != 0, hy: mv[1] & 1 != 0, bw: 16, bh: 16 }; - predict(&mut p.y, 0, 16, f.plane(0, None), blk, false); + predict(&mut p.y, 0, 16, f.plane(0, None), blk, avg); let cmv = [if ctx.shx == 1 { mv[0] / 2 } else { mv[0] }, if ctx.shy == 1 { mv[1] / 2 } else { mv[1] }]; let cb = Block { x: (mbx * cbw) as i32 + (cmv[0] >> 1), @@ -406,7 +585,48 @@ fn predict_mb(ctx: &PicCtx, f: &Frame, mv: [i32; 2], mbx: usize, mby: usize) -> bh: cbh, }; for c in 0..2 { - predict(&mut p.c[c], 0, cbw, f.plane(1 + c, None), cb, false); + predict(&mut p.c[c], 0, cbw, f.plane(1 + c, None), cb, avg); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_skip_prediction_never_leaves_the_reference() { + // three macroblocks across; the left neighbour's forward vector (+17 samples) fits its + // own position but points past the right edge from the middle macroblock + let mut f = Frame::new(48, 16, 24, 8); + for (i, v) in f.planes[0].iter_mut().enumerate() { + *v = ((i % 48) * 5 + (i / 48) * 11) as u8; + } + let ctx = PicCtx { + ptype: PictureType::B, + src: &f, + fwd: Some(&f), + bwd: Some(&f), + cand: [&[], &[]], + mb_w: 3, + shx: 1, + shy: 1, + intra_matrix: &crate::mpeg2::headers::DEFAULT_INTRA, + inter_matrix: &[16; 64], + nonlinear: true, + dc_prec: 1, + f_code: 3, + search: 31, + mb_qcode: &[4; 3], + }; + let bad = BPred { dirs: MB_FWD, mvs: [[34, 0], [0, 0]] }; + // the bitstream can carry the vector (f_code 3: -64..64): only the position rules it out + let at = |mbx| Search { reference: &f, src: &[0; 256], mbx, mby: 0, f_code: ctx.f_code, range: ctx.search, pmv: bad.mvs[0], lambda: 1 }; + assert!(at(0).valid(bad.mvs[0]) && !at(1).valid(bad.mvs[0])); + // a source that the out-of-range (edge-clamped) prediction would match exactly + let src = predict_b(&ctx, bad, 1, 0); + let st = SliceSt { qcode: 4, dc: [256; 3], pmv: bad.mvs, skipped: 0, left_mv: bad.mvs, last_dirs: MB_FWD }; + let mb = MbIn { src: &src, mbx: 1, mby: 0, qcode: 4 }; + let pred = b_decision(&ctx, &st, &mb, 1); + assert_ne!(pred, Some(bad)); } - p } diff --git a/crates/video/src/mpeg2/encode/rate.rs b/crates/video/src/mpeg2/encode/rate.rs index 65c23efc3..96c6f2aa1 100644 --- a/crates/video/src/mpeg2/encode/rate.rs +++ b/crates/video/src/mpeg2/encode/rate.rs @@ -1,18 +1,26 @@ //! Single-pass average bitrate control at picture level, after the target bit allocation of the //! MPEG-2 Test Model 5: each picture type keeps a complexity `X = bits · average quantiser`, the -//! bits left for the GOP are shared out by complexity, and a picture's quantiser is `X / target`. -//! There is no VBV model: the average converges on the target, single pictures may not. +//! bits left for the GOP are shared out by complexity (B pictures weighted down by `KB`), and a +//! picture's quantiser is `X / target`. There is no VBV model: the average converges on the +//! target, single pictures may not. + +use crate::mpeg2::headers::PictureType; + +/// TM5's quantiser ratio of B to P pictures (K_b / K_p). +const KB: f64 = 1.4; pub(crate) struct RateCtl { bps: f64, fps: f64, - /// Complexity of I and P pictures. + /// Complexity of I, P and B pictures. xi: f64, xp: f64, + xb: f64, /// Bits left for the current GOP (carries over between GOPs). remaining: f64, - /// P pictures left in the current GOP. + /// P and B pictures left in the current GOP. np: u32, + nb: u32, /// Range of quantiser_scale values. q_min: f64, q_max: f64, @@ -21,34 +29,60 @@ pub(crate) struct RateCtl { impl RateCtl { pub fn new(bps: f64, fps: f64, q_range: (f64, f64)) -> Self { // TM5's starting complexities - Self { bps, fps, xi: 160.0 * bps / 115.0, xp: 60.0 * bps / 115.0, remaining: 0.0, np: 0, q_min: q_range.0, q_max: q_range.1 } + Self { + bps, + fps, + xi: 160.0 * bps / 115.0, + xp: 60.0 * bps / 115.0, + xb: 42.0 * bps / 115.0, + remaining: 0.0, + np: 0, + nb: 0, + q_min: q_range.0, + q_max: q_range.1, + } } - /// A GOP of `pictures` pictures (one I, the rest P) starts. - pub fn start_gop(&mut self, pictures: u32) { - self.remaining += self.bps * f64::from(pictures) / self.fps; - self.np = pictures.saturating_sub(1); + /// A GOP of one I, `np` P and `nb` B pictures starts. + pub fn start_gop(&mut self, np: u32, nb: u32) { + self.remaining += self.bps * f64::from(1 + np + nb) / self.fps; + self.np = np; + self.nb = nb; } - /// quantiser_scale for the next picture. - pub fn qscale(&self, intra: bool) -> f64 { + /// The GOP ends `missing` pictures short of what `start_gop` budgeted (the encoder was + /// flushed): their bits are not carried into the next GOP. + pub fn end_gop(&mut self, missing: u32) { + self.remaining -= self.bps * f64::from(missing) / self.fps; + self.np = 0; + self.nb = 0; + } + + /// quantiser_scale for the next picture of type `ptype`. + pub fn qscale(&self, ptype: PictureType) -> f64 { let floor = self.bps / (8.0 * self.fps); - let (target, x) = if intra { - (self.remaining / (1.0 + f64::from(self.np) * self.xp / self.xi), self.xi) - } else { - (self.remaining / f64::from(self.np.max(1)), self.xp) + let (np, nb) = (f64::from(self.np), f64::from(self.nb)); + let (target, x) = match ptype { + PictureType::I => (self.remaining / (1.0 + np * self.xp / self.xi + nb * self.xb / (self.xi * KB)), self.xi), + PictureType::B => (self.remaining / (nb.max(1.0) + np * KB * self.xp / self.xb), self.xb), + _ => (self.remaining / (np.max(1.0) + nb * self.xb / (KB * self.xp)), self.xp), }; (x / target.max(floor)).clamp(self.q_min, self.q_max) } - /// The picture used `bits` at average quantiser_scale `avg_q`. - pub fn update(&mut self, intra: bool, bits: u64, avg_q: f64) { - let x = bits as f64 * avg_q; - if intra { - self.xi = x.max(1.0); - } else { - self.xp = x.max(1.0); - self.np = self.np.saturating_sub(1); + /// A picture of type `ptype` used `bits` at average quantiser_scale `avg_q`. + pub fn update(&mut self, ptype: PictureType, bits: u64, avg_q: f64) { + let x = (bits as f64 * avg_q).max(1.0); + match ptype { + PictureType::I => self.xi = x, + PictureType::B => { + self.xb = x; + self.nb = self.nb.saturating_sub(1); + } + _ => { + self.xp = x; + self.np = self.np.saturating_sub(1); + } } self.remaining -= bits as f64; } @@ -58,18 +92,26 @@ impl RateCtl { mod tests { use super::*; - /// A picture whose size is `complexity / q` (the model the controller assumes). - fn run(complexity_i: f64, complexity_p: f64, bps: f64, gops: u32) -> f64 { + /// A picture whose size is `complexity / q` (the model the controller assumes), in GOPs of + /// 12 pictures with `b` B pictures between anchors. + fn run(c: [f64; 3], b: usize, bps: f64, gops: u32) -> f64 { let fps = 25.0; + let types: Vec<PictureType> = (0..12) + .map(|k| match k { + 0 => PictureType::I, + k if k % (b + 1) == 0 => PictureType::P, + _ => PictureType::B, + }) + .collect(); + let np = types.iter().filter(|&&t| t == PictureType::P).count() as u32; let mut rc = RateCtl::new(bps, fps, (1.0, 112.0)); let mut total = 0.0; for _ in 0..gops { - rc.start_gop(12); - for k in 0..12 { - let intra = k == 0; - let q = rc.qscale(intra); - let bits = (if intra { complexity_i } else { complexity_p }) / q; - rc.update(intra, bits as u64, q); + rc.start_gop(np, 11 - np); + for &t in &types { + let q = rc.qscale(t); + let bits = c[t as usize] / q; + rc.update(t, bits as u64, q); total += bits; } } @@ -79,24 +121,40 @@ mod tests { #[test] fn converges_on_the_target() { // complexities whose target quantiser is inside the allowed range - for (ci, cp) in [(4e7, 1e7), (8e7, 2e6), (1e7, 9e6)] { - let got = run(ci, cp, 4e6, 20); - assert!((got / 4e6 - 1.0).abs() < 0.03, "{ci} {cp}: {got}"); + for (c, b) in [([4e7, 1e7, 7e6], 0), ([8e7, 2e6, 1e6], 0), ([1e7, 9e6, 8e6], 0), ([4e7, 1e7, 7e6], 2), ([6e7, 2e7, 5e6], 1)] { + let got = run(c, b, 4e6, 20); + assert!((got / 4e6 - 1.0).abs() < 0.03, "{c:?} b {b}: {got}"); } } + #[test] + fn a_gop_cut_short_gives_its_budget_back() { + let mut rc = RateCtl::new(4e6, 25.0, (1.0, 112.0)); + for _ in 0..20 { + // a GOP of 12 that ends after its I picture and two P pictures + rc.start_gop(11, 0); + for t in [PictureType::I, PictureType::P, PictureType::P] { + let q = rc.qscale(t); + rc.update(t, (1e7 / q) as u64, q); + } + rc.end_gop(9); + } + // what is left is the three pictures' rounding, not nine pictures' budget per GOP + assert!(rc.remaining.abs() < 3.0 * 4e6 / 25.0, "{}", rc.remaining); + } + #[test] fn the_quantiser_stays_in_range() { let mut rc = RateCtl::new(1e6, 25.0, (2.0, 62.0)); - rc.start_gop(2); + rc.start_gop(1, 0); // a picture far larger than its budget pushes the next quantiser to the top - rc.update(true, 50_000_000, 10.0); - rc.start_gop(2); - assert_eq!(rc.qscale(true), 62.0); + rc.update(PictureType::I, 50_000_000, 10.0); + rc.start_gop(1, 0); + assert_eq!(rc.qscale(PictureType::I), 62.0); // and a tiny one to the bottom let mut rc = RateCtl::new(1e6, 25.0, (2.0, 62.0)); - rc.start_gop(2); - rc.update(true, 10, 2.0); - assert_eq!(rc.qscale(true), 2.0); + rc.start_gop(1, 0); + rc.update(PictureType::I, 10, 2.0); + assert_eq!(rc.qscale(PictureType::I), 2.0); } } diff --git a/crates/video/src/mpeg2/encode/tables.rs b/crates/video/src/mpeg2/encode/tables.rs index b79dd92ea..e23929450 100644 --- a/crates/video/src/mpeg2/encode/tables.rs +++ b/crates/video/src/mpeg2/encode/tables.rs @@ -4,7 +4,7 @@ use std::sync::OnceLock; use crate::mpeg2::vlc::{ - CBP, DC_CHROMA, DC_LUMA, DCT_EOB, DCT_ESCAPE, DCT_ONE, DCT_ZERO, DCT_ZERO_LONG, MBA, MBA_ESCAPE, MBTYPE_I, MBTYPE_P, MOTION, dct_table, + CBP, DC_CHROMA, DC_LUMA, DCT_EOB, DCT_ESCAPE, DCT_ONE, DCT_ZERO, DCT_ZERO_LONG, MBA, MBA_ESCAPE, MBTYPE_B, MBTYPE_I, MBTYPE_P, MOTION, dct_table, parse_code, }; @@ -38,9 +38,10 @@ pub(crate) struct EncTables { /// macroblock_address_increment 1..=33 (index 0 unused) and the escape. pub mba: [Code; 34], pub mba_escape: Code, - /// macroblock_type by flags: I pictures, P pictures (index: flags, 0..32). + /// macroblock_type by flags: I, P and B pictures (index: flags, 0..32). pub mbtype_i: [Option<Code>; 32], pub mbtype_p: [Option<Code>; 32], + pub mbtype_b: [Option<Code>; 32], /// coded_block_pattern_420 (the first six blocks). pub cbp: [Code; 64], /// motion_code -16..=16 at index code + 16. @@ -105,6 +106,7 @@ pub(crate) fn enc_tables() -> &'static EncTables { mba_escape, mbtype_i: mb_types(MBTYPE_I), mbtype_p: mb_types(MBTYPE_P), + mbtype_b: mb_types(MBTYPE_B), cbp: by_value(CBP, 0), motion: by_value(MOTION, 16), dc_luma: by_value(DC_LUMA, 0), @@ -185,11 +187,25 @@ mod tests { use super::*; use crate::mpeg2::bits::Bits; use crate::mpeg2::slice::wrap_vector; - use crate::mpeg2::vlc::{MB_FWD, MB_INTRA, MB_PATTERN, MB_QUANT, rl, tables}; + use crate::mpeg2::vlc::{MB_BWD, MB_FWD, MB_INTRA, MB_PATTERN, MB_QUANT, rl, tables}; - /// Macroblock types the encoder sends (frame pictures, frame prediction, no B pictures). + /// Macroblock types the encoder sends in P pictures (frame pictures, frame prediction). const ENC_MB_TYPES: [i16; 7] = [MB_INTRA, MB_INTRA | MB_QUANT, MB_FWD | MB_PATTERN, MB_PATTERN, MB_FWD, MB_QUANT | MB_FWD | MB_PATTERN, MB_QUANT | MB_PATTERN]; + /// And in B pictures: every combination of directions, with and without a residual. + const ENC_MB_TYPES_B: [i16; 11] = [ + MB_INTRA, + MB_INTRA | MB_QUANT, + MB_FWD, + MB_BWD, + MB_FWD | MB_BWD, + MB_FWD | MB_PATTERN, + MB_BWD | MB_PATTERN, + MB_FWD | MB_BWD | MB_PATTERN, + MB_QUANT | MB_FWD | MB_PATTERN, + MB_QUANT | MB_BWD | MB_PATTERN, + MB_QUANT | MB_FWD | MB_BWD | MB_PATTERN, + ]; #[test] fn every_code_decodes_to_its_value() { @@ -223,6 +239,9 @@ mod tests { } check(t.mbtype_p[f as usize].unwrap_or_default(), &d.mbtype[1], f); } + for f in ENC_MB_TYPES_B { + check(t.mbtype_b[f as usize].unwrap_or_default(), &d.mbtype[2], f); + } for (k, vlc) in [&d.dct_zero, &d.dct_one].into_iter().enumerate() { for run in 0..=MAX_RUN { for level in 1..=MAX_LEVEL { diff --git a/crates/video/src/mpeg2/encode/tests.rs b/crates/video/src/mpeg2/encode/tests.rs index 5352161b3..01aac2b32 100644 --- a/crates/video/src/mpeg2/encode/tests.rs +++ b/crates/video/src/mpeg2/encode/tests.rs @@ -3,7 +3,7 @@ //! comparison is in `tests/mpeg2/encode.rs`. use super::*; -use crate::mpeg2::{Decoder, access_units, probe}; +use crate::mpeg2::{Decoder, probe}; /// A moving, textured test sequence: a gradient with a sharp pattern drifting by a fraction of a /// sample per picture, and a block moving across it. @@ -54,16 +54,21 @@ fn encode(cfg: EncoderConfig, frames: usize) -> (Vec<u8>, Vec<ReconFrame>, Vec<P packets.push(p); } } - packets.extend(enc.flush()); + for p in enc.flush() { + es.extend_from_slice(&p.data); + packets.push(p); + } es.extend_from_slice(enc.end_of_sequence()); (es, enc.take_recon(), packets) } -fn decode(es: &[u8]) -> Vec<crate::mpeg2::Picture> { +/// Decode packets (each tagged with its presentation time); returns the pictures in display +/// order. +fn decode(packets: &[Packet]) -> Vec<crate::mpeg2::Picture> { let mut d = Decoder::new(); let mut out = Vec::new(); - for (i, r) in access_units(es).into_iter().enumerate() { - out.extend(d.decode(&es[r], i as i64).unwrap()); + for p in packets { + out.extend(d.decode(&p.data, p.pts).unwrap()); } out.extend(d.flush()); assert_eq!(d.errors(), 0, "decoder errors: {:?}", d.last_error()); @@ -71,9 +76,11 @@ fn decode(es: &[u8]) -> Vec<crate::mpeg2::Picture> { } fn assert_decodes_to_recon(name: &str, cfg: EncoderConfig, frames: usize) -> Vec<Packet> { - let (es, recon, packets) = encode(cfg, frames); - let pics = decode(&es); + let (_, recon, packets) = encode(cfg, frames); + assert!(packets.windows(2).all(|w| w[0].dts < w[1].dts) && packets.iter().all(|p| p.dts <= p.pts), "{name}: decoding times"); + let pics = decode(&packets); assert_eq!(pics.len(), frames, "{name}: picture count"); + assert_eq!(recon.len(), frames, "{name}: reconstruction count"); for (i, (p, r)) in pics.iter().zip(&recon).enumerate() { assert_eq!(p.pts, i as i64, "{name}: display order"); for (plane, (a, b)) in [("Y", (&p.y, &r.y)), ("Cb", (&p.cb, &r.cb)), ("Cr", (&p.cr, &r.cr))] { @@ -101,6 +108,7 @@ fn intra_only_decodes_to_the_reconstruction() { fn long_p_gop_does_not_drift() { let mut cfg = EncoderConfig::new(96, 64, 25, 1); cfg.gop_size = 30; + cfg.b_pictures = 0; let packets = assert_decodes_to_recon("long gop", cfg, 30); assert_eq!(packets.iter().filter(|p| p.keyframe).count(), 1); assert!(packets[1..].iter().all(|p| p.picture_type == PictureType::P)); @@ -127,7 +135,201 @@ fn every_coding_option_decodes_to_the_reconstruction() { ("422 odd size", EncoderConfig { width: 70, height: 30, chroma: ChromaFormat::Yuv422, ..base.clone() }), ]; for (name, cfg) in cases { - assert_decodes_to_recon(name, cfg, 8); + assert_decodes_to_recon(name, cfg.clone(), 8); + assert_decodes_to_recon(name, EncoderConfig { b_pictures: 0, ..cfg }, 8); + } +} + +#[test] +fn b_pictures_decode_to_the_reconstruction() { + let base = EncoderConfig::new(96, 64, 25, 1); + for b in 1..=4 { + for closed in [true, false] { + for (gop, frames) in [(12, 30), (7, 17), (2, 6), (1, 4), (15, 16)] { + let name = format!("b {b} closed {closed} gop {gop} frames {frames}"); + let cfg = EncoderConfig { b_pictures: b, closed_gop: closed, gop_size: gop, ..base.clone() }; + let packets = assert_decodes_to_recon(&name, cfg, frames); + if gop > 1 { + assert!(packets.iter().any(|p| p.picture_type == PictureType::B), "{name}: no B pictures"); + } + } + } + } + let cases = [ + ("422", EncoderConfig { chroma: ChromaFormat::Yuv422, ..base.clone() }), + ("abr", EncoderConfig { rate: RateControl::Abr { kbps: 400 }, ..base.clone() }), + ("odd size", EncoderConfig { width: 50, height: 34, ..base.clone() }), + ("small range", EncoderConfig { search_range: 2, ..base.clone() }), + ("linear coarse", EncoderConfig { nonlinear_quant: false, rate: RateControl::Quantiser(25), ..base.clone() }), + ]; + for (name, cfg) in cases { + assert_decodes_to_recon(name, cfg, 14); + } +} + +#[test] +fn pictures_are_reordered_into_decoding_order() { + let cfg = EncoderConfig { gop_size: 12, b_pictures: 2, ..EncoderConfig::new(64, 48, 25, 1) }; + let (_, _, packets) = encode(cfg, 15); + let order: Vec<(PictureType, i64)> = packets.iter().map(|p| (p.picture_type, p.pts)).collect(); + use PictureType::{B, I, P}; + #[rustfmt::skip] + let want = [(I, 0), (P, 3), (B, 1), (B, 2), (P, 6), (B, 4), (B, 5), (P, 9), (B, 7), (B, 8), + // B10 and B11 lead the second GOP; at the end the last held picture becomes a P picture + (I, 12), (B, 10), (B, 11), (P, 14), (B, 13)]; + assert_eq!(order, want); + // decoding times: the presentation times in order, one interval early + let dts: Vec<i64> = packets.iter().map(|p| p.dts).collect(); + assert_eq!(dts, (-1..14).collect::<Vec<_>>()); + // temporal_reference counts display order from each GOP's first picture + let pics = decode(&packets); + let tr: Vec<u16> = pics.iter().map(|p| p.temporal_reference).collect(); + assert_eq!(tr, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]); +} + +#[test] +fn a_closed_gop_decodes_on_its_own() { + for closed in [true, false] { + let cfg = EncoderConfig { gop_size: 6, b_pictures: 2, closed_gop: closed, ..EncoderConfig::new(64, 48, 25, 1) }; + let (_, recon, packets) = encode(cfg, 12); + // start decoding at the second GOP's I picture (display 6): B4 and B5 lead it + let at = packets.iter().position(|p| p.pts == 6).unwrap(); + assert!(packets[at].keyframe); + let mut d = Decoder::new(); + let mut pics = Vec::new(); + for p in &packets[at..] { + pics.extend(d.decode(&p.data, p.pts).unwrap()); + } + pics.extend(d.flush()); + let shown: Vec<i64> = pics.iter().map(|p| p.pts).collect(); + if closed { + assert_eq!(shown, (4..12).collect::<Vec<_>>()); + for p in &pics { + assert_eq!(p.y, recon[p.pts as usize].y, "closed GOP: picture {}", p.pts); + } + } else { + // the leading B pictures need the previous GOP's last P picture + assert_eq!(shown, (6..12).collect::<Vec<_>>()); + } + } +} + +#[test] +fn b_pictures_are_smaller_than_p_pictures() { + let cfg = EncoderConfig { gop_size: 12, b_pictures: 2, ..EncoderConfig::new(128, 96, 25, 1) }; + let (_, _, packets) = encode(cfg, 12); + let avg = |t: PictureType| { + let s: Vec<usize> = packets.iter().filter(|p| p.picture_type == t).map(|p| p.data.len()).collect(); + s.iter().sum::<usize>() as f64 / s.len().max(1) as f64 + }; + let (p, b) = (avg(PictureType::P), avg(PictureType::B)); + assert!(b * 1.5 < p, "P {p:.0} bytes, B {b:.0} bytes"); + // static content: the B pictures skip every macroblock but the first and last of a slice + let mut enc = Encoder::new(EncoderConfig { gop_size: 12, b_pictures: 2, ..EncoderConfig::new(128, 64, 25, 1) }).unwrap(); + let (y, cb, cr) = scene(128, 64, 64, 32, 0); + let f = YuvFrame { y: &y, cb: &cb, cr: &cr, y_stride: 128, c_stride: 64 }; + let mut packets = Vec::new(); + for t in 0..7 { + packets.extend(enc.encode(&f, t).unwrap()); + } + let i = packets[0].data.len(); + let bs: Vec<&Packet> = packets.iter().filter(|p| p.picture_type == PictureType::B).collect(); + assert_eq!(bs.len(), 4); + for p in bs { + // a picture header, four slice headers and eight edge macroblocks + assert!(p.data.len() < 64, "static B picture {} of {} bytes (I {i})", p.pts, p.data.len()); + } +} + +#[test] +fn presentation_times_must_step_evenly_with_b_pictures() { + let mut enc = Encoder::new(EncoderConfig::new(32, 32, 25, 1)).unwrap(); + let (y, c) = (vec![0u8; 32 * 32], vec![0u8; 16 * 16]); + let f = YuvFrame { y: &y, cb: &c, cr: &c, y_stride: 32, c_stride: 16 }; + // the I picture waits for the second time, which sets the step + assert!(enc.encode(&f, 10).unwrap().is_empty()); + let mut packets = enc.encode(&f, 12).unwrap(); + for bad in [12, 11, 15] { + assert!(matches!(enc.encode(&f, bad), Err(EncodeError::BadTimestamp(_))), "{bad}"); + } + packets.extend(enc.encode(&f, 14).unwrap()); + packets.extend(enc.flush()); + assert_eq!(packets.iter().map(|p| (p.pts, p.dts)).collect::<Vec<_>>(), [(10, 8), (14, 10), (12, 12)]); + // without B pictures any increasing (or not) times pass through + let mut enc = Encoder::new(EncoderConfig { b_pictures: 0, ..EncoderConfig::new(32, 32, 25, 1) }).unwrap(); + for pts in [5, 3, 9] { + let p = enc.encode(&f, pts).unwrap().remove(0); + assert_eq!((p.pts, p.dts), (pts, pts)); + } +} + +#[test] +fn decoding_times_increase_after_a_lone_picture_is_flushed() { + let mut enc = Encoder::new(EncoderConfig::new(32, 32, 25, 1)).unwrap(); + let (y, c) = (vec![0u8; 32 * 32], vec![0u8; 16 * 16]); + let f = YuvFrame { y: &y, cb: &c, cr: &c, y_stride: 32, c_stride: 16 }; + // one picture, flushed before a second sets the step: it decodes one unit early + assert!(enc.encode(&f, 100).unwrap().is_empty()); + let mut packets = enc.flush(); + assert_eq!(packets.iter().map(|p| (p.pts, p.dts)).collect::<Vec<_>>(), [(100, 99)]); + // encoding goes on: the next picture decodes at the first one's presentation time + for pts in [105, 110] { + packets.extend(enc.encode(&f, pts).unwrap()); + } + packets.extend(enc.flush()); + assert_eq!(packets.iter().map(|p| (p.pts, p.dts)).collect::<Vec<_>>(), [(100, 99), (105, 100), (110, 105)]); + assert!(packets[1].keyframe); +} + +#[test] +fn presentation_times_without_a_decoding_time_are_refused() { + let (y, c) = (vec![0u8; 32 * 32], vec![0u8; 16 * 16]); + let f = YuvFrame { y: &y, cb: &c, cr: &c, y_stride: 32, c_stride: 16 }; + // the decoding times are one step earlier: they must fit in an i64 + for (first, second) in [(i64::MIN + 1, i64::MIN + 3), (i64::MIN + 5, i64::MIN + 20)] { + let mut enc = Encoder::new(EncoderConfig::new(32, 32, 25, 1)).unwrap(); + assert!(matches!(enc.encode(&f, i64::MIN), Err(EncodeError::BadTimestamp(_)))); + assert!(enc.encode(&f, first).unwrap().is_empty()); + assert!(matches!(enc.encode(&f, second), Err(EncodeError::BadTimestamp(_))), "{second} after {first}"); + // a refused time leaves the encoder usable + assert_eq!(enc.flush().iter().map(|p| (p.pts, p.dts)).collect::<Vec<_>>(), [(first, first - 1)]); + } + // the lowest times that have one + let mut enc = Encoder::new(EncoderConfig::new(32, 32, 25, 1)).unwrap(); + let mut packets = enc.encode(&f, i64::MIN + 1).unwrap(); + packets.extend(enc.encode(&f, i64::MIN + 2).unwrap()); + packets.extend(enc.flush()); + assert_eq!(packets.iter().map(|p| p.dts).collect::<Vec<_>>(), [i64::MIN, i64::MIN + 1]); + // without B pictures every time passes through + let mut enc = Encoder::new(EncoderConfig { b_pictures: 0, ..EncoderConfig::new(32, 32, 25, 1) }).unwrap(); + assert_eq!(enc.encode(&f, i64::MIN).unwrap()[0].dts, i64::MIN); +} + +/// Average bitrate (bit/s) of the scene coded in groups of `group` pictures, flushed after each. +fn flushed_bitrate(cfg: EncoderConfig, group: usize, groups: usize) -> f64 { + let (w, h) = (cfg.width as usize, cfg.height as usize); + let fps = f64::from(cfg.fps_num) / f64::from(cfg.fps_den); + let mut enc = Encoder::new(cfg).unwrap(); + let mut bytes = 0; + for t in 0..group * groups { + let (y, cb, cr) = scene(w, h, w / 2, h / 2, t); + let f = YuvFrame { y: &y, cb: &cb, cr: &cr, y_stride: w, c_stride: w / 2 }; + bytes += enc.encode(&f, t as i64).unwrap().iter().map(|p| p.data.len()).sum::<usize>(); + if (t + 1) % group == 0 { + bytes += enc.flush().iter().map(|p| p.data.len()).sum::<usize>(); + } + } + bytes as f64 * 8.0 * fps / (group * groups) as f64 +} + +#[test] +fn flushing_short_gops_keeps_the_average_bitrate() { + // every flush ends a GOP of 12 after 4 pictures: the 8 that never came must not leave their + // bits to the next GOP + for b in [0, 2] { + let cfg = EncoderConfig { gop_size: 12, b_pictures: b, rate: RateControl::Abr { kbps: 600 }, ..EncoderConfig::new(176, 144, 25, 1) }; + let got = flushed_bitrate(cfg, 4, 15); + assert!((got / 600e3 - 1.0).abs() < 0.15, "b {b}: {got:.0} bit/s for 600000"); } } @@ -161,7 +363,7 @@ fn quality_follows_the_quantiser() { #[test] fn p_pictures_are_smaller_and_static_content_skips() { - let cfg = EncoderConfig { gop_size: 8, ..EncoderConfig::new(128, 64, 25, 1) }; + let cfg = EncoderConfig { gop_size: 8, b_pictures: 0, ..EncoderConfig::new(128, 64, 25, 1) }; let mut enc = Encoder::new(cfg).unwrap(); let (y, cb, cr) = scene(128, 64, 64, 32, 0); let f = YuvFrame { y: &y, cb: &cb, cr: &cr, y_stride: 128, c_stride: 64 }; @@ -191,7 +393,7 @@ fn the_sequence_header_describes_the_stream() { let enc = Encoder::new(cfg).unwrap(); assert_eq!(enc.profile_and_level(), pli, "{name}"); let info = probe(enc.sequence_header()).unwrap(); - assert_eq!((info.width, info.height, info.mpeg2, info.progressive_sequence, info.low_delay), (w, h, true, true, true)); + assert_eq!((info.width, info.height, info.mpeg2, info.progressive_sequence, info.low_delay), (w, h, true, true, false)); assert_eq!(info.codec_name(), format!("MPEG-2 Video ({name})")); assert_eq!(aspect, AspectRatio::Square); assert_eq!(info.sar, (1, 1)); @@ -199,6 +401,9 @@ fn the_sequence_header_describes_the_stream() { let enc = Encoder::new(EncoderConfig { aspect: AspectRatio::Dar16x9, ..EncoderConfig::new(720, 576, 30000, 1001) }).unwrap(); let info = probe(enc.sequence_header()).unwrap(); assert_eq!((info.dar, info.frame_rate), (Some((16, 9)), Some((30000, 1001)))); + // without B pictures the stream is low delay + let enc = Encoder::new(EncoderConfig { b_pictures: 0, ..EncoderConfig::new(720, 576, 25, 1) }).unwrap(); + assert!(probe(enc.sequence_header()).unwrap().low_delay); } #[test] @@ -214,6 +419,8 @@ fn bad_configurations_are_refused() { EncoderConfig { fps_den: 0, ..ok.clone() }, EncoderConfig { gop_size: 0, ..ok.clone() }, EncoderConfig { gop_size: 1024, ..ok.clone() }, + EncoderConfig { b_pictures: 5, ..ok.clone() }, + EncoderConfig { gop_size: 1023, b_pictures: 2, ..ok.clone() }, EncoderConfig { rate: RateControl::Quantiser(0), ..ok.clone() }, EncoderConfig { rate: RateControl::Quantiser(32), ..ok.clone() }, EncoderConfig { rate: RateControl::Abr { kbps: 0 }, ..ok.clone() }, @@ -231,7 +438,7 @@ fn bad_configurations_are_refused() { #[test] fn short_or_inconsistent_planes_are_refused() { - let mut enc = Encoder::new(EncoderConfig::new(32, 32, 25, 1)).unwrap(); + let mut enc = Encoder::new(EncoderConfig { b_pictures: 0, ..EncoderConfig::new(32, 32, 25, 1) }).unwrap(); let (y, c) = (vec![0u8; 32 * 32], vec![0u8; 16 * 16]); let ok = YuvFrame { y: &y, cb: &c, cr: &c, y_stride: 32, c_stride: 16 }; assert!(enc.encode(&ok, 0).is_ok()); diff --git a/crates/video/src/mpeg2/mod.rs b/crates/video/src/mpeg2/mod.rs index ae2bb1682..4fd59dced 100644 --- a/crates/video/src/mpeg2/mod.rs +++ b/crates/video/src/mpeg2/mod.rs @@ -1,5 +1,5 @@ //! Clean-room MPEG-2 video (ITU-T H.262 | ISO/IEC 13818-2) and MPEG-1 video (ISO/IEC 11172-2) -//! decoder, and the start of an MPEG-2 encoder ([`encode`], feature `mpeg2-encode`: I and P +//! decoder, and the start of an MPEG-2 encoder ([`encode`], feature `mpeg2-encode`: I, P and B //! pictures). //! //! - Main Profile at Low/Main/High-1440/High Level, 4:2:2 Profile (XDCAM HD422, IMX / D-10), diff --git a/crates/video/tests/h264_encode/pinned_decisions.rs b/crates/video/tests/h264_encode/pinned_decisions.rs index cccb6dac7..c547b54ff 100644 --- a/crates/video/tests/h264_encode/pinned_decisions.rs +++ b/crates/video/tests/h264_encode/pinned_decisions.rs @@ -7,8 +7,12 @@ use craft_video::h264::*; /// FNV-1a over the slice NAL units of `n` frames of [`synth`] encoded with `c`. fn slices_hash(c: EncoderConfig, n: usize) -> u64 { + slices_hash_with_starts(c, n, MotionSearchStarts::Extended) +} + +fn slices_hash_with_starts(c: EncoderConfig, n: usize, starts: MotionSearchStarts) -> u64 { let (w, h) = (c.width as usize, c.height as usize); - let mut enc = Encoder::new(c).unwrap(); + let mut enc = Encoder::new_with_motion_search_starts(c, starts).unwrap(); let mut stream = Vec::new(); for t in 0..n { let f = synth(w, h, t); @@ -61,3 +65,27 @@ fn coded_slices_are_pinned() { assert_eq!(*got, *want, "{name}: the coded slices changed"); } } + +#[test] +fn filmcraft_writer_keeps_shared_search_decisions_pinned() { + let cases = [ + ("high balanced crf", cfg(Profile::High, Preset::Balanced, RateControl::Crf(23.0)), 0x6223_db82_41eb_7da1u64), + ("high quality vbr", cfg(Profile::High, Preset::Quality, RateControl::Vbr { target_kbps: 800, max_kbps: 1200 }), 0x721d_6e68_3f96_5bf1), + ("main speed qp", cfg(Profile::Main, Preset::Speed, RateControl::Qp(30)), 0x7772_91d5_4c75_c320), + ("baseline balanced cbr", cfg(Profile::Baseline, Preset::Balanced, RateControl::Cbr { kbps: 600 }), 0x72ff_5e78_a3f0_e46e), + ]; + let got: Vec<u64> = cases + .iter() + .map(|(_, c, _)| { + let mut c = c.clone(); + c.writer = "filmcraft-h264enc 0.20.1".into(); + slices_hash_with_starts(c, 20, MotionSearchStarts::SeedAndNeighbour) + }) + .collect(); + for ((name, _, _), got) in cases.iter().zip(&got) { + eprintln!("FilmCraft {name}: {got:#018x}"); + } + for ((name, _, want), got) in cases.iter().zip(&got) { + assert_eq!(*got, *want, "{name}: FilmCraft's coded slices changed"); + } +} diff --git a/crates/video/tests/mpeg2/encode.rs b/crates/video/tests/mpeg2/encode.rs index 5cb2377dc..122fe2d71 100644 --- a/crates/video/tests/mpeg2/encode.rs +++ b/crates/video/tests/mpeg2/encode.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -use craft_video::mpeg2::{ChromaFormat, Encoder, EncoderConfig, RateControl, ReconFrame, YuvFrame}; +use craft_video::mpeg2::{ChromaFormat, Encoder, EncoderConfig, Packet, RateControl, ReconFrame, YuvFrame}; use crate::common::{Stats, fixture_dir, pix_fmt_of}; use crate::oracle::{MAX_DIFFERING, MIN_PSNR, TOL_MAX}; @@ -39,24 +39,22 @@ fn sizes(cfg: &EncoderConfig) -> (usize, usize, usize) { (w * h, w / 2 * ch, w / 2) } -/// Encode `raw` frames; returns the elementary stream and the reconstruction. -fn encode(cfg: &EncoderConfig, raw: &[u8]) -> (Vec<u8>, Vec<ReconFrame>) { +/// Encode `raw` frames; returns the elementary stream, the reconstruction (display order) and +/// the packets (decoding order). +fn encode(cfg: &EncoderConfig, raw: &[u8]) -> (Vec<u8>, Vec<ReconFrame>, Vec<Packet>) { let (ys, cs, cw) = sizes(cfg); let fsize = ys + 2 * cs; let mut enc = Encoder::new(cfg.clone()).expect("config"); enc.set_recon_capture(true); - let mut es = Vec::new(); + let mut packets = Vec::new(); for (i, f) in raw.chunks_exact(fsize).enumerate() { let frame = YuvFrame { y: &f[..ys], cb: &f[ys..ys + cs], cr: &f[ys + cs..], y_stride: cfg.width as usize, c_stride: cw }; - for p in enc.encode(&frame, i as i64).expect("encode") { - es.extend_from_slice(&p.data); - } - } - for p in enc.flush() { - es.extend_from_slice(&p.data); + packets.extend(enc.encode(&frame, i as i64).expect("encode")); } + packets.extend(enc.flush()); + let mut es: Vec<u8> = packets.iter().flat_map(|p| p.data.iter().copied()).collect(); es.extend_from_slice(enc.end_of_sequence()); - (es, enc.take_recon()) + (es, enc.take_recon(), packets) } /// ffmpeg's decode of `file`, failing on any decoding error. @@ -121,10 +119,11 @@ fn check(ff: &Path, c: &Case) -> (Vec<u8>, f64) { let raw = source(ff, c.cfg.width, c.cfg.height, c.frames, pix_fmt); let (ys, cs, _) = sizes(&c.cfg); let fsize = ys + 2 * cs; - let (es, recon) = encode(&c.cfg, &raw); + let (es, recon, packets) = encode(&c.cfg, &raw); let path = write(c.name, &es); let decoded = ffmpeg_decode(ff, &path, pix_fmt); assert_eq!(decoded.len(), c.frames * fsize, "{}: ffmpeg's frame count", c.name); + assert_eq!(recon.len(), c.frames, "{}: reconstruction count", c.name); let mut all = Stats::default(); for (i, (r, f)) in recon.iter().zip(decoded.chunks_exact(fsize)).enumerate() { let mut s = Stats::default(); @@ -139,15 +138,21 @@ fn check(ff: &Path, c: &Case) -> (Vec<u8>, f64) { assert!(quality >= c.min_psnr, "{}: luma PSNR {quality:.2} dB against the source", c.name); if let Some((stream, types)) = ffprobe(&path) { assert_eq!(stream, c.probe, "{}: ffprobe", c.name); - let gop = c.cfg.gop_size as usize; - let want: Vec<&str> = (0..c.frames).map(|i| if i % gop == 0 { "I" } else { "P" }).collect(); + // ffprobe lists the pictures in display order + let mut shown: Vec<&Packet> = packets.iter().collect(); + shown.sort_by_key(|p| p.pts); + let want: Vec<String> = shown.iter().map(|p| format!("{:?}", p.picture_type)).collect(); assert_eq!(types, want, "{}: picture types", c.name); } + let count = |t: &str| packets.iter().filter(|p| format!("{:?}", p.picture_type) == t).count(); let kbps = es.len() as f64 * 8.0 * 25.0 / c.frames as f64 / 1000.0; println!( - "{}: {} frames, {kbps:.0} kbit/s, luma PSNR {quality:.2} dB, max diff to ffmpeg {}, {:.3}% differ", + "{}: {} frames ({} I, {} P, {} B), {kbps:.0} kbit/s, luma PSNR {quality:.2} dB, max diff to ffmpeg {}, {:.3}% differ", c.name, c.frames, + count("I"), + count("P"), + count("B"), all.max, 100.0 * all.diff as f64 / all.n as f64 ); @@ -160,6 +165,21 @@ fn ffmpeg_decodes_our_streams() { let cif = EncoderConfig { gop_size: 12, ..EncoderConfig::new(352, 288, 25, 1) }; let cases = [ Case { name: "cif_q4", cfg: cif.clone(), frames: 25, probe: "mpeg2video,Main,10,yuv420p", min_psnr: 36.0 }, + Case { name: "cif_ip", cfg: EncoderConfig { b_pictures: 0, ..cif.clone() }, frames: 25, probe: "mpeg2video,Main,10,yuv420p", min_psnr: 36.0 }, + Case { + name: "cif_open_gop", + cfg: EncoderConfig { closed_gop: false, gop_size: 15, ..cif.clone() }, + frames: 31, + probe: "mpeg2video,Main,10,yuv420p", + min_psnr: 35.0, + }, + Case { + name: "cif_b4", + cfg: EncoderConfig { b_pictures: 4, gop_size: 10, ..cif.clone() }, + frames: 23, + probe: "mpeg2video,Main,10,yuv420p", + min_psnr: 34.0, + }, Case { name: "cif_intra", cfg: EncoderConfig { gop_size: 1, rate: RateControl::Quantiser(8), ..cif.clone() }, @@ -191,10 +211,14 @@ fn ffmpeg_decodes_our_streams() { #[test] fn average_bitrate_reaches_its_target() { let Some(ff) = craft_media_testkit::ffmpeg_or_skip("mpeg2 encoder bitrate") else { return }; - for kbps in [800u32, 2500] { + for (kbps, b) in [(800u32, 2), (2500, 2), (800, 0)] { let c = Case { - name: if kbps == 800 { "cif_abr_800" } else { "cif_abr_2500" }, - cfg: EncoderConfig { rate: RateControl::Abr { kbps }, gop_size: 12, ..EncoderConfig::new(352, 288, 25, 1) }, + name: match (kbps, b) { + (800, 0) => "cif_abr_800_ip", + (800, _) => "cif_abr_800", + _ => "cif_abr_2500", + }, + cfg: EncoderConfig { rate: RateControl::Abr { kbps }, gop_size: 12, b_pictures: b, ..EncoderConfig::new(352, 288, 25, 1) }, frames: 72, probe: "mpeg2video,Main,10,yuv420p", min_psnr: 26.0, diff --git a/crates/webp/src/anim.rs b/crates/webp/src/anim.rs index 3c6df1a64..7d63c75b7 100644 --- a/crates/webp/src/anim.rs +++ b/crates/webp/src/anim.rs @@ -56,48 +56,8 @@ pub fn animation(width: u32, height: u32, frames: &[AnimFrame], opts: &AnimOptio if frames.is_empty() { return Err(Error::Encode("an animation needs a frame")); } - let mut anmf = Vec::new(); - let mut any_alpha = opts.alpha; - for f in frames { - if f.width == 0 || f.height == 0 || f.x % 2 != 0 || f.y % 2 != 0 { - return Err(Error::Encode("a frame is empty or not at an even position")); - } - if f.x.checked_add(f.width).is_none_or(|r| r > width) || f.y.checked_add(f.height).is_none_or(|b| b > height) { - return Err(Error::Encode("a frame reaches past the canvas")); - } - if f.duration_ms >= 1 << 24 { - return Err(Error::Encode("a frame duration is 2^24 ms or more")); - } - let mut body = Vec::new(); - u24(&mut body, f.x / 2); - u24(&mut body, f.y / 2); - u24(&mut body, f.width - 1); - u24(&mut body, f.height - 1); - u24(&mut body, f.duration_ms); - // Bit 1: do not blend; bit 0: dispose to the background. - body.push(u8::from(!f.blend) << 1 | u8::from(f.dispose_to_background)); - match f.payload { - Payload::Lossy { vp8, alpha } => { - if f.width > MAX_VP8_DIMENSION || f.height > MAX_VP8_DIMENSION { - return Err(Error::Encode("a lossy frame is at most 16383 pixels a side")); - } - if let Some(a) = alpha { - if a.len() as u64 != u64::from(f.width) * u64::from(f.height) { - return Err(Error::Encode("an alpha plane does not match its frame")); - } - any_alpha = true; - let mut alph = Vec::with_capacity(a.len() + 1); - // Header byte: no pre-processing, no filtering, no compression. - alph.push(0); - alph.extend_from_slice(a); - chunk(&mut body, b"ALPH", &alph)?; - } - chunk(&mut body, b"VP8 ", vp8)?; - } - Payload::Lossless { vp8l } => chunk(&mut body, b"VP8L", vp8l)?, - } - chunk(&mut anmf, b"ANMF", &body)?; - } + // Determine the header flag before writing, without retaining another full animation. + let any_alpha = opts.alpha || frames.iter().any(|f| matches!(f.payload, Payload::Lossy { alpha: Some(_), .. })); let mut body = b"WEBP".to_vec(); let flags = [(opts.icc.is_some(), 0x20u8), (any_alpha, 0x10), (opts.exif.is_some(), 0x08), (opts.xmp.is_some(), 0x04), (true, 0x02)] .iter() @@ -113,7 +73,46 @@ pub fn animation(width: u32, height: u32, frames: &[AnimFrame], opts: &AnimOptio let mut anim = opts.background_bgra.to_vec(); anim.extend_from_slice(&opts.loop_count.to_le_bytes()); chunk(&mut body, b"ANIM", &anim)?; - body.extend_from_slice(&anmf); + + for f in frames { + if f.width == 0 || f.height == 0 || f.x % 2 != 0 || f.y % 2 != 0 { + return Err(Error::Encode("a frame is empty or not at an even position")); + } + if f.x.checked_add(f.width).is_none_or(|r| r > width) || f.y.checked_add(f.height).is_none_or(|b| b > height) { + return Err(Error::Encode("a frame reaches past the canvas")); + } + if f.duration_ms >= 1 << 24 { + return Err(Error::Encode("a frame duration is 2^24 ms or more")); + } + let mut frame_body = Vec::new(); + u24(&mut frame_body, f.x / 2); + u24(&mut frame_body, f.y / 2); + u24(&mut frame_body, f.width - 1); + u24(&mut frame_body, f.height - 1); + u24(&mut frame_body, f.duration_ms); + // Bit 1: do not blend; bit 0: dispose to the background. + frame_body.push(u8::from(!f.blend) << 1 | u8::from(f.dispose_to_background)); + match f.payload { + Payload::Lossy { vp8, alpha } => { + if f.width > MAX_VP8_DIMENSION || f.height > MAX_VP8_DIMENSION { + return Err(Error::Encode("a lossy frame is at most 16383 pixels a side")); + } + if let Some(a) = alpha { + if a.len() as u64 != u64::from(f.width) * u64::from(f.height) { + return Err(Error::Encode("an alpha plane does not match its frame")); + } + let mut alph = Vec::with_capacity(a.len() + 1); + // Header byte: no pre-processing, no filtering, no compression. + alph.push(0); + alph.extend_from_slice(a); + chunk(&mut frame_body, b"ALPH", &alph)?; + } + chunk(&mut frame_body, b"VP8 ", vp8)?; + } + Payload::Lossless { vp8l } => chunk(&mut frame_body, b"VP8L", vp8l)?, + } + chunk(&mut body, b"ANMF", &frame_body)?; + } if let Some(exif) = opts.exif { chunk(&mut body, b"EXIF", exif)?; } @@ -231,6 +230,23 @@ mod tests { assert_eq!(&file[anim + 8..anim + 14], &[1, 2, 3, 4, 0, 0]); } + #[test] + fn lossy_container_keeps_alpha_payload_padding_and_xmp() { + // Container-only fixture: the writer must not reinterpret an encoder's VP8 bytes. + let vp8 = [11, 22, 33]; + let alpha = [128]; + let f = frame(Payload::Lossy { vp8: &vp8, alpha: Some(&alpha) }, 0, 0, 1, 1, 17); + let file = animation(1, 1, &[f], &AnimOptions { xmp: Some(b"xmp"), ..Default::default() }).unwrap(); + let info = scan(&file, 10).unwrap(); + assert!(info.alpha && info.complete); + assert_eq!(info.frames[0].duration_ms, 17); + let at = file.windows(4).position(|c| c == b"ANMF").unwrap(); + let payload = at + 8 + 16; + assert_eq!(&file[payload..payload + 10], &[b'A', b'L', b'P', b'H', 2, 0, 0, 0, 0, 128]); + assert_eq!(&file[payload + 10..payload + 22], &[b'V', b'P', b'8', b' ', 3, 0, 0, 0, 11, 22, 33, 0]); + assert_eq!(&file[file.len() - 12..], &[b'X', b'M', b'P', b' ', 3, 0, 0, 0, b'x', b'm', b'p', 0]); + } + #[test] fn what_does_not_fit_is_refused() { let px = vp8l(2, 2, [0; 4]); diff --git a/crates/webp/src/frames.rs b/crates/webp/src/frames.rs index 8fa89962b..e97118482 100644 --- a/crates/webp/src/frames.rs +++ b/crates/webp/src/frames.rs @@ -24,7 +24,9 @@ pub struct FrameLimits { pub max_frames: usize, /// Most bytes of kept pictures (4 bytes a pixel each). Default 1 GiB. pub max_bytes: u64, - /// Largest canvas (logical screen) in bytes at 4 bytes a pixel. Default 512 MiB. + /// Largest canvas (logical screen) in bytes at 4 bytes a pixel. Default 512 MiB. This is a + /// pre-decode canvas check; image 0.25.10's WebP decoder does not enforce its working-buffer + /// allocations through the `ImageDecoder::set_limits` hook. pub max_canvas_bytes: u64, /// Merge a frame identical to the one before into it (its delay added). Default off. pub merge_identical: bool, @@ -98,10 +100,7 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result<Animation, Fram return Err(FrameError::LimitExceeded(format!("a {}x{} canvas is over {} bytes", info.width, info.height, limits.max_canvas_bytes))); } let malformed = |e: image::ImageError| FrameError::Malformed(e.to_string()); - let mut decoder = WebPDecoder::new(Cursor::new(bytes)).map_err(malformed)?; - let mut il = image::Limits::default(); - il.max_alloc = Some(limits.max_canvas_bytes.saturating_mul(2)); - decoder.set_limits(il).map_err(malformed)?; + let decoder = WebPDecoder::new(Cursor::new(bytes)).map_err(malformed)?; let (width, height) = decoder.dimensions(); if !decoder.has_animation() { let mut rgba = vec![0u8; usize::try_from(canvas).map_err(|_| FrameError::LimitExceeded("canvas".into()))?]; diff --git a/crates/webp/src/lib.rs b/crates/webp/src/lib.rs index 82f0a2003..a24dfc656 100644 --- a/crates/webp/src/lib.rs +++ b/crates/webp/src/lib.rs @@ -17,6 +17,7 @@ //! Input is treated as hostile: every read is bounds-checked, chunk sizes are checked against the //! file, and the number of frames recorded is capped by the caller. +pub mod anim; #[cfg(feature = "frames")] pub mod frames; #[cfg(test)] diff --git a/crates/webp/tests/animation_public.rs b/crates/webp/tests/animation_public.rs new file mode 100644 index 000000000..9106f1a79 --- /dev/null +++ b/crates/webp/tests/animation_public.rs @@ -0,0 +1,6 @@ +//! Guard the public module wiring: the implementation must be usable by consumers. +#[test] +fn public_animation_api_refuses_empty_movies() { + let result = craft_webp::anim::animation(1, 1, &[], &craft_webp::anim::AnimOptions::default()); + assert!(result.is_err()); +} diff --git a/crates/wordmodel/src/numbering.rs b/crates/wordmodel/src/numbering.rs index 5ab94ea87..91eb221b8 100644 --- a/crates/wordmodel/src/numbering.rs +++ b/crates/wordmodel/src/numbering.rs @@ -70,12 +70,18 @@ impl Default for Level { } } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[derive(Clone, Debug, Serialize, Deserialize, Default)] #[serde(default)] pub struct AbstractNum { pub id: u32, pub name: Option<String>, pub levels: Vec<Level>, + /// Which levels were defined in the source file. `None` is used by model-created definitions, + /// where the populated `levels` vector is authoritative. DOCX readers set this when they fill + /// unspecified Word levels with their effective defaults. This reader-only provenance is not + /// serialized as part of the document model. + #[serde(skip)] + pub explicit_levels: Option<[bool; 9]>, /// Word's list identity (`w:nsid`, 8 hex digits), which it uses to match lists across /// documents (paste, compare); kept from the file. #[serde(skip_serializing_if = "Option::is_none")] @@ -89,6 +95,20 @@ pub struct AbstractNum { pub multi_level_type: Option<String>, } +// Explicit source-level presence is reader provenance used to distinguish an omitted Word level +// from an effective default. It is intentionally not part of the document model's structural +// equality, just as it is not serialized. +impl PartialEq for AbstractNum { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + && self.name == other.name + && self.levels == other.levels + && self.nsid == other.nsid + && self.tmpl == other.tmpl + && self.multi_level_type == other.multi_level_type + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] #[serde(default, rename_all = "camelCase")] pub struct Num { @@ -236,6 +256,20 @@ impl Numbering { } self.abstract_of(num)?.levels.get(level as usize) } + /// Whether the source definition supplied this level, or a per-numbering override defines it. + /// + /// [`Self::level`] also exposes Word's effective default for omitted levels. This method lets + /// importers preserve formats whose historical behavior distinguishes an explicit level from + /// that effective fallback. Older serialized and model-created definitions have no source + /// presence metadata, so their populated levels count as defined. + pub fn level_is_defined(&self, num: u32, level: u8) -> bool { + let Some(n) = self.num(num) else { return false }; + if n.level_overrides.iter().any(|(i, _)| *i == level) { + return true; + } + let Some(a) = self.abstract_of(num) else { return false }; + a.explicit_levels.map_or_else(|| a.levels.get(level as usize).is_some(), |levels| levels.get(level as usize).copied().unwrap_or(false)) + } /// Create a new list of `kind`; returns the `num` id. List ids run out only past `u32::MAX` /// lists, more than memory holds; then nothing is added and the id is 0, "no list". pub fn add_list(&mut self, kind: ListKind) -> u32 { @@ -485,6 +519,42 @@ const MAX_LABEL_BYTES: usize = 256; mod tests { use super::*; + #[test] + fn explicit_level_metadata_preserves_effective_defaults_and_old_models() { + let mut numbering = Numbering::default(); + let id = numbering.add_list(ListKind::Numbered); + assert!(numbering.level_is_defined(id, 0)); + assert!(numbering.level_is_defined(id, 8)); + + let abstract_id = numbering.num(id).unwrap().abstract_id; + let mut explicit = [false; 9]; + explicit[0] = true; + numbering.abstracts.iter_mut().find(|a| a.id == abstract_id).unwrap().explicit_levels = Some(explicit); + + // Effective Word defaults remain available to existing model callers, while importers can + // tell that this source file supplied only level zero. + assert!(numbering.level(id, 1).is_some()); + assert!(!numbering.level_is_defined(id, 1)); + assert!(numbering.level_is_defined(id, 0)); + + // Old serialized definitions have no presence marker; populated levels remain valid. + numbering.abstracts.iter_mut().find(|a| a.id == abstract_id).unwrap().explicit_levels = None; + assert!(numbering.level_is_defined(id, 8)); + + // A per-numbering level definition takes precedence over the abstract's missing level. + numbering.abstracts.iter_mut().find(|a| a.id == abstract_id).unwrap().explicit_levels = Some(explicit); + numbering.nums.iter_mut().find(|n| n.id == id).unwrap().level_overrides.push((1, Level::default())); + assert!(numbering.level_is_defined(id, 1)); + } + + #[test] + fn explicit_level_metadata_does_not_change_model_equality() { + let mut with_metadata = AbstractNum::default(); + let without_metadata = with_metadata.clone(); + with_metadata.explicit_levels = Some([true; 9]); + assert_eq!(with_metadata, without_metadata); + } + /// Read-only counter APIs retain the renderer's bounds and never advance a list. #[test] fn reference_labels_are_bounded_and_do_not_advance_counters() { diff --git a/crates/wordmodel/src/para.rs b/crates/wordmodel/src/para.rs index 0ed90870b..bbfeb9cbc 100644 --- a/crates/wordmodel/src/para.rs +++ b/crates/wordmodel/src/para.rs @@ -24,7 +24,7 @@ pub use inline_object::{CanvasStyle, GroupChild, InlineObject, MAX_GROUP_CHILDRE pub use run::{COLUMN_BREAK, LINE_BREAK, NB_HYPHEN, NBSP, OBJ, PAGE_BREAK, Run, SOFT_HYPHEN, next_rev}; /// A paragraph. -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Serialize, Deserialize)] pub struct Paragraph { pub text: String, pub runs: Vec<Run>, @@ -54,6 +54,19 @@ impl PartialEq for Paragraph { } } +impl std::fmt::Debug for Paragraph { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Paragraph") + .field("text", &self.text) + .field("runs", &self.runs) + .field("props", &self.props) + .field("mark", &self.mark) + .field("objects", &self.objects) + .field("section", &self.section) + .finish_non_exhaustive() + } +} + impl Default for Paragraph { fn default() -> Self { Paragraph::new() diff --git a/crates/wordmodel/src/props.rs b/crates/wordmodel/src/props.rs index 38feba083..65a59592c 100644 --- a/crates/wordmodel/src/props.rs +++ b/crates/wordmodel/src/props.rs @@ -93,6 +93,16 @@ mod tests { } } + #[test] + fn explicit_off_values_disable_underline() { + for value in ["off", "false", "0"] { + assert_eq!(Underline::from_ooxml(value), Underline::None, "{value}"); + } + assert_eq!(Underline::from_ooxml("none"), Underline::None); + assert_eq!(Underline::from_ooxml("single"), Underline::Single); + assert_eq!(Underline::from_ooxml("unknown"), Underline::Single); + } + /// The 16 `w14:ligatures` values of [MS-DOCX], each to its flags and back. #[test] fn ligature_names() { diff --git a/crates/wordmodel/src/props/char_props.rs b/crates/wordmodel/src/props/char_props.rs index 3cde0b132..db08ce2fe 100644 --- a/crates/wordmodel/src/props/char_props.rs +++ b/crates/wordmodel/src/props/char_props.rs @@ -51,6 +51,10 @@ impl Underline { } pub fn from_ooxml(s: &str) -> Underline { Underline::ALL.iter().copied().find(|u| u.ooxml() == s).unwrap_or(match s { + // Some Word producers serialize the generic on/off values here, although the + // underline simple type normally uses `none`. Honor an explicit disable rather + // than treating an unrecognized value as the default single underline. + "off" | "false" | "0" => Underline::None, "thickDash" | "dashLong" | "dashedHeavy" | "dashLongHeavy" => Underline::Dash, "dottedHeavy" => Underline::Dotted, "wavyHeavy" => Underline::Wave, diff --git a/crates/wordmodel/src/resolve.rs b/crates/wordmodel/src/resolve.rs index 40449e82c..7ef12ccdc 100644 --- a/crates/wordmodel/src/resolve.rs +++ b/crates/wordmodel/src/resolve.rs @@ -66,6 +66,11 @@ pub struct ResolvedChar { pub rtl: bool, /// The whole run uses the complex-script properties (`w:cs`). pub cs: bool, + /// The run says it is not complex script (`w:cs w:val="0"`): its Thai, Indic, Arabic or + /// Hebrew characters take its other font, size, bold and italic, as Word draws them in a run + /// that isn't complex script or right to left. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub cs_off: bool, /// Complex-script font, size, bold and italic (Arabic, Persian, Hebrew… text). pub font_cs: String, /// East Asian font (Chinese, Japanese and Korean text), when one is set. @@ -115,6 +120,7 @@ impl ResolvedChar { lang: c.lang.clone(), rtl: c.rtl.unwrap_or(false), cs: c.cs.unwrap_or(false), + cs_off: c.cs == Some(false), font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()), font_ea: c.font_ea.clone(), size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0), @@ -133,9 +139,11 @@ impl ResolvedChar { pub fn kerned(&self) -> bool { self.kern > 0.0 && self.size >= self.kern } - /// Does a character of this run use the complex-script properties? + /// Does a character of this run use the complex-script properties? Every character of a + /// right-to-left or complex-script run does; otherwise a complex-script character does, + /// unless the run says it is not complex script. pub fn uses_complex(&self, c: char) -> bool { - self.rtl || self.cs || crate::bidi::is_complex_script(c) + self.rtl || self.cs || (!self.cs_off && crate::bidi::is_complex_script(c)) } /// The size glyphs are drawn and measured at. Word sets superscript and subscript text at /// 0.65 of the run's size rounded to the half point, a font size the format can store diff --git a/crates/wordmodel/src/styles.rs b/crates/wordmodel/src/styles.rs index 090df9a05..1d725efa2 100644 --- a/crates/wordmodel/src/styles.rs +++ b/crates/wordmodel/src/styles.rs @@ -6,8 +6,8 @@ use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use crate::props::{ - Align, Border, BorderStyle, Borders, CharProps, LineSpacing, ParaProps, Rgb, TabAlign, TabLeader, TabStop, TableLook, TextColor, Underline, - VAlign, + Align, Border, BorderStyle, Borders, CharProps, LineSpacing, ParaProps, PropChange, Rgb, TabAlign, TabLeader, TabStop, TableLook, TextColor, + Underline, VAlign, }; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] @@ -52,6 +52,12 @@ pub struct Style { pub default: bool, /// Table style: conditional formatting for header row, banding etc. pub table: Option<TableStyleParts>, + /// Tracked change to the style's paragraph properties (`w:pPrChange`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub para_change: Option<Box<PropChange<ParaProps>>>, + /// Tracked change to the style's run properties (`w:rPrChange`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub chr_change: Option<Box<PropChange<CharProps>>>, } /// Table style conditional formats (shading + character formatting per region). @@ -822,6 +828,94 @@ impl StyleSheet { out.chr.style = None; Some(out) } + /// Word draws a run's text with the complex-script font, size, bold and italic only when the run + /// is complex script or right to left (`w:cs`, `w:rtl`) by its own properties, its paragraph + /// style, its table style or the run defaults; a character style saying so, or saying not, + /// doesn't count (nor does its `w:rtl` change the order of the text). Anywhere else the text takes the run's other font and `w:sz`, Thai included, + /// whatever its language or `w:hint` (measured in Word for Windows: Thai text at `w:sz` 22 pt, + /// `w:szCs` 11 pt is drawn at 22 pt), and the same in a `.doc`. WordCraft draws Thai, Lao and Indic characters with the + /// complex-script formatting unless the run says it is not complex script, and counts a character + /// style's `w:cs`; so a run it would draw otherwise says on itself whether it is complex script + /// (`w:cs`, which Word reads the same way). A reader calls this on each paragraph it has read. `table` is the run formatting the table style gives + /// the paragraph's cell. Runs with right-to-left text are left as they are: they are written + /// right to left. + pub fn mark_runs_as_word_draws_them(&self, para: &mut crate::para::Paragraph, table: Option<&CharProps>) { + use crate::bidi::{is_complex_script, is_rtl_script}; + use crate::para::{InlineObject, OBJ}; + // What each run draws: its text, a field kept as one object standing for its result + // (drawn in the run's formatting, and measured in Word to follow the same rule). + let mut drawn = Vec::with_capacity(para.runs.len()); + let (mut at, mut objects) = (0, para.objects.iter()); + for run in &para.runs { + let mut text = String::new(); + for c in para.text.get(at..at + run.len).unwrap_or("").chars() { + if c != OBJ { + text.push(c); + } else if let Some(InlineObject::Field { result, code: false, .. }) = objects.next() { + text.push_str(result); + } + } + at += run.len; + drawn.push(text); + } + let style = para.props.style.as_deref(); + for (run, text) in para.runs.iter_mut().zip(&drawn) { + if text.is_empty() || text.chars().any(is_rtl_script) { + continue; + } + let word = self.resolve_char_in(style, table, &CharProps { style: None, ..run.props.clone() }); + let mut ours = self.resolve_char_in(style, table, &run.props); + // Right to left only by its character style: Word draws and orders the run as it does + // one that says nothing (measured, Latin and Thai text). + if ours.rtl && !word.rtl { + run.props.rtl = Some(false); + ours = self.resolve_char_in(style, table, &run.props); + } + if word.cs || word.rtl { + if !ours.cs && !ours.rtl { + run.props.cs = Some(true); + } + } else if !ours.rtl && (ours.cs || (!ours.cs_off && text.chars().any(is_complex_script))) { + run.props.cs = Some(false); + } + } + } + /// The run formatting `t`'s table style gives the text of each of its cells, by row and then + /// cell: each of a cell's parts' over the last, lowest precedence first (ECMA-376 §17.7.6), as + /// layout applies it between document defaults and the paragraph's style. `None` when the + /// table has no style. The style and the table's size are worked out once for the whole table, + /// and each set of parts is put together once. + pub fn table_cells_chr(&self, t: &crate::table::Table) -> Option<Vec<Vec<CharProps>>> { + let st = self.table_style(t.props.style.as_deref()?)?; + let sizes = (st.parts.band_size.unwrap_or(0), st.parts.col_band_size.unwrap_or(0)); + let ncols = t.cols().clamp(1, crate::table::MAX_COLS); + let nrows = t.rows.len(); + let mut made: Vec<(PartSet, CharProps)> = Vec::new(); + let mut out = Vec::with_capacity(nrows); + for (r, row) in t.rows.iter().enumerate() { + let mut g = row.first_grid(); + let mut cells = Vec::with_capacity(row.cells.len()); + for cell in &row.cells { + let span = cell.span(); + let parts = PartSet::of_cell(&t.props.look, sizes, (r, nrows), (g, span, ncols)); + g = g.saturating_add(span); + let chr = match made.iter().find(|(p, _)| *p == parts) { + Some((_, chr)) => chr.clone(), + None => { + let mut chr = CharProps::default(); + for part in parts.iter() { + chr.overlay(&st.part(part).chr); + } + made.push((parts, chr.clone())); + chr + } + }; + cells.push(chr); + } + out.push(cells); + } + Some(out) + } /// Add or replace a style. pub fn upsert(&mut self, st: Style) { match self.styles.iter_mut().find(|s| s.id == st.id) { diff --git a/crates/xfl/Cargo.toml b/crates/xfl/Cargo.toml new file mode 100644 index 000000000..9c8a40e3c --- /dev/null +++ b/crates/xfl/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "craft-xfl" +description = "Bounded XFL/FLA package reader and native shape-edge parser." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-xml = { workspace = true } +miniz_oxide = "0.8" +thiserror = { workspace = true } diff --git a/crates/xfl/src/document.rs b/crates/xfl/src/document.rs new file mode 100644 index 000000000..ec749189a --- /dev/null +++ b/crates/xfl/src/document.rs @@ -0,0 +1,844 @@ +//! Neutral views of the native XFL document schema. +//! +//! This layer recognizes the document, stage, scene, layer and keyframe fields defined by XFL. +//! It does not construct a consumer's animation model. More detailed payloads remain available +//! through [`Document::root`] for the application adapter. +use crate::shape::XflElement; +use craft_xml::{Doctype, El, Error as XmlError, Limits, Local, Options, Pat, UnknownEntity}; +use std::borrow::Cow; + +/// Maximum bytes of XML in one XFL document or library item. +pub const MAX_XML_BYTES: usize = 256 * 1024 * 1024; +/// Maximum depth accepted by AniCraft's existing XFL XML adapter (root depth is one). +pub const MAX_XML_DEPTH: usize = 257; +/// Maximum XFL document elements accepted by the existing adapter. +pub const MAX_XML_ELEMENTS: usize = 4_000_000; + +/// An XFL `DOMDocument.xml` tree plus typed, zero-copy views over its native structure. +#[derive(Clone, Debug)] +pub struct Document { + root: El, +} + +/// Stage metadata stored on the root `DOMDocument` element. +#[derive(Clone, Copy, Debug)] +pub struct Stage<'a> { + pub width: Option<f32>, + pub height: Option<f32>, + pub frame_rate: Option<f32>, + pub background_color: Option<&'a str>, +} + +/// The script-language version and document class selected by an XFL `PublishSettings.xml`. +/// Values stay in their native string form so each consumer can apply its own domain rules. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PublishSettings<'a> { + pub action_script_version: Option<Cow<'a, str>>, + pub document_class: Option<Cow<'a, str>>, +} + +/// Bounds used when projecting native schema fields into a compact model. +#[derive(Clone, Copy, Debug)] +pub struct ModelLimits { + pub max_timelines: usize, + pub max_layers_per_timeline: usize, +} + +/// Compact XFL metadata that does not retain or duplicate the parsed XML tree. +#[derive(Clone, Debug, PartialEq)] +pub struct DocumentModel { + pub stage: StageModel, + pub timelines: Vec<TimelineModel>, + /// Present for a library `DOMSymbolItem`; absent for normal `DOMDocument` files. + pub symbol_timeline: Option<TimelineModel>, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct StageModel { + pub width: Option<f32>, + pub height: Option<f32>, + pub frame_rate: Option<f32>, + pub has_background_color: bool, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TimelineModel { + pub layers: Vec<LayerModel>, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum LayerType { + #[default] + Normal, + Folder, + Guide, + Mask, + Other, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct LayerModel { + pub layer_type: LayerType, + pub parent_layer_index: Option<u32>, + pub visible: Option<bool>, + pub locked: Option<bool>, + pub outline: Option<bool>, + pub height_multiplier: Option<u32>, + pub frames: Vec<FrameModel>, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TweenType { + Motion, + Shape, + MotionObject, + #[default] + Other, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct FrameModel { + pub index: Option<u32>, + pub duration: Option<u32>, + pub is_comment: bool, + pub tween_type: TweenType, +} + +/// A timeline (`DOMTimeline`) listed under `DOMDocument/timelines`. +#[derive(Debug)] +pub struct Timeline<'a, E: XflElement = El> { + element: &'a E, +} + +impl<E: XflElement> Copy for Timeline<'_, E> {} + +impl<E: XflElement> Clone for Timeline<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +/// A native `DOMLayer` element. +#[derive(Debug)] +pub struct Layer<'a, E: XflElement = El> { + element: &'a E, +} + +impl<E: XflElement> Copy for Layer<'_, E> {} + +impl<E: XflElement> Clone for Layer<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +/// A native `DOMFrame` element. +#[derive(Debug)] +pub struct Frame<'a, E: XflElement = El> { + element: &'a E, +} + +/// An `Include` entry in the document's `<symbols>` library list. +#[derive(Debug)] +pub struct SymbolInclude<'a, E: XflElement = El> { + element: &'a E, +} + +/// A folder entry in the document's `<folders>` library list. +#[derive(Debug)] +pub struct LibraryFolder<'a, E: XflElement = El> { + element: &'a E, +} + +/// Native metadata stored on a library `DOMSymbolItem`. +#[derive(Debug)] +pub struct SymbolItem<'a, E: XflElement = El> { + element: &'a E, +} + +impl<E: XflElement> Copy for Frame<'_, E> {} + +impl<E: XflElement> Clone for Frame<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +impl<E: XflElement> Copy for SymbolInclude<'_, E> {} + +impl<E: XflElement> Clone for SymbolInclude<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +impl<E: XflElement> Copy for LibraryFolder<'_, E> {} + +impl<E: XflElement> Clone for LibraryFolder<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +impl<E: XflElement> Copy for SymbolItem<'_, E> {} + +impl<E: XflElement> Clone for SymbolItem<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +fn attr_last<'a>(element: &'a impl XflElement, name: &str) -> Option<&'a str> { + element.attr(name) +} + +fn number_f32(element: &impl XflElement, name: &str) -> Option<f32> { + attr_last(element, name).and_then(|value| value.trim().parse::<f32>().ok()).filter(|value| value.is_finite()) +} + +fn number_u32(element: &impl XflElement, name: &str) -> Option<u32> { + attr_last(element, name).and_then(|value| value.trim().parse::<u32>().ok()) +} + +fn boolean(element: &impl XflElement, name: &str) -> Option<bool> { + attr_last(element, name).map(|value| value.trim() == "true") +} + +fn trimmed_text<'a>(element: &'a El) -> Option<Cow<'a, str>> { + match element.text() { + Cow::Borrowed(text) => { + let trimmed = text.trim(); + (!trimmed.is_empty()).then_some(Cow::Borrowed(trimmed)) + } + Cow::Owned(text) => { + let trimmed = text.trim(); + (!trimmed.is_empty()).then(|| Cow::Owned(trimmed.to_string())) + } + } +} + +impl Document { + /// Parse XFL XML with AniCraft's existing size, depth, element, attribute, entity, doctype + /// and malformed-end-tag behavior. The shared XML parser owns byte parsing; this crate owns + /// the XFL-specific limits and schema views. + pub fn parse(bytes: &[u8]) -> Result<Self, XmlError> { + let defaults = Limits::DEFAULT; + let limits = Limits { + max_input: MAX_XML_BYTES, + max_depth: MAX_XML_DEPTH, + max_nodes: MAX_XML_ELEMENTS.saturating_mul(2).saturating_add(1), + max_elements: MAX_XML_ELEMENTS, + max_attrs: defaults.max_attrs, + max_attrs_total: defaults.max_attrs_total, + }; + let options = + Options { limits, strict_end_tags: true, unknown_entity: UnknownEntity::Literal, doctype: Doctype::Ignore, ..Options::default() }; + Ok(Self { root: options.parse(bytes)? }) + } + + /// The lossless XML tree used by consumer adapters for schema details this view does not + /// interpret. Text and child order come directly from `craft-xml`. + pub fn root(&self) -> &El { + &self.root + } + + /// The root's local element name (normally `DOMDocument`). + pub fn root_name(&self) -> &str { + &self.root.name + } + + /// Reads the current publish profile, falling back to the first profile and then the root. + /// This is also used for `PublishSettings.xml` files, whose schema is separate from the main + /// `DOMDocument` tree. + pub fn publish_settings(&self) -> PublishSettings<'_> { + let profile = self + .root + .elements() + .find(|element| Local("flash_profile").matches(&element.name) && boolean(*element, "current") == Some(true)) + .or_else(|| self.root.elements().find(|element| Local("flash_profile").matches(&element.name))) + .unwrap_or(&self.root); + let properties = profile.child(Local("PublishFlashProperties")).unwrap_or(profile); + let value = |name: &str| properties.child(Local(name)).and_then(trimmed_text); + PublishSettings { action_script_version: value("ActionScriptVersion"), document_class: value("DocumentClass") } + } + + /// The XFL stage metadata, applying finite-number checks but leaving product defaults and + /// clamping to the consumer. + pub fn stage(&self) -> Stage<'_> { + Stage { + width: number_f32(&self.root, "width"), + height: number_f32(&self.root, "height"), + frame_rate: number_f32(&self.root, "frameRate"), + background_color: attr_last(&self.root, "backgroundColor"), + } + } + + /// Timelines in document order. Non-`DOMTimeline` extension nodes are skipped. + pub fn timelines(&self) -> impl Iterator<Item = Timeline<'_>> { + self.root + .child(Local("timelines")) + .into_iter() + .flat_map(El::elements) + .filter(|element| Local("DOMTimeline").matches(&element.name)) + .map(|element| Timeline { element }) + } + + /// The timeline nested under `DOMSymbolItem/timeline`, if this is library symbol XML. + pub fn symbol_timeline(&self) -> Option<Timeline<'_>> { + self.root.child(Local("timeline"))?.child(Local("DOMTimeline")).map(|element| Timeline { element }) + } + + /// Projects bounded schema metadata and returns the XML tree by ownership. Consumers can + /// convert that tree into their compatibility representation without keeping two full trees + /// alive during import. + pub fn into_parts(self, limits: ModelLimits) -> (DocumentModel, El) { + let stage = StageModel { + width: number_f32(&self.root, "width"), + height: number_f32(&self.root, "height"), + frame_rate: number_f32(&self.root, "frameRate"), + has_background_color: attr_last(&self.root, "backgroundColor").is_some(), + }; + let timelines = self.timelines().take(limits.max_timelines).map(|timeline| timeline.into_model(limits.max_layers_per_timeline)).collect(); + let symbol_timeline = self.symbol_timeline().map(|timeline| timeline.into_model(limits.max_layers_per_timeline)); + (DocumentModel { stage, timelines, symbol_timeline }, self.root) + } +} + +impl<'a, E: XflElement> Timeline<'a, E> { + /// Creates a borrowed XFL timeline view over a consumer's compatible XML element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + pub fn name(self) -> Option<&'a str> { + attr_last(self.element, "name") + } + + /// Raw timeline XML for application-specific payload conversion. + pub fn element(self) -> &'a E { + self.element + } + + /// Layers in native order. Non-`DOMLayer` extension nodes are skipped. + pub fn layers(self) -> impl Iterator<Item = Layer<'a, E>> { + self.element + .child("layers") + .into_iter() + .flat_map(|element| element.elements()) + .filter(|element| element.local_name() == "DOMLayer") + .map(|element| Layer { element }) + } + + fn into_model(self, max_layers: usize) -> TimelineModel { + TimelineModel { layers: self.layers().take(max_layers).map(Layer::into_model).collect() } + } +} + +impl<'a, E: XflElement> Layer<'a, E> { + /// Creates a borrowed XFL layer view over a consumer's compatible XML element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + pub fn name(self) -> Option<&'a str> { + attr_last(self.element, "name") + } + + pub fn layer_type(self) -> Option<&'a str> { + attr_last(self.element, "layerType") + } + + pub fn parent_layer_index(self) -> Option<u32> { + number_u32(self.element, "parentLayerIndex") + } + + pub fn visible(self) -> Option<bool> { + boolean(self.element, "visible") + } + + pub fn locked(self) -> Option<bool> { + boolean(self.element, "locked") + } + + pub fn outline(self) -> Option<bool> { + boolean(self.element, "outline") + } + + pub fn color(self) -> Option<&'a str> { + attr_last(self.element, "color") + } + + pub fn height_multiplier(self) -> Option<u32> { + number_u32(self.element, "heightMultiplier") + } + + /// Frames in native order. Non-`DOMFrame` extension nodes are skipped. + pub fn element(self) -> &'a E { + self.element + } + + pub fn frames(self) -> impl Iterator<Item = Frame<'a, E>> { + self.element + .child("frames") + .into_iter() + .flat_map(|element| element.elements()) + .filter(|element| element.local_name() == "DOMFrame") + .map(|element| Frame { element }) + } + + fn into_model(self) -> LayerModel { + let layer_type = match attr_last(self.element, "layerType") { + Some("folder") => LayerType::Folder, + Some("guide") => LayerType::Guide, + Some("mask") => LayerType::Mask, + Some("normal") | None => LayerType::Normal, + Some(_) => LayerType::Other, + }; + LayerModel { + layer_type, + parent_layer_index: number_u32(self.element, "parentLayerIndex"), + visible: boolean(self.element, "visible"), + locked: boolean(self.element, "locked"), + outline: boolean(self.element, "outline"), + height_multiplier: number_u32(self.element, "heightMultiplier"), + frames: self.frames().map(Frame::into_model).collect(), + } + } +} + +impl<'a, E: XflElement> Frame<'a, E> { + /// Creates a borrowed XFL frame view over a consumer's compatible XML element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + pub fn index(self) -> Option<u32> { + number_u32(self.element, "index") + } + + pub fn duration(self) -> Option<u32> { + number_u32(self.element, "duration") + } + + pub fn label_type(self) -> Option<&'a str> { + attr_last(self.element, "labelType") + } + + pub fn name(self) -> Option<&'a str> { + attr_last(self.element, "name") + } + + pub fn tween_type(self) -> Option<&'a str> { + attr_last(self.element, "tweenType") + } + + /// Raw frame XML for application-specific shape, action, sound and tween conversion. + pub fn element(self) -> &'a E { + self.element + } + + fn into_model(self) -> FrameModel { + let tween_type = match attr_last(self.element, "tweenType") { + Some("motion") => TweenType::Motion, + Some("shape") => TweenType::Shape, + Some("motion object") => TweenType::MotionObject, + _ => TweenType::Other, + }; + FrameModel { + index: number_u32(self.element, "index"), + duration: number_u32(self.element, "duration"), + is_comment: attr_last(self.element, "labelType").is_some_and(|value| value.trim() == "comment"), + tween_type, + } + } +} + +impl<'a, E: XflElement> SymbolInclude<'a, E> { + /// Creates a borrowed view over a native `Include` element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + /// The package-relative library XML path from `href`, kept in native string form. + pub fn href(self) -> Option<&'a str> { + attr_last(self.element, "href") + } + + /// The source element for application-specific path resolution. + pub fn element(self) -> &'a E { + self.element + } +} + +impl<'a, E: XflElement> LibraryFolder<'a, E> { + /// Creates a borrowed view over a native `DOMFolderItem` element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + /// The folder path from `name`, kept in native string form. + pub fn name(self) -> Option<&'a str> { + attr_last(self.element, "name") + } + + /// The source element for application-specific path validation. + pub fn element(self) -> &'a E { + self.element + } +} + +impl<'a, E: XflElement> SymbolItem<'a, E> { + /// Creates a borrowed view over a native `DOMSymbolItem` element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + pub fn name(self) -> Option<&'a str> { + attr_last(self.element, "name") + } + + pub fn symbol_type(self) -> Option<&'a str> { + attr_last(self.element, "symbolType") + } + + pub fn linkage_export_for_action_script(self) -> Option<&'a str> { + attr_last(self.element, "linkageExportForAS") + } + + pub fn linkage_class_name(self) -> Option<&'a str> { + attr_last(self.element, "linkageClassName") + } + + pub fn linkage_identifier(self) -> Option<&'a str> { + attr_last(self.element, "linkageIdentifier") + } + + pub fn linkage_base_class(self) -> Option<&'a str> { + attr_last(self.element, "linkageBaseClass") + } + + /// Whether the symbol declares any native 9-slice scale-grid attribute, even if malformed. + pub fn has_scale_grid(self) -> bool { + ["scaleGridLeft", "scaleGridRight", "scaleGridTop", "scaleGridBottom"].iter().any(|name| attr_last(self.element, name).is_some()) + } + + pub fn scale_grid_left(self) -> Option<f32> { + number_f32(self.element, "scaleGridLeft") + } + + pub fn scale_grid_right(self) -> Option<f32> { + number_f32(self.element, "scaleGridRight") + } + + pub fn scale_grid_top(self) -> Option<f32> { + number_f32(self.element, "scaleGridTop") + } + + pub fn scale_grid_bottom(self) -> Option<f32> { + number_f32(self.element, "scaleGridBottom") + } + + /// The symbol's optional timeline wrapper, for the consumer to map into its own model. + pub fn timeline(self) -> Option<&'a E> { + self.element.child("timeline") + } + + /// The source element for application-specific symbol validation and mapping. + pub fn element(self) -> &'a E { + self.element + } +} + +/// Symbol library entries in source order, skipping non-`Include` extension nodes. +pub fn symbol_includes<'a, E: XflElement>(root: &'a E) -> impl Iterator<Item = SymbolInclude<'a, E>> + 'a { + root.child("symbols").into_iter().flat_map(XflElement::elements).filter(|element| element.local_name() == "Include").map(SymbolInclude::new) +} + +/// Library folders in source order, skipping non-`DOMFolderItem` extension nodes. +pub fn library_folders<'a, E: XflElement>(root: &'a E) -> impl Iterator<Item = LibraryFolder<'a, E>> + 'a { + root.child("folders").into_iter().flat_map(XflElement::elements).filter(|element| element.local_name() == "DOMFolderItem").map(LibraryFolder::new) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_stage_scene_layer_and_frame_schema_without_building_an_app_model() { + let bytes = br##"<!DOCTYPE DOMDocument [<!ENTITY custom "kept">]> +<DOMDocument width="640" height="480" frameRate="29.97" backgroundColor="#123456"> + <timelines> + <Extension/> + <DOMTimeline name="Scene &custom;"><layers> + <Extension/> + <DOMLayer name="Background" layerType="normal" visible="false" locked="true" outline="true" color="#abcdef" heightMultiplier="2" parentLayerIndex="0"> + <frames><DOMFrame index="4" duration="3" name="Intro" labelType="name" tweenType="motion"><elements><Shape/></elements></DOMFrame></frames> + </DOMLayer> + </layers></DOMTimeline> + </timelines> +</DOMDocument>"##; + let document = Document::parse(bytes).unwrap(); + assert_eq!(document.root_name(), "DOMDocument"); + let stage = document.stage(); + assert_eq!((stage.width, stage.height, stage.frame_rate), (Some(640.0), Some(480.0), Some(29.97))); + assert_eq!(stage.background_color, Some("#123456")); + let mut timelines = document.timelines(); + let timeline = timelines.next().unwrap(); + assert_eq!(timeline.name(), Some("Scene &custom;"), "declared entities stay literal"); + assert!(timelines.next().is_none()); + let mut layers = timeline.layers(); + let layer = layers.next().unwrap(); + assert_eq!(layer.name(), Some("Background")); + assert_eq!(layer.layer_type(), Some("normal")); + assert_eq!(layer.parent_layer_index(), Some(0)); + assert_eq!((layer.visible(), layer.locked(), layer.outline()), (Some(false), Some(true), Some(true))); + assert_eq!(layer.color(), Some("#abcdef")); + assert_eq!(layer.height_multiplier(), Some(2)); + let frame = layer.frames().next().unwrap(); + assert_eq!((frame.index(), frame.duration()), (Some(4), Some(3))); + assert_eq!((frame.name(), frame.label_type(), frame.tween_type()), (Some("Intro"), Some("name"), Some("motion"))); + assert_eq!(frame.element().child("elements").unwrap().child("Shape").unwrap().name, "Shape"); + } + + #[test] + fn borrowed_timeline_views_accept_compatible_element_adapters() { + #[derive(Debug)] + struct AppElement { + name: String, + attributes: Vec<(String, String)>, + children: Vec<AppElement>, + } + + impl XflElement for AppElement { + type Elements<'a> = std::slice::Iter<'a, Self>; + + fn local_name(&self) -> &str { + self.name.rsplit(':').next().unwrap_or(&self.name) + } + + fn attr(&self, name: &str) -> Option<&str> { + self.attributes.iter().rev().find(|(key, _)| key == name).map(|(_, value)| value.as_str()) + } + + fn elements(&self) -> Self::Elements<'_> { + self.children.iter() + } + + fn text_content(&self) -> Cow<'_, str> { + Cow::Borrowed("") + } + } + + fn element(name: &str, attributes: &[(&str, &str)], children: Vec<AppElement>) -> AppElement { + AppElement { + name: name.to_string(), + attributes: attributes.iter().map(|(key, value)| ((*key).to_string(), (*value).to_string())).collect(), + children, + } + } + + let root = element( + "x:DOMDocument", + &[], + vec![element( + "x:timelines", + &[], + vec![element( + "x:DOMTimeline", + &[("name", "Old"), ("name", "Scene")], + vec![element( + "x:layers", + &[], + vec![element( + "x:DOMLayer", + &[("name", "Old"), ("name", "Layer"), ("color", "#abcdef"), ("visible", "false")], + vec![element( + "x:frames", + &[], + vec![element( + "x:DOMFrame", + &[ + ("index", "999"), + ("index", "3"), + ("duration", "2"), + ("name", "Intro"), + ("labelType", "name"), + ("tweenType", "motion"), + ], + vec![], + )], + )], + )], + )], + )], + )], + ); + let timeline_element = root.child("timelines").unwrap().child("DOMTimeline").unwrap(); + let timeline = Timeline::new(timeline_element); + assert_eq!(timeline.name(), Some("Scene")); + let layer = timeline.layers().next().unwrap(); + assert_eq!(layer.name(), Some("Layer")); + assert_eq!(layer.color(), Some("#abcdef")); + assert_eq!(layer.visible(), Some(false)); + let frame = layer.frames().next().unwrap(); + assert_eq!((frame.index(), frame.duration()), (Some(3), Some(2))); + assert_eq!((frame.name(), frame.label_type(), frame.tween_type()), (Some("Intro"), Some("name"), Some("motion"))); + } + + #[test] + fn uses_last_duplicate_attribute_like_the_legacy_xfl_adapter() { + let document = Document::parse(br##"<DOMDocument width="1" width="2"><timelines/></DOMDocument>"##).unwrap(); + assert_eq!(document.stage().width, Some(2.0)); + } + + #[test] + fn preserves_lenient_doctype_entities_and_strict_end_tag_behavior() { + let document = Document::parse(br##"<!DOCTYPE DOMDocument><DOMDocument width="&custom;"/>tail"##).unwrap(); + assert_eq!(document.stage().width, None); + assert!(Document::parse(b"<DOMDocument><timelines></DOMDocument>").is_err()); + } + + #[test] + fn applies_the_existing_xfl_depth_and_attribute_budgets() { + let too_deep = format!("{}{}", "<x>".repeat(MAX_XML_DEPTH + 1), "</x>".repeat(MAX_XML_DEPTH + 1)); + assert!(matches!(Document::parse(too_deep.as_bytes()), Err(XmlError::TooDeep(_)))); + + let mut too_many_attrs = String::from("<DOMDocument"); + for _ in 0..=Limits::DEFAULT.max_attrs { + too_many_attrs.push_str(" x=''"); + } + too_many_attrs.push_str("/>"); + assert!(matches!(Document::parse(too_many_attrs.as_bytes()), Err(XmlError::TooManyAttrs(_)))); + } + + #[test] + fn projects_neutral_schema_fields_and_returns_the_xml_tree_by_move() { + let document = Document::parse( + br##"<DOMDocument width="640" backgroundColor="#fff"><timelines><DOMTimeline name="Scene"><layers><DOMLayer name="Layer" layerType="mask" visible="false"><frames><DOMFrame index="7" duration="2" labelType="comment" tweenType="shape"/></frames></DOMLayer></layers></DOMTimeline></timelines></DOMDocument>"##, + ) + .unwrap(); + let (model, root) = document.into_parts(ModelLimits { max_timelines: 1, max_layers_per_timeline: 1 }); + assert_eq!(model.stage, StageModel { width: Some(640.0), height: None, frame_rate: None, has_background_color: true }); + assert_eq!(model.timelines.len(), 1); + let layer = &model.timelines[0].layers[0]; + assert_eq!(layer.layer_type, LayerType::Mask); + assert_eq!(layer.visible, Some(false)); + assert_eq!(layer.frames[0], FrameModel { index: Some(7), duration: Some(2), is_comment: true, tween_type: TweenType::Shape }); + assert_eq!(root.attr("width"), Some("640")); + assert_eq!(root.child("timelines").unwrap().child("DOMTimeline").unwrap().attr("name"), Some("Scene")); + } + + #[test] + fn projects_symbol_timeline_under_the_native_symbol_wrapper() { + let document = Document::parse(b"<DOMSymbolItem><timeline><DOMTimeline><layers><DOMLayer><frames><DOMFrame index='1'/></frames></DOMLayer></layers></DOMTimeline></timeline></DOMSymbolItem>").unwrap(); + let (model, _) = document.into_parts(ModelLimits { max_timelines: 10, max_layers_per_timeline: 10 }); + assert!(model.timelines.is_empty()); + assert_eq!(model.symbol_timeline.unwrap().layers[0].frames[0].index, Some(1)); + } + + #[test] + fn recognizes_prefixed_xfl_timeline_elements_by_local_name() { + let document = Document::parse( + b"<x:DOMDocument xmlns:x='urn:adobe:xfl'><x:timelines><x:DOMTimeline><x:layers><x:DOMLayer><x:frames><x:DOMFrame index='4' duration='2'/></x:frames></x:DOMLayer></x:layers></x:DOMTimeline></x:timelines></x:DOMDocument>", + ) + .unwrap(); + { + let mut timelines = document.timelines(); + let timeline = timelines.next().unwrap(); + assert!(timelines.next().is_none()); + let mut layers = timeline.layers(); + let layer = layers.next().unwrap(); + assert!(layers.next().is_none()); + let frame = layer.frames().next().unwrap(); + assert_eq!((frame.index(), frame.duration()), (Some(4), Some(2))); + } + let (model, _) = document.into_parts(ModelLimits { max_timelines: 1, max_layers_per_timeline: 1 }); + assert_eq!(model.timelines[0].layers[0].frames[0].index, Some(4)); + + let symbol = + Document::parse(b"<x:DOMSymbolItem xmlns:x='urn:adobe:xfl'><x:timeline><x:DOMTimeline/></x:timeline></x:DOMSymbolItem>").unwrap(); + assert!(symbol.symbol_timeline().is_some()); + } + + #[test] + fn reads_prefixed_publish_settings_children_by_local_name() { + let document = Document::parse( + b"<x:PublishSettings xmlns:x='urn:adobe:xfl'><x:flash_profile current='true'><x:PublishFlashProperties><x:ActionScriptVersion>3</x:ActionScriptVersion><x:DocumentClass>com.example.Main</x:DocumentClass></x:PublishFlashProperties></x:flash_profile></x:PublishSettings>", + ) + .unwrap(); + let settings = document.publish_settings(); + assert_eq!(settings.action_script_version.as_deref(), Some("3")); + assert_eq!(settings.document_class.as_deref(), Some("com.example.Main")); + } + + #[test] + fn selects_current_publish_profile_and_uses_native_value_strings() { + let document = Document::parse( + br#"<PublishSettings><flash_profile><PublishFlashProperties><ActionScriptVersion>2</ActionScriptVersion><DocumentClass>OldClass</DocumentClass></PublishFlashProperties></flash_profile><flash_profile current="true"><PublishFlashProperties><ActionScriptVersion> 3 </ActionScriptVersion><DocumentClass> com.example.Main </DocumentClass></PublishFlashProperties></flash_profile></PublishSettings>"#, + ) + .unwrap(); + let settings = document.publish_settings(); + assert_eq!(settings.action_script_version.as_deref(), Some("3")); + assert_eq!(settings.document_class.as_deref(), Some("com.example.Main")); + } + + #[test] + fn publish_settings_fall_back_to_first_profile_then_root() { + let first = Document::parse( + br#"<PublishSettings><flash_profile><PublishFlashProperties><ActionScriptVersion>2</ActionScriptVersion></PublishFlashProperties></flash_profile><flash_profile><PublishFlashProperties><ActionScriptVersion>3</ActionScriptVersion></PublishFlashProperties></flash_profile></PublishSettings>"#, + ) + .unwrap(); + assert_eq!(first.publish_settings().action_script_version.as_deref(), Some("2")); + + let root = Document::parse( + br#"<PublishSettings><ActionScriptVersion> 3 </ActionScriptVersion><DocumentClass>RootClass</DocumentClass></PublishSettings>"#, + ) + .unwrap(); + let settings = root.publish_settings(); + assert_eq!(settings.action_script_version.as_deref(), Some("3")); + assert_eq!(settings.document_class.as_deref(), Some("RootClass")); + } + + #[test] + fn reads_symbol_library_entries_and_native_symbol_metadata() { + let document = Document::parse( + br#"<DOMDocument><symbols><Extension/><Include href="LIBRARY/Shape.xml"/><Include href="LIBRARY/Button.xml"/></symbols><folders><Extension/><DOMFolderItem name="Characters/Hero"/></folders></DOMDocument>"#, + ) + .unwrap(); + let includes: Vec<_> = symbol_includes(document.root()).map(SymbolInclude::href).collect(); + assert_eq!(includes, [Some("LIBRARY/Shape.xml"), Some("LIBRARY/Button.xml")]); + let include = symbol_includes(document.root()).next().unwrap(); + assert_eq!(include.element().local_name(), "Include"); + let folders: Vec<_> = library_folders(document.root()).map(LibraryFolder::name).collect(); + assert_eq!(folders, [Some("Characters/Hero")]); + let folder = library_folders(document.root()).next().unwrap(); + assert_eq!(folder.element().local_name(), "DOMFolderItem"); + + let symbol = Document::parse( + br#"<x:DOMSymbolItem xmlns:x="urn:adobe:xfl" name="Characters/Hero" name="Characters/Final" symbolType="graphic" linkageExportForAS="true" linkageClassName="example.Hero" linkageIdentifier="legacy.Hero" linkageBaseClass="flash.display.MovieClip" scaleGridLeft="10" scaleGridRight="90" scaleGridTop="5" scaleGridBottom="75"><x:timeline><x:DOMTimeline/></x:timeline></x:DOMSymbolItem>"#, + ) + .unwrap(); + let item = SymbolItem::new(symbol.root()); + assert_eq!(item.element().local_name(), "DOMSymbolItem"); + assert_eq!(item.name(), Some("Characters/Final"), "the last duplicate attribute wins"); + assert_eq!(item.symbol_type(), Some("graphic")); + assert_eq!(item.linkage_export_for_action_script(), Some("true")); + assert_eq!(item.linkage_class_name(), Some("example.Hero")); + assert_eq!(item.linkage_identifier(), Some("legacy.Hero")); + assert_eq!(item.linkage_base_class(), Some("flash.display.MovieClip")); + assert_eq!( + (item.scale_grid_left(), item.scale_grid_right(), item.scale_grid_top(), item.scale_grid_bottom()), + (Some(10.0), Some(90.0), Some(5.0), Some(75.0)) + ); + assert!(item.has_scale_grid()); + assert!(item.timeline().is_some()); + + let malformed = Document::parse(br#"<DOMSymbolItem scaleGridLeft="not-a-number"/>"#).unwrap(); + let malformed = SymbolItem::new(malformed.root()); + assert!(malformed.has_scale_grid(), "attribute presence remains observable when its value is malformed"); + assert_eq!(malformed.scale_grid_left(), None); + + let absent = Document::parse(b"<DOMSymbolItem/>").unwrap(); + assert!(!SymbolItem::new(absent.root()).has_scale_grid()); + } +} diff --git a/crates/xfl/src/edges.rs b/crates/xfl/src/edges.rs new file mode 100644 index 000000000..e58602e9d --- /dev/null +++ b/crates/xfl/src/edges.rs @@ -0,0 +1,152 @@ +//! XFL's compact shape-edge attribute grammar. +//! +//! An edge's `edges` attribute uses twips (1/20 pixel): `!x y` moves, `|x y` and `/x y` draw a +//! line, `[cx cy x y` and `]cx cy x y` draw a quadratic curve, and `Sn` marks selection state. +//! Coordinates may be decimal or signed 24.8 fixed-point hexadecimal (`#A.8` is 10.5). +//! +//! This module returns neutral points and segments so consumers can map them to their own +//! geometry model. Like Animate files in the wild, a damaged suffix ends parsing while keeping +//! the valid prefix. The segment cap bounds output allocation. + +/// Most segments parsed from one edge attribute. +pub const MAX_EDGE_SEGMENTS: usize = 2_000_000; + +/// A point in XFL's edge geometry, expressed in pixels after twips conversion. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Point { + pub x: f32, + pub y: f32, +} + +/// One line (`control` is absent) or quadratic curve segment. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Segment { + pub from: Point, + pub control: Option<Point>, + pub to: Point, +} + +const TWIPS_PER_PIXEL: f32 = 20.0; + +fn number(input: &[u8], at: &mut usize) -> Option<f32> { + while input.get(*at).is_some_and(|b| b.is_ascii_whitespace()) { + *at += 1; + } + let start = *at; + if input.get(*at) == Some(&b'#') { + *at += 1; + let integer_start = *at; + while input.get(*at).is_some_and(u8::is_ascii_hexdigit) { + *at += 1; + } + let integer = std::str::from_utf8(input.get(integer_start..*at)?).ok()?; + let mut fraction = 0_u32; + if input.get(*at) == Some(&b'.') { + *at += 1; + let fraction_start = *at; + while input.get(*at).is_some_and(u8::is_ascii_hexdigit) && *at - fraction_start < 2 { + *at += 1; + } + let digits = std::str::from_utf8(input.get(fraction_start..*at)?).ok()?; + // A single hex digit is the high nibble of the 8-bit fractional part. + fraction = u32::from_str_radix(digits, 16).ok()? << if digits.len() == 1 { 4 } else { 0 }; + } + let whole = u32::from_str_radix(if integer.is_empty() { "0" } else { integer }, 16).ok()?; + let fixed = whole.wrapping_shl(8) | fraction; + return Some((fixed as i32) as f32 / 256.0); + } + if matches!(input.get(*at), Some(b'-' | b'+')) { + *at += 1; + } + while input.get(*at).is_some_and(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E')) { + *at += 1; + } + std::str::from_utf8(input.get(start..*at)?).ok()?.parse::<f32>().ok().filter(|v| v.is_finite()) +} + +fn point(input: &[u8], at: &mut usize) -> Option<Point> { + Some(Point { x: number(input, at)? / TWIPS_PER_PIXEL, y: number(input, at)? / TWIPS_PER_PIXEL }) +} + +/// Parses an XFL `<Edge edges="…">` attribute into pixel-coordinate line and quadratic segments. +/// +/// Stops at the first unknown or malformed command, preserving the valid prefix. The current +/// point starts at the origin. Move and selection commands do not produce segments. +pub fn parse_edge_segments(source: &str) -> Vec<Segment> { + let input = source.as_bytes(); + let mut at = 0; + let mut current = Point::default(); + let mut segments = Vec::new(); + while let Some(&command) = input.get(at) { + at += 1; + match command { + b'!' => match point(input, &mut at) { + Some(p) => current = p, + None => break, + }, + b'|' | b'/' => match point(input, &mut at) { + Some(to) => { + segments.push(Segment { from: current, control: None, to }); + current = to; + } + None => break, + }, + b'[' | b']' => match (point(input, &mut at), point(input, &mut at)) { + (Some(control), Some(to)) => { + segments.push(Segment { from: current, control: Some(control), to }); + current = to; + } + _ => break, + }, + b'S' => { + while input.get(at).is_some_and(u8::is_ascii_digit) { + at += 1; + } + } + b if b.is_ascii_whitespace() => {} + _ => break, + } + if segments.len() >= MAX_EDGE_SEGMENTS { + break; + } + } + segments +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_line_quadratic_and_twips() { + let segments = parse_edge_segments("!0 0|200 0[400 0 400 200S2/0 200"); + assert_eq!(segments.len(), 3); + assert_eq!(segments[0].to, Point { x: 10.0, y: 0.0 }); + assert_eq!(segments[1].control, Some(Point { x: 20.0, y: 0.0 })); + assert_eq!(segments[2], Segment { from: Point { x: 20.0, y: 10.0 }, control: None, to: Point { x: 0.0, y: 10.0 } }); + } + + #[test] + fn parses_signed_24_8_fixed_hex_coordinates() { + let segments = parse_edge_segments("!#A.8 -20|#FFFFFF.80 0"); + assert_eq!(segments.len(), 1); + assert_eq!(segments[0].from, Point { x: 0.525, y: -1.0 }); + assert_eq!(segments[0].to, Point { x: -0.025, y: 0.0 }); + } + + #[test] + fn malformed_suffix_keeps_only_valid_prefix() { + let segments = parse_edge_segments("!0 0|200 0[400 0 nope 200"); + assert_eq!(segments, [Segment { from: Point::default(), control: None, to: Point { x: 10.0, y: 0.0 } }]); + assert!(parse_edge_segments("!1 2|x").is_empty()); + assert!(parse_edge_segments("!NaN 2|5 5").is_empty()); + } + + #[test] + fn oversized_coordinate_numbers_and_segment_lists_are_bounded() { + assert!(parse_edge_segments("!999999999999999999999999999999999999999999999999 0|1 1").is_empty()); + let source = "|0 0".repeat(MAX_EDGE_SEGMENTS + 1); + let segments = parse_edge_segments(&source); + assert_eq!(segments.len(), MAX_EDGE_SEGMENTS); + } +} diff --git a/crates/xfl/src/filters.rs b/crates/xfl/src/filters.rs new file mode 100644 index 000000000..ef29a3707 --- /dev/null +++ b/crates/xfl/src/filters.rs @@ -0,0 +1,239 @@ +//! Borrowed views of native XFL filter records. +//! +//! This module parses the wire-level filter names, fields, and gradient-ramp entries. Consumers +//! remain responsible for mapping those values into their own rendering/filter models. + +use crate::shape::{self, Color, XflElement, boolean, integer, number}; + +/// Native filter variants understood by XFL. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FilterKind { + Blur, + DropShadow, + Glow, + AdjustColor, + Bevel, + GradientGlow, + GradientBevel, +} + +/// Bevel/glow placement recorded by the native `type` attribute. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FilterSide { + Inner, + Outer, + Full, +} + +/// The native `<filters>` list on an element, preserving source order and unknown records. +#[derive(Clone, Copy, Debug)] +pub struct FilterList<'a, E: XflElement> { + wrapper: Option<&'a E>, +} + +impl<'a, E: XflElement> FilterList<'a, E> { + pub fn new(element: &'a E) -> Self { + Self { wrapper: element.child("filters") } + } + + pub fn iter(&self) -> impl Iterator<Item = Filter<'a, E>> + 'a { + let wrapper = self.wrapper; + wrapper.into_iter().flat_map(XflElement::elements).map(|element| Filter { element }) + } +} + +/// One native filter record. Unknown records are retained so the consumer can report/skip them. +#[derive(Clone, Copy, Debug)] +pub struct Filter<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Filter<'a, E> { + pub fn kind(&self) -> Option<FilterKind> { + match self.element.local_name() { + "BlurFilter" => Some(FilterKind::Blur), + "DropShadowFilter" => Some(FilterKind::DropShadow), + "GlowFilter" => Some(FilterKind::Glow), + "AdjustColorFilter" => Some(FilterKind::AdjustColor), + "BevelFilter" => Some(FilterKind::Bevel), + "GradientGlowFilter" => Some(FilterKind::GradientGlow), + "GradientBevelFilter" => Some(FilterKind::GradientBevel), + _ => None, + } + } + + /// XFL treats filters as enabled unless explicitly set to false. + pub fn enabled(&self) -> bool { + boolean(self.element, "enabled") != Some(false) + } + + /// Quality is a native integer in the range 1 through 3, defaulting to 1. + pub fn quality(&self) -> u8 { + integer(self.element, "quality").unwrap_or(1).clamp(1, 3) as u8 + } + + pub fn blur_x(&self) -> Option<f32> { + number(self.element, "blurX") + } + + pub fn blur_y(&self) -> Option<f32> { + number(self.element, "blurY") + } + + pub fn strength(&self) -> Option<f32> { + number(self.element, "strength") + } + + pub fn angle(&self) -> Option<f32> { + number(self.element, "angle") + } + + pub fn distance(&self) -> Option<f32> { + number(self.element, "distance") + } + + pub fn brightness(&self) -> Option<f32> { + number(self.element, "brightness") + } + + pub fn contrast(&self) -> Option<f32> { + number(self.element, "contrast") + } + + pub fn saturation(&self) -> Option<f32> { + number(self.element, "saturation") + } + + pub fn hue(&self) -> Option<f32> { + number(self.element, "hue") + } + + pub fn inner(&self) -> Option<bool> { + boolean(self.element, "inner") + } + + pub fn knockout(&self) -> Option<bool> { + boolean(self.element, "knockout") + } + + pub fn hide_object(&self) -> Option<bool> { + boolean(self.element, "hideObject") + } + + pub fn side(&self) -> Option<FilterSide> { + match self.element.attr("type").map(str::trim) { + Some("inner") => Some(FilterSide::Inner), + Some("outer") => Some(FilterSide::Outer), + Some("full") => Some(FilterSide::Full), + _ => None, + } + } + + pub fn color(&self) -> Color { + shape::color(self.element, "color", "alpha") + } + + pub fn shadow_color(&self) -> Color { + shape::color(self.element, "shadowColor", "shadowAlpha") + } + + /// Explicit highlight color, absent when the native attribute is missing so consumers can + /// apply the format-specific white highlight default. + pub fn highlight_color(&self) -> Option<Color> { + self.element.attr("highlightColor").map(|_| shape::color(self.element, "highlightColor", "highlightAlpha")) + } + + pub fn highlight_alpha(&self) -> Option<f32> { + number(self.element, "highlightAlpha") + } + + /// Native gradient entries, either direct children or one wrapper level below the filter. + pub fn ramp_entries(&self) -> impl Iterator<Item = RampEntry<'a, E>> + 'a { + self.element + .elements() + .flat_map(|child| std::iter::once(child).chain(child.elements())) + .filter(|entry| entry.local_name() == "GradientEntry") + .map(|element| RampEntry { element }) + } +} + +/// One XFL gradient-ramp entry. +#[derive(Clone, Copy, Debug)] +pub struct RampEntry<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> RampEntry<'a, E> { + pub fn ratio(&self) -> Option<f32> { + number(self.element, "ratio") + } + + pub fn color(&self) -> Color { + shape::color(self.element, "color", "alpha") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::parse(source).expect("well-formed test XML") + } + + #[test] + fn recognizes_filter_kinds_and_preserves_unknown_entries_and_order() { + let root = parse(br##"<DOMSymbolInstance><filters><BlurFilter/><x:GlowFilter xmlns:x="urn:xfl" enabled="false"/><FutureFilter/><GradientBevelFilter/></filters></DOMSymbolInstance>"##); + let filters: Vec<_> = FilterList::new(&root).iter().collect(); + assert_eq!(filters.len(), 4); + assert_eq!(filters[0].kind(), Some(FilterKind::Blur)); + assert_eq!(filters[1].kind(), Some(FilterKind::Glow)); + assert!(!filters[1].enabled()); + assert_eq!(filters[2].kind(), None); + assert_eq!(filters[3].kind(), Some(FilterKind::GradientBevel)); + } + + #[test] + fn reads_native_filter_values_colors_and_gradient_entries_in_order() { + let root = parse( + br##"<DOMSymbolInstance><filters><DropShadowFilter blurX="7.5" blurY="8" strength="1.25" quality="9" angle="45" distance="4" color="#123456" alpha="0.5" inner="true" knockout="false" hideObject="true"/><BevelFilter type="full" shadowColor="#010203" shadowAlpha="0.25" highlightColor="#aabbcc" highlightAlpha="0.75"/><GradientGlowFilter><GradientEntry ratio="255" color="#ff0000"/><Ramp><GradientEntry ratio="64" color="#00ff00"/></Ramp></GradientGlowFilter></filters></DOMSymbolInstance>"##, + ); + let filters: Vec<_> = FilterList::new(&root).iter().collect(); + let shadow = &filters[0]; + assert_eq!(shadow.quality(), 3); + assert_eq!( + (shadow.blur_x(), shadow.blur_y(), shadow.strength(), shadow.angle(), shadow.distance()), + (Some(7.5), Some(8.0), Some(1.25), Some(45.0), Some(4.0)) + ); + assert_eq!(shadow.color(), Color { rgb: 0x123456, alpha: 0.5 }); + assert_eq!(shadow.inner(), Some(true)); + assert_eq!(shadow.knockout(), Some(false)); + assert_eq!(shadow.hide_object(), Some(true)); + + let bevel = &filters[1]; + assert_eq!(bevel.side(), Some(FilterSide::Full)); + assert_eq!(bevel.shadow_color(), Color { rgb: 0x010203, alpha: 0.25 }); + assert_eq!(bevel.highlight_color(), Some(Color { rgb: 0xaabbcc, alpha: 0.75 })); + + let ramp: Vec<_> = filters[2].ramp_entries().collect(); + assert_eq!(ramp.iter().map(RampEntry::ratio).collect::<Vec<_>>(), [Some(255.0), Some(64.0)]); + assert_eq!(ramp[0].color(), Color { rgb: 0xff0000, alpha: 1.0 }); + } + + #[test] + fn absent_lists_are_empty_and_values_use_shared_wire_validation() { + let root = parse(b"<DOMSymbolInstance/>"); + assert_eq!(FilterList::new(&root).iter().count(), 0); + + let root = parse(br##"<BlurFilter quality="bad" blurX="NaN" enabled="unexpected"/>"##); + let filter = FilterList::new(&root).iter().next(); + assert_eq!(filter.map(|filter| filter.kind()), None); + let parent = + parse(br##"<DOMSymbolInstance><filters><BlurFilter quality="bad" blurX="NaN" enabled="unexpected"/></filters></DOMSymbolInstance>"##); + let filter = FilterList::new(&parent).iter().next().expect("filter entry"); + assert_eq!(filter.kind(), Some(FilterKind::Blur)); + assert_eq!(filter.quality(), 1); + assert_eq!(filter.blur_x(), None); + assert!(!filter.enabled()); + } +} diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs new file mode 100644 index 000000000..fbcb3ecc2 --- /dev/null +++ b/crates/xfl/src/lib.rs @@ -0,0 +1,629 @@ +//! Reads the hostile ZIP package used by an Animate `.fla` (an archive of an XFL folder), +//! including its XFL-specific path rules and resource limits. +//! +//! Implements the parts of the published ZIP format (PKWARE APPNOTE 6.3) that archive tools +//! write: the end-of-central-directory record (and its ZIP64 form), central directory entries +//! with ZIP64 sizes, local headers, data descriptors, "stored" and "deflate" entries (inflated +//! by `miniz_oxide`), UTF-8 names (flag bit 11 or the Info-ZIP Unicode path field) and CP437 +//! names. Self-extracting archives with ZIP data after a program stub are supported whether +//! their offsets count from the ZIP data or from the start of the file. Encryption, other +//! compression methods and split archives are refused with a clear error. +//! +//! The archive is treated as hostile. Every offset and size is checked against the bytes it +//! comes from; entries may not overlap each other or the central directory; a name that would +//! leave the package (`..`, absolute or drive paths), is listed twice or is nested deeper than +//! [`MAX_DEPTH`] refuses the archive; an entry may not claim more than deflate can produce from +//! its bytes ([`MAX_RATIO`]), more than [`MAX_ENTRY`], or a size or checksum it doesn't have; +//! and the archive hands out at most [`MAX_TOTAL`] bytes in all. Nothing is ever written to +//! disk. Never panics. +//! +//! [`edges`] decodes native shape-edge attributes into neutral points and line/quadratic +//! segments for consumers to map into their own geometry models. + +use std::cell::Cell; +use std::collections::HashMap; + +/// Neutral views of the XFL document, timeline, layer and frame schema. +pub mod document; +/// XFL's edge-attribute grammar, independent of any consuming application's geometry types. +pub mod edges; +/// Borrowed views of native XFL filter records. +pub mod filters; +/// Borrowed views of native XFL media library records. +pub mod media; +/// Borrowed views of native XFL shape and style elements. +pub mod shape; +/// Borrowed views of native XFL shape-hint records. +pub mod shape_hints; +/// Borrowed views of native XFL frame-sound and envelope records. +pub mod sound; +/// Borrowed views of native XFL text-field and text-run schema. +pub mod text; +/// Borrowed views of native XFL tween and custom-ease records. +pub mod tween; + +/// Largest single entry inflated (bytes). +pub const MAX_ENTRY: usize = 256 * 1024 * 1024; +/// Most bytes one archive hands out, over every read (the import's memory budget). +pub const MAX_TOTAL: u64 = 1024 * 1024 * 1024; +/// Most entries an archive may list (files and folders). +pub const MAX_ENTRIES: usize = 100_000; +/// Most folders a path may be inside (Animate's library nests a few deep). +pub const MAX_DEPTH: usize = 32; +/// Largest size-to-compressed-size ratio believed: deflate itself can't pass about 1032 : 1, +/// so an entry claiming more is a zip bomb or a damaged size, refused before inflating. +pub const MAX_RATIO: u64 = 1024; + +#[derive(Debug, Clone, thiserror::Error, PartialEq)] +pub enum ZipError { + #[error("not a zip archive (no end-of-directory record)")] + NotZip, + #[error("the archive is damaged: {0}")] + Damaged(&'static str), + #[error("the archive is damaged: '{0}' {1}")] + DamagedEntry(String, &'static str), + #[error("the archive uses a zip feature this XFL reader can't read ({0})")] + UnsupportedArchive(&'static str), + #[error("'{0}' uses a zip feature this XFL reader can't read ({1})")] + Unsupported(String, &'static str), + #[error("'{0}' is too large to read")] + TooLarge(String), + #[error("the archive asks for more than {} MB in all", MAX_TOTAL / (1024 * 1024))] + TooMuch, + #[error("the archive lists more than {MAX_ENTRIES} files")] + TooMany, + #[error("'{0}' claims to expand more than compression allows (a zip bomb or a damaged archive)")] + Bomb(String), + #[error("'{0}' and '{1}' share bytes in the archive (a zip bomb or a damaged archive)")] + Overlap(String, String), + #[error("'{0}' points outside the document")] + Unsafe(String), + #[error("'{0}' is in the archive twice")] + Duplicate(String), + #[error("'{0}' is inside more than {MAX_DEPTH} folders")] + TooDeep(String), +} + +#[derive(Debug, Clone)] +struct Entry { + method: u16, + flags: u16, + crc: u32, + comp: usize, + size: usize, + /// Where its (compressed) bytes start. + data: usize, +} + +pub struct Archive<'a> { + data: &'a [u8], + entries: HashMap<String, Entry>, + folders: usize, + /// Bytes still to hand out ([`MAX_TOTAL`] at first). + budget: Cell<u64>, +} + +/// The package root selected from an XFL archive's `DOMDocument.xml` paths. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum XflPackageRoot<'a> { + /// A document XML file is directly at the archive root. + Document, + /// The sole eligible top-level folder containing a document. + Folder(&'a str), + /// No document path was found. + Missing, + /// More than one eligible top-level folder contains a document, sorted by name. + Multiple(Vec<&'a str>), +} + +const END: u32 = 0x0605_4b50; +const END64: u32 = 0x0606_4b50; +const LOCATOR64: u32 = 0x0706_4b50; +const CENTRAL: u32 = 0x0201_4b50; +const LOCAL: u32 = 0x0403_4b50; + +fn get(d: &[u8], at: usize, len: usize) -> Option<&[u8]> { + d.get(at..at.checked_add(len)?) +} +fn u16_at(d: &[u8], i: usize) -> Option<u16> { + Some(u16::from_le_bytes(get(d, i, 2)?.try_into().ok()?)) +} +fn u32_at(d: &[u8], i: usize) -> Option<u32> { + Some(u32::from_le_bytes(get(d, i, 4)?.try_into().ok()?)) +} +fn u64_at(d: &[u8], i: usize) -> Option<u64> { + Some(u64::from_le_bytes(get(d, i, 8)?.try_into().ok()?)) +} + +/// The body of the extra field `id`, if `extra` has one. +fn extra_field(mut extra: &[u8], id: u16) -> Option<&[u8]> { + while extra.len() >= 4 { + let (tag, len) = (u16_at(extra, 0)?, u16_at(extra, 2)? as usize); + let body = get(extra, 4, len)?; + if tag == id { + return Some(body); + } + extra = extra.get(4 + len..)?; + } + None +} + +/// CRC-32 tables for eight bytes at a time ("slicing by 8"): `TABLES[0]` is the classic +/// byte table, `TABLES[k][b]` the checksum of byte `b` followed by `k` zero bytes. +const TABLES: [[u32; 256]; 8] = { + let mut t = [[0u32; 256]; 8]; + let mut i = 0; + while i < 256 { + let mut c = i as u32; + let mut k = 0; + while k < 8 { + c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + k += 1; + } + t[0][i] = c; + i += 1; + } + let mut k = 1; + while k < 8 { + let mut i = 0; + while i < 256 { + let prev = t[k - 1][i]; + t[k][i] = (prev >> 8) ^ t[0][(prev & 0xff) as usize]; + i += 1; + } + k += 1; + } + t +}; + +/// CRC-32 (ISO-HDLC, the zip checksum), eight bytes at a time. +pub fn crc32(data: &[u8]) -> u32 { + let t = &TABLES; + let mut c = !0u32; + let (blocks, rest) = data.as_chunks::<8>(); + for b in blocks { + let lo = c ^ u32::from_le_bytes([b[0], b[1], b[2], b[3]]); + c = t[7][(lo & 0xff) as usize] + ^ t[6][((lo >> 8) & 0xff) as usize] + ^ t[5][((lo >> 16) & 0xff) as usize] + ^ t[4][(lo >> 24) as usize] + ^ t[3][b[4] as usize] + ^ t[2][b[5] as usize] + ^ t[1][b[6] as usize] + ^ t[0][b[7] as usize]; + } + for &b in rest { + c = t[0][((c ^ b as u32) & 0xff) as usize] ^ (c >> 8); + } + !c +} + +/// Code page 437, bytes 0x80 to 0xFF: the zip format's name encoding without the UTF-8 flag. +const CP437: [char; 128] = [ + 'Ç', 'ü', 'é', 'â', 'ä', 'à', 'å', 'ç', 'ê', 'ë', 'è', 'ï', 'î', 'ì', 'Ä', 'Å', // + 'É', 'æ', 'Æ', 'ô', 'ö', 'ò', 'û', 'ù', 'ÿ', 'Ö', 'Ü', '¢', '£', '¥', '₧', 'ƒ', // + 'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', '⌐', '¬', '½', '¼', '¡', '«', '»', // + '░', '▒', '▓', '│', '┤', '╡', '╢', '╖', '╕', '╣', '║', '╗', '╝', '╜', '╛', '┐', // + '└', '┴', '┬', '├', '─', '┼', '╞', '╟', '╚', '╔', '╩', '╦', '╠', '═', '╬', '╧', // + '╨', '╤', '╥', '╙', '╘', '╒', '╓', '╫', '╪', '┘', '┌', '█', '▄', '▌', '▐', '▀', // + 'α', 'ß', 'Γ', 'π', 'Σ', 'σ', 'µ', 'τ', 'Φ', 'Θ', 'Ω', 'δ', '∞', 'φ', 'ε', '∩', // + '≡', '±', '≥', '≤', '⌠', '⌡', '÷', '≈', '°', '∙', '·', '√', 'ⁿ', '²', '■', '\u{a0}', +]; + +/// An entry's name as text: the Info-ZIP Unicode path field when it matches the name, UTF-8 +/// when flag bit 11 says so, else CP437 as the format specifies. Many writers store UTF-8 +/// without setting the flag, so a name that is valid UTF-8 is read as UTF-8 (ASCII, which +/// nearly every name is, reads the same either way). +fn decode_name(raw: &[u8], utf8: bool, extra: &[u8]) -> Result<String, ZipError> { + if let Some(up) = extra_field(extra, 0x7075) + && up.first() == Some(&1) + && u32_at(up, 1) == Some(crc32(raw)) + && let Some(Ok(s)) = up.get(5..).map(std::str::from_utf8) + { + return Ok(s.to_string()); + } + match std::str::from_utf8(raw) { + Ok(s) => Ok(s.to_string()), + Err(_) if utf8 => Err(ZipError::Damaged("an entry's name is not the UTF-8 it says it is")), + Err(_) => Ok(raw.iter().map(|&b| if b < 0x80 { b as char } else { CP437.get((b - 0x80) as usize).copied().unwrap_or('\u{fffd}') }).collect()), + } +} + +/// A name as a plain path inside the package: `\` read as `/`, empty and `.` parts dropped. +/// Names that would leave the package are refused, though nothing is ever extracted: every +/// lookup stays unambiguous, as the folder form's reader also refuses them. +fn clean_path(name: &str) -> Result<String, ZipError> { + let unix = name.replace('\\', "/"); + let shown = || name.chars().take(200).collect::<String>(); + if unix.starts_with('/') || unix.contains('\0') { + return Err(ZipError::Unsafe(shown())); + } + let mut parts = Vec::new(); + for part in unix.split('/') { + match part { + "" | "." => {} + ".." => return Err(ZipError::Unsafe(shown())), + // `C:`, `C:x`: a drive. + p if parts.is_empty() && p.contains(':') => return Err(ZipError::Unsafe(shown())), + p => parts.push(p), + } + } + if parts.len() > MAX_DEPTH + 1 { + return Err(ZipError::TooDeep(shown())); + } + Ok(parts.join("/")) +} + +fn method_name(method: u16) -> &'static str { + match method { + 9 => "Deflate64 compression", + 12 => "bzip2 compression", + 14 => "LZMA compression", + 93 => "Zstandard compression", + 95 => "XZ compression", + 99 => "AES encryption", + _ => "an unknown compression method", + } +} + +/// The end of the central directory: (entry count, its size, its offset, where it must end). +/// +/// For a self-extracting archive, the record's offsets may be relative to the ZIP data rather +/// than the start of the executable. The returned directory offset stays as written; its real +/// location is resolved against `dir_limit` when opening the archive. +fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { + // The end record is in the last 22 + 65535 bytes (it may carry a comment). + let lo = data.len().saturating_sub(22 + 65_535); + let mut eocd = None; + // A shifted empty SFX archive has no central-directory signature with which to distinguish + // it from an empty EOCD-shaped record inside the preceding archive's comment. Keep it as a + // last resort while searching for an older, structurally stronger candidate. + let mut empty_sfx = None; + let mut fallback = None; + // Fake EOCD records in a comment can all describe the same large directory. Cache binary + // directory jumps so checking each candidate does not rescan every entry. + let mut directory_jumps = HashMap::new(); + for candidate in (lo..data.len().saturating_sub(21)).rev() { + if u32_at(data, candidate) != Some(END) + || !u16_at(data, candidate + 20) + .is_some_and(|comment| candidate.checked_add(22 + usize::from(comment)).is_some_and(|end| end <= data.len())) + { + continue; + } + // Keep the earliest bounds-valid candidate's eventual parse error if no structurally + // consistent candidate is found. This preserves useful damaged-ZIP diagnostics. + fallback = Some(candidate); + + let count = u16_at(data, candidate + 10).unwrap_or(u16::MAX); + let size = u32_at(data, candidate + 12).unwrap_or(u32::MAX); + let offset = u32_at(data, candidate + 16).unwrap_or(u32::MAX); + if count == u16::MAX || size == u32::MAX || offset == u32::MAX { + let locator = candidate.checked_sub(20).filter(|&at| u32_at(data, at) == Some(LOCATOR64)); + let valid = locator.and_then(|locator| find_zip64_end(data, locator)).and_then(|at| { + let count = u64_at(data, at + 32)?; + let dir_size = u64_at(data, at + 40)?; + let dir_offset = u64_at(data, at + 48)?; + locate_directory(data, count, dir_size, dir_offset, at) + .filter(|&(dir, _)| directory_is_exact(data, dir, dir_size, count, &mut directory_jumps)) + .map(|(_, shift)| (at, count == 0 && shift > 0)) + }); + let Some((_, shifted_empty)) = valid else { + continue; + }; + if shifted_empty { + empty_sfx = Some(candidate); + continue; + } + } else { + let Some((_, shift)) = locate_directory(data, count.into(), size.into(), offset.into(), candidate) + .filter(|&(dir, _)| directory_is_exact(data, dir, size.into(), count.into(), &mut directory_jumps)) + else { + continue; + }; + if count == 0 && shift > 0 { + empty_sfx = Some(candidate); + continue; + } + } + eocd = Some(candidate); + break; + } + let eocd = eocd.or(empty_sfx).or(fallback).ok_or(ZipError::NotZip)?; + let field16 = |o: usize| u16_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short")); + let field32 = |o: usize| u32_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short")); + let (disk, dir_disk, on_disk, count) = (field16(4)?, field16(6)?, field16(8)?, field16(10)?); + let (size, offset) = (field32(12)?, field32(16)?); + if count != 0xffff && size != 0xffff_ffff && offset != 0xffff_ffff { + if disk != 0 || dir_disk != 0 || on_disk != count { + return Err(ZipError::UnsupportedArchive("split across several files")); + } + return Ok((count.into(), size.into(), offset.into(), eocd)); + } + // ZIP64: a locator just before the end record points at the ZIP64 end record. + let locator = eocd.checked_sub(20).filter(|&l| u32_at(data, l) == Some(LOCATOR64)).ok_or(ZipError::Damaged("the ZIP64 end record is missing"))?; + let missing = ZipError::Damaged("the ZIP64 end record is missing"); + let at = find_zip64_end(data, locator).ok_or(missing)?; + let cut = ZipError::Damaged("the ZIP64 end record is cut short"); + let (disk, dir_disk) = (u32_at(data, at + 16).ok_or(cut.clone())?, u32_at(data, at + 20).ok_or(cut.clone())?); + let (on_disk, count) = (u64_at(data, at + 24).ok_or(cut.clone())?, u64_at(data, at + 32).ok_or(cut.clone())?); + if disk != 0 || dir_disk != 0 || on_disk != count { + return Err(ZipError::UnsupportedArchive("split across several files")); + } + Ok((count, u64_at(data, at + 40).ok_or(cut.clone())?, u64_at(data, at + 48).ok_or(cut)?, at)) +} + +/// Finds the ZIP64 end record named by `locator`. For an SFX archive with unadjusted offsets, +/// the locator points to where that record was before the stub was prepended, so the record +/// itself immediately before the locator is authoritative. The shifted fallback supports the +/// no-extensible-data layout; ordinary ZIP64 records continue to use the locator's exact offset. +fn find_zip64_end(data: &[u8], locator: usize) -> Option<usize> { + let stated = usize::try_from(u64_at(data, locator.checked_add(8)?)?).ok()?; + let valid = |at: usize, shifted: bool| { + if u32_at(data, at) != Some(END64) { + return false; + } + let Some(record_size_at) = at.checked_add(4) else { return false }; + let Some(record_size) = u64_at(data, record_size_at).and_then(|n| usize::try_from(n).ok()) else { return false }; + if at.checked_add(12).and_then(|start| start.checked_add(record_size)) != Some(locator) || (shifted && record_size != 44) { + return false; + } + let Some(size_at) = at.checked_add(40) else { return false }; + let Some(offset_at) = at.checked_add(48) else { return false }; + let Some(size) = u64_at(data, size_at).and_then(|n| usize::try_from(n).ok()) else { return false }; + let Some(offset) = u64_at(data, offset_at).and_then(|n| usize::try_from(n).ok()) else { return false }; + if !shifted { + offset.checked_add(size) == Some(at) + } else { + let empty_directory = size == 0 && u64_at(data, at + 24) == Some(0) && u64_at(data, at + 32) == Some(0); + at > stated + && offset.checked_add(size) == Some(stated) + && at.checked_sub(size).is_some_and(|dir| dir > offset && (empty_directory || u32_at(data, dir) == Some(CENTRAL))) + } + }; + if valid(stated, false) { + return Some(stated); + } + let at = locator.checked_sub(56).filter(|&at| at > stated)?; + valid(at, true).then_some(at) +} + +/// Resolves a directory offset. If the stated offset already points to a central-directory +/// header and the directory ends at `limit`, it is used as is. Otherwise the only correction +/// accepted is a prefix shift that moves the directory to immediately before `limit`. +fn locate_directory(data: &[u8], count: u64, size: u64, stated: u64, limit: usize) -> Option<(usize, usize)> { + let stated = usize::try_from(stated).ok()?; + let size = usize::try_from(size).ok()?; + if stated.checked_add(size) == Some(limit) && (count == 0 || u32_at(data, stated) == Some(CENTRAL)) { + return Some((stated, 0)); + } + let actual = limit.checked_sub(size)?; + if actual > stated && (count == 0 || u32_at(data, actual) == Some(CENTRAL)) { + return Some((actual, actual - stated)); + } + None +} + +fn central_entry_end(data: &[u8], cursor: usize) -> Option<usize> { + if u32_at(data, cursor) != Some(CENTRAL) { + return None; + } + let header_end = cursor.checked_add(46).filter(|&at| at <= data.len())?; + let name_len = usize::from(u16_at(data, header_end - 18)?); + let extra_len = usize::from(u16_at(data, header_end - 16)?); + let comment_len = usize::from(u16_at(data, header_end - 14)?); + header_end.checked_add(name_len)?.checked_add(extra_len)?.checked_add(comment_len).filter(|&end| end <= data.len()) +} + +/// Return the offset after `2^power` contiguous central-directory records, memoizing offsets +/// shared by competing EOCD candidates in untrusted comments. +fn central_directory_jump(data: &[u8], start: usize, power: u8, jumps: &mut HashMap<(usize, u8), Option<usize>>) -> Option<usize> { + if let Some(&cached) = jumps.get(&(start, power)) { + return cached; + } + let end = if power == 0 { + central_entry_end(data, start) + } else { + central_directory_jump(data, start, power - 1, jumps).and_then(|middle| central_directory_jump(data, middle, power - 1, jumps)) + }; + jumps.insert((start, power), end); + end +} + +/// Checks that the declared central-directory entries consume the entire directory. This is +/// used while choosing among EOCD-shaped signatures, where comments may contain many fake records. +fn directory_is_exact(data: &[u8], start: usize, size: u64, count: u64, jumps: &mut HashMap<(usize, u8), Option<usize>>) -> bool { + let Ok(size) = usize::try_from(size) else { return false }; + let Some(end) = start.checked_add(size).filter(|&end| end <= data.len()) else { return false }; + // Preserve the existing TooMany diagnostic in `Archive::open` without walking attacker-sized + // entry counts here. + if count > MAX_ENTRIES as u64 { + return true; + } + let mut cursor = start; + let mut remaining = count; + let mut power = 0; + while remaining != 0 { + if remaining & 1 != 0 { + let Some(next) = central_directory_jump(data, cursor, power, jumps) else { + return false; + }; + cursor = next; + } + remaining >>= 1; + power += 1; + } + cursor == end +} + +impl<'a> Archive<'a> { + pub fn open(data: &'a [u8]) -> Result<Archive<'a>, ZipError> { + let (count, dir_size, dir_at, dir_limit) = find_end(data)?; + let past = ZipError::Damaged("the central directory is outside the archive"); + let (dir_at, shift) = locate_directory(data, count, dir_size, dir_at, dir_limit).ok_or(past.clone())?; + let dir_end = usize::try_from(dir_size).ok().and_then(|s| dir_at.checked_add(s)).filter(|&e| e <= dir_limit).ok_or(past.clone())?; + let dir = data.get(dir_at..dir_end).ok_or(past)?; + if count > MAX_ENTRIES as u64 { + return Err(ZipError::TooMany); + } + let count = count as usize; + // Every central entry is at least 46 bytes. + let cut = ZipError::Damaged("the central directory is cut short"); + if count.saturating_mul(46) > dir.len() { + return Err(cut); + } + let mut entries = HashMap::with_capacity(count); + let mut folders = 0; + // (start, end, name) of every entry's local header and data. + let mut spans: Vec<(usize, usize, String)> = Vec::with_capacity(count); + let mut i = 0usize; + for _ in 0..count { + if u32_at(dir, i) != Some(CENTRAL) { + return Err(cut); + } + let short = |o: usize| u16_at(dir, i + o).ok_or(cut.clone()); + let long = |o: usize| u32_at(dir, i + o).ok_or(cut.clone()); + let (flags, method) = (short(8)?, short(10)?); + let crc = long(16)?; + let (comp32, size32, offset32) = (long(20)?, long(24)?, long(42)?); + let (nlen, xlen, clen) = (short(28)? as usize, short(30)? as usize, short(32)? as usize); + let raw_name = get(dir, i + 46, nlen).ok_or(cut.clone())?; + let extra = get(dir, i + 46 + nlen, xlen).ok_or(cut.clone())?; + get(dir, i + 46 + nlen + xlen, clen).ok_or(cut.clone())?; + i += 46 + nlen + xlen + clen; + + let name = decode_name(raw_name, flags & 0x0800 != 0, extra)?; + let shown = || name.chars().take(200).collect::<String>(); + // ZIP64: each 32-bit field that overflowed is in the extra field, in this order. + let (mut size, mut comp, mut offset) = (u64::from(size32), u64::from(comp32), u64::from(offset32)); + if size32 == u32::MAX || comp32 == u32::MAX || offset32 == u32::MAX { + let z = extra_field(extra, 0x0001).ok_or_else(|| ZipError::DamagedEntry(shown(), "has no ZIP64 sizes"))?; + let mut at = 0; + for (wide, value) in [(size32, &mut size), (comp32, &mut comp), (offset32, &mut offset)] { + if wide == u32::MAX { + *value = u64_at(z, at).ok_or_else(|| ZipError::DamagedEntry(shown(), "has its ZIP64 sizes cut short"))?; + at += 8; + } + } + } + let outside = || ZipError::DamagedEntry(shown(), "is outside the archive"); + let offset = usize::try_from(offset).ok().and_then(|offset| offset.checked_add(shift)).ok_or_else(outside)?; + let comp = usize::try_from(comp).map_err(|_| outside())?; + // An entry's size is checked when it is read: one too large to read may sit unused. + let size = usize::try_from(size).unwrap_or(usize::MAX); + + // Its local header, then its data, all before the central directory. + if u32_at(data, offset) != Some(LOCAL) { + return Err(ZipError::DamagedEntry(shown(), "has no local header")); + } + let lnlen = u16_at(data, offset + 26).ok_or_else(outside)? as usize; + let lxlen = u16_at(data, offset + 28).ok_or_else(outside)? as usize; + let start = offset + 30 + lnlen + lxlen; + let end = start.checked_add(comp).filter(|&e| e <= dir_at).ok_or_else(outside)?; + spans.push((offset, end, shown())); + + let folder = name.ends_with('/') || name.ends_with('\\'); + let path = clean_path(&name)?; + if folder || path.is_empty() { + if size != 0 || comp > 2 { + return Err(ZipError::DamagedEntry(shown(), "is a folder with data")); + } + folders += 1; + continue; + } + if method == 8 && size as u64 > (comp as u64).saturating_mul(MAX_RATIO).saturating_add(4096) { + return Err(ZipError::Bomb(shown())); + } + if method == 0 && flags & 0x41 == 0 && size != comp { + return Err(ZipError::DamagedEntry(shown(), "is stored with two different sizes")); + } + if entries.insert(path, Entry { method, flags, crc, comp, size, data: start }).is_some() { + return Err(ZipError::Duplicate(shown())); + } + } + if i != dir.len() { + return Err(ZipError::Damaged("the central directory has trailing data")); + } + // No two entries may share bytes (the overlapping-entries zip bomb). + spans.sort_unstable_by_key(|s| s.0); + if let Some(w) = spans.windows(2).find(|w| w[0].1 > w[1].0) { + return Err(ZipError::Overlap(w[0].2.clone(), w[1].2.clone())); + } + Ok(Archive { data, entries, folders, budget: Cell::new(MAX_TOTAL) }) + } + + /// The files' paths (`/`-separated, folders left out). + pub fn names(&self) -> impl Iterator<Item = &str> { + self.entries.keys().map(String::as_str) + } + + /// Selects the package root from XFL document paths. A root-level document takes precedence; + /// otherwise only a single-level folder is eligible, with macOS metadata excluded. + pub fn xfl_package_root(&self) -> XflPackageRoot<'_> { + if self.entries.contains_key("DOMDocument.xml") { + return XflPackageRoot::Document; + } + let mut folders: Vec<&str> = self + .names() + .filter_map(|name| name.strip_suffix("/DOMDocument.xml")) + .filter(|folder| !folder.contains('/') && *folder != "__MACOSX") + .collect(); + folders.sort_unstable(); + match folders.as_slice() { + [] => XflPackageRoot::Missing, + [folder] => XflPackageRoot::Folder(folder), + _ => XflPackageRoot::Multiple(folders), + } + } + + /// How many files and folder entries the archive lists. + pub fn counts(&self) -> (usize, usize) { + (self.entries.len(), self.folders) + } + + /// The bytes of entry `name` (path inside the archive, `/`-separated), checked against + /// its size and checksum. + pub fn read(&self, name: &str) -> Result<Option<Vec<u8>>, ZipError> { + let Some(e) = self.entries.get(name) else { return Ok(None) }; + if e.flags & 0x41 != 0 { + return Err(ZipError::Unsupported(name.into(), "encryption")); + } + if !matches!(e.method, 0 | 8) { + return Err(ZipError::Unsupported(name.into(), method_name(e.method))); + } + if e.size > MAX_ENTRY || e.comp > MAX_ENTRY { + return Err(ZipError::TooLarge(name.into())); + } + let left = self.budget.get(); + if e.size as u64 > left { + return Err(ZipError::TooMuch); + } + let raw = get(self.data, e.data, e.comp).ok_or_else(|| ZipError::DamagedEntry(name.into(), "is outside the archive"))?; + let out = match e.method { + 0 => raw.to_vec(), + _ => miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.max(1)).map_err(|err| { + let why = if err.status == miniz_oxide::inflate::TINFLStatus::HasMoreOutput { + "expands past the size it gives" + } else { + "has damaged compressed data" + }; + ZipError::DamagedEntry(name.into(), why) + })?, + }; + if out.len() != e.size { + return Err(ZipError::DamagedEntry(name.into(), "is not the size it gives")); + } + if crc32(&out) != e.crc { + return Err(ZipError::DamagedEntry(name.into(), "fails its checksum")); + } + self.budget.set(left - e.size as u64); + Ok(Some(out)) + } +} + +#[cfg(test)] +#[path = "../tests/support/fla.rs"] +pub(crate) mod pack; + +#[cfg(test)] +#[path = "tests.rs"] +mod tests; diff --git a/crates/xfl/src/media.rs b/crates/xfl/src/media.rs new file mode 100644 index 000000000..a501e7888 --- /dev/null +++ b/crates/xfl/src/media.rs @@ -0,0 +1,190 @@ +//! Borrowed views of XFL's bitmap, sound, and video library-item records. +//! +//! These views expose native XFL metadata and archive member names. Decoding those bytes and +//! mapping the records into an application's media model remain consumer responsibilities. + +use crate::shape::XflElement; + +/// Archive member named by a library item's native `href` attribute. +pub fn library_member(href: &str) -> String { + format!("LIBRARY/{href}") +} + +/// Archive member named by an XFL item's native `*DataHRef` attribute. +pub fn data_member(href: &str) -> String { + format!("bin/{href}") +} + +/// A packaged `./...` external video source, normalized to ZIP's slash separators. +pub fn packaged_external_member(path: &str) -> Option<String> { + path.strip_prefix("./").map(|path| path.replace('\\', "/")) +} + +/// Media library records in an XFL document, in source order. +#[derive(Clone, Copy, Debug)] +pub struct Catalog<'a, E: XflElement> { + media: Option<&'a E>, +} + +impl<'a, E: XflElement> Catalog<'a, E> { + pub fn new(document: &'a E) -> Self { + Self { media: document.child("media") } + } + + pub fn bitmaps(&self) -> impl Iterator<Item = Bitmap<'a, E>> + 'a { + let media = self.media; + media.into_iter().flat_map(|media| media.elements_named("DOMBitmapItem")).map(|element| Bitmap { element }) + } + + pub fn sounds(&self) -> impl Iterator<Item = Sound<'a, E>> + 'a { + let media = self.media; + media.into_iter().flat_map(|media| media.elements_named("DOMSoundItem")).map(|element| Sound { element }) + } + + pub fn videos(&self) -> impl Iterator<Item = Video<'a, E>> + 'a { + let media = self.media; + media.into_iter().flat_map(|media| media.elements_named("DOMVideoItem")).map(|element| Video { element }) + } +} + +/// Native bitmap library metadata. +#[derive(Clone, Copy, Debug)] +pub struct Bitmap<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Bitmap<'a, E> { + pub fn name(&self) -> Option<&'a str> { + self.element.attr("name") + } + + pub fn href(&self) -> Option<&'a str> { + self.element.attr("href") + } + + pub fn data_href(&self) -> Option<&'a str> { + self.element.attr("bitmapDataHRef") + } + + pub fn allow_smoothing(&self) -> Option<bool> { + self.element.attr("allowSmoothing").map(|value| value.trim() == "true") + } +} + +/// Native sound library metadata. +#[derive(Clone, Copy, Debug)] +pub struct Sound<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Sound<'a, E> { + pub fn name(&self) -> Option<&'a str> { + self.element.attr("name") + } + + pub fn href(&self) -> Option<&'a str> { + self.element.attr("href") + } + + pub fn data_href(&self) -> Option<&'a str> { + self.element.attr("soundDataHRef") + } +} + +/// Native video library metadata. +#[derive(Clone, Copy, Debug)] +pub struct Video<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Video<'a, E> { + pub fn name(&self) -> Option<&'a str> { + self.element.attr("name") + } + + pub fn href(&self) -> Option<&'a str> { + self.element.attr("href") + } + + pub fn external_path(&self) -> Option<&'a str> { + self.element.attr("sourceExternalFilepath") + } + + pub fn data_href(&self) -> Option<&'a str> { + self.element.attr("videoDataHRef") + } + + pub fn length(&self) -> Option<f32> { + number(self.element, "length") + } + + pub fn frame_count(&self) -> Option<f32> { + number(self.element, "frameCount") + } + + pub fn frames_per_second(&self) -> Option<f32> { + number(self.element, "fps") + } +} + +fn number(element: &impl XflElement, name: &str) -> Option<f32> { + element.attr(name)?.trim().parse::<f32>().ok().filter(|value| value.is_finite()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::Options::default().parse(source).unwrap() + } + + #[test] + fn reads_native_media_metadata_in_order_and_ignores_other_records() { + let root = parse( + br#"<DOMDocument><media> + <DOMBitmapItem name="folder/a" href="a.png" bitmapDataHRef="Bitmap 1" allowSmoothing="false"/> + <DOMSoundItem name="s" href="s.wav" soundDataHRef="Sound 1"/> + <DOMVideoItem name="v" sourceExternalFilepath="./LIBRARY/v.flv" videoDataHRef="Video 1" length="3.5" frameCount="70" fps="20"/> + <Other name="ignored"/> + <DOMBitmapItem name="b"/> + </media></DOMDocument>"#, + ); + let catalog = Catalog::new(&root); + let bitmaps: Vec<_> = catalog.bitmaps().collect(); + assert_eq!(bitmaps.len(), 2); + assert_eq!(bitmaps[0].name(), Some("folder/a")); + assert_eq!(bitmaps[0].href(), Some("a.png")); + assert_eq!(bitmaps[0].data_href(), Some("Bitmap 1")); + assert_eq!(bitmaps[0].allow_smoothing(), Some(false)); + assert_eq!( + catalog.sounds().next().map(|item| (item.name(), item.href(), item.data_href())), + Some((Some("s"), Some("s.wav"), Some("Sound 1"))) + ); + let video = catalog.videos().next().expect("video record"); + assert_eq!(video.external_path(), Some("./LIBRARY/v.flv")); + assert_eq!(video.data_href(), Some("Video 1")); + assert_eq!(video.length(), Some(3.5)); + assert_eq!(video.frame_count(), Some(70.0)); + assert_eq!(video.frames_per_second(), Some(20.0)); + } + + #[test] + fn missing_or_invalid_media_metadata_stays_optional() { + let root = parse(br#"<DOMDocument><media><DOMVideoItem name="v" length="NaN" fps="?"/></media></DOMDocument>"#); + let video = Catalog::new(&root).videos().next().expect("video record"); + assert_eq!(video.name(), Some("v")); + assert_eq!(video.length(), None); + assert_eq!(video.frames_per_second(), None); + let empty = parse(b"<DOMDocument/>"); + assert_eq!(Catalog::new(&empty).bitmaps().count(), 0); + } + + #[test] + fn native_media_references_resolve_to_the_legacy_archive_members() { + assert_eq!(library_member("folder/a.png"), "LIBRARY/folder/a.png"); + assert_eq!(data_member("Bitmap 1"), "bin/Bitmap 1"); + assert_eq!(packaged_external_member("./LIBRARY\\v.flv").as_deref(), Some("LIBRARY/v.flv")); + assert_eq!(packaged_external_member("/outside/v.flv"), None); + } +} diff --git a/crates/xfl/src/shape.rs b/crates/xfl/src/shape.rs new file mode 100644 index 000000000..173359a52 --- /dev/null +++ b/crates/xfl/src/shape.rs @@ -0,0 +1,675 @@ +//! Borrowed views of native XFL shape and style elements. +//! +//! These views recognize XFL's element names and attribute grammar without depending on an +//! application's geometry, paint, or animation types. They work with `craft_xml::El` and with +//! compatible borrowed element adapters implemented by consumers. + +use crate::edges::{self, Segment}; +use std::borrow::Cow; + +/// An element source used by the borrowed XFL schema views. +/// +/// Consumers with an existing XML facade can implement this small interface and use the same +/// XFL parser without converting or reparsing their tree. Attribute lookup must return the last +/// occurrence when an XML document repeats an attribute, matching the native XFL reader's +/// historical behavior. +pub trait XflElement { + /// Iterator type for direct child elements. + type Elements<'a>: Iterator<Item = &'a Self> + where + Self: 'a; + + /// The element's local name, with any namespace prefix removed. + fn local_name(&self) -> &str; + + /// The last attribute with this exact name. + fn attr(&self, name: &str) -> Option<&str>; + + /// Direct child elements in document order. + fn elements(&self) -> Self::Elements<'_>; + + /// This element's direct character data, with XML references resolved. + fn text_content(&self) -> Cow<'_, str>; + + /// The first direct child whose local name matches. + fn child(&self, name: &str) -> Option<&Self> { + self.elements().find(|element| element.local_name() == name) + } + + /// Direct children whose local name matches, in document order. + fn elements_named<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Self> + 'a { + self.elements().filter(move |element| element.local_name() == name) + } +} + +/// Direct child elements of `craft_xml::El`, used by its `XflElement` implementation. +pub struct XmlElements<'a> { + nodes: std::slice::Iter<'a, craft_xml::Node>, +} + +impl<'a> Iterator for XmlElements<'a> { + type Item = &'a craft_xml::El; + + fn next(&mut self) -> Option<Self::Item> { + self.nodes.find_map(|node| match node { + craft_xml::Node::El(element) => Some(element), + _ => None, + }) + } +} + +impl XflElement for craft_xml::El { + type Elements<'a> = XmlElements<'a>; + + fn local_name(&self) -> &str { + self.name.rsplit(':').next().unwrap_or(&self.name) + } + + fn attr(&self, name: &str) -> Option<&str> { + self.attrs.iter().rev().find(|(key, _)| key == name).map(|(_, value)| value.as_str()) + } + + fn elements(&self) -> Self::Elements<'_> { + XmlElements { nodes: self.children.iter() } + } + + fn text_content(&self) -> Cow<'_, str> { + self.text() + } +} + +/// XFL matrix coefficients, in the native units stored in XML. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Matrix { + pub a: f32, + pub b: f32, + pub c: f32, + pub d: f32, + pub tx: f32, + pub ty: f32, +} + +/// A color encoded by an XFL color attribute and its optional alpha attribute. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Color { + pub rgb: u32, + pub alpha: f32, +} + +/// A native XFL instance color record (`<color><Color .../></color>`). +/// +/// The view parses the authored tint, brightness, channel multipliers and offsets but does not +/// choose a consumer's color-effect style or clamp values into an application's model. Offsets +/// remain in XFL's native 0–255 scale. Invalid or non-finite channel multipliers use 1, and +/// invalid or non-finite offsets use 0, matching the historical AniCraft importer. +#[derive(Clone, Copy, Debug)] +pub struct NativeColorEffect<'a, E: XflElement> { + element: &'a E, +} + +impl Matrix { + /// The matrix used when an XFL element omits its transform. + pub const IDENTITY: Matrix = Matrix { a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0 }; +} + +impl<'a, E: XflElement> NativeColorEffect<'a, E> { + /// Views a native XFL `Color` element without converting it to an application's model. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + /// The native tint amount, when authored. + pub fn tint_multiplier(&self) -> Option<f32> { + number(self.element, "tintMultiplier") + } + + /// The native tint color. Missing or malformed color values use black as other XFL colors do. + pub fn tint_color(&self) -> Color { + color(self.element, "tintColor", "__none") + } + + /// The native brightness value, when authored. + pub fn brightness(&self) -> Option<f32> { + number(self.element, "brightness") + } + + /// Red, green, blue, and alpha multipliers, with identity defaults for absent or invalid data. + pub fn multipliers(&self) -> [f32; 4] { + ["redMultiplier", "greenMultiplier", "blueMultiplier", "alphaMultiplier"].map(|name| number(self.element, name).unwrap_or(1.0)) + } + + /// Red, green, blue, and alpha offsets in XFL's native 0–255 scale. + pub fn offsets(&self) -> [f32; 4] { + ["redOffset", "greenOffset", "blueOffset", "alphaOffset"].map(|name| number(self.element, name).unwrap_or(0.0)) + } +} + +pub(crate) fn number(element: &impl XflElement, name: &str) -> Option<f32> { + element.attr(name)?.trim().parse::<f32>().ok().filter(|value| value.is_finite()) +} + +pub(crate) fn integer(element: &impl XflElement, name: &str) -> Option<u32> { + element.attr(name)?.trim().parse::<u32>().ok() +} + +pub(crate) fn boolean(element: &impl XflElement, name: &str) -> Option<bool> { + element.attr(name).map(|value| value.trim() == "true") +} + +/// Parses XFL's hexadecimal color and alpha attributes. Missing or malformed colors use black; +/// missing, malformed, or non-finite alpha uses full opacity, matching the legacy importer. +pub fn color(element: &impl XflElement, color_attribute: &str, alpha_attribute: &str) -> Color { + color_from_attributes(element.attr(color_attribute), element.attr(alpha_attribute)) +} + +/// Parses native color and alpha strings after a consumer has read them from its own element +/// adapter. This keeps wire-value interpretation shared even when an application already has a +/// borrowed schema view for the containing element. +pub fn color_from_attributes(color: Option<&str>, alpha: Option<&str>) -> Color { + let rgb = color.and_then(|value| u32::from_str_radix(value.trim().trim_start_matches('#'), 16).ok()).unwrap_or(0); + let alpha = alpha.and_then(|value| value.trim().parse::<f32>().ok()).filter(|value| value.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0); + Color { rgb, alpha } +} + +/// Reads the native `<matrix><Matrix .../></matrix>` transform. +/// +/// Each absent, malformed, or non-finite coefficient uses its identity default independently. +/// This preserves the prior AniCraft reader's `Element::f32` behavior, including retaining other +/// valid coefficients when one coefficient is invalid. +pub fn matrix(element: &impl XflElement) -> Matrix { + let Some(matrix) = element.child("matrix").and_then(|wrapper| wrapper.child("Matrix")) else { + return Matrix::IDENTITY; + }; + Matrix { + a: number(matrix, "a").unwrap_or(1.0), + b: number(matrix, "b").unwrap_or(0.0), + c: number(matrix, "c").unwrap_or(0.0), + d: number(matrix, "d").unwrap_or(1.0), + tx: number(matrix, "tx").unwrap_or(0.0), + ty: number(matrix, "ty").unwrap_or(0.0), + } +} + +/// A native `DOMShape` or drawing shape and its XFL style tables. +#[derive(Clone, Copy, Debug)] +pub struct Shape<'a, E: XflElement> { + element: &'a E, +} + +/// Kind of native drawable primitive stored in XFL. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PrimitiveKind { + Rectangle, + Oval, +} + +/// Native rectangle or oval object, including its native style definitions. +#[derive(Clone, Copy, Debug)] +pub struct Primitive<'a, E: XflElement> { + element: &'a E, + kind: PrimitiveKind, +} + +impl<'a, E: XflElement> Primitive<'a, E> { + /// Views a supported native primitive by its local element name. + pub fn new(element: &'a E) -> Option<Self> { + let kind = match element.local_name() { + "DOMRectangleObject" => PrimitiveKind::Rectangle, + "DOMOvalObject" => PrimitiveKind::Oval, + _ => return None, + }; + Some(Self { element, kind }) + } + + pub fn kind(&self) -> PrimitiveKind { + self.kind + } + + pub fn x(&self) -> Option<f32> { + number(self.element, "x") + } + + pub fn y(&self) -> Option<f32> { + number(self.element, "y") + } + + pub fn width(&self) -> Option<f32> { + number(self.element, "objectWidth") + } + + pub fn height(&self) -> Option<f32> { + number(self.element, "objectHeight") + } + + pub fn top_left_radius(&self) -> Option<f32> { + number(self.element, "topLeftRadius") + } + + pub fn matrix(&self) -> Matrix { + matrix(self.element) + } + + pub fn fill(&self) -> Option<Fill<'_, E>> { + self.element.child("fill")?.elements().next().map(|element| Fill { element }) + } + + pub fn stroke(&self) -> Option<Stroke<'_, E>> { + self.element.child("stroke")?.elements().next().map(|element| Stroke { element }) + } +} + +impl<'a, E: XflElement> Shape<'a, E> { + /// Views an element as an XFL shape when its local name is `DOMShape`. + pub fn new(element: &'a E) -> Option<Self> { + (element.local_name() == "DOMShape").then_some(Self { element }) + } + + /// Native shape transform. + pub fn matrix(&self) -> Matrix { + matrix(self.element) + } + + /// Whether Animate stores the shape as a drawing object. + pub fn is_drawing_object(&self) -> Option<bool> { + boolean(self.element, "isDrawingObject") + } + + /// Fill styles, preserving their native order and index values. + pub fn fills(&self) -> impl Iterator<Item = FillStyle<'_, E>> + '_ { + self.element.child("fills").into_iter().flat_map(|table| table.elements()).map(|element| FillStyle { element }) + } + + /// Stroke styles, preserving their native order and index values. + pub fn strokes(&self) -> impl Iterator<Item = StrokeStyle<'_, E>> + '_ { + self.element.child("strokes").into_iter().flat_map(|table| table.elements()).map(|element| StrokeStyle { element }) + } + + /// Native edge records, preserving malformed and unknown data for consumer policy. + pub fn edges(&self) -> impl Iterator<Item = Edge<'_, E>> + '_ { + self.element.child("edges").into_iter().flat_map(|table| table.elements_named("Edge")).map(|element| Edge { element }) + } +} + +/// A native `FillStyle` entry. +#[derive(Clone, Copy, Debug)] +pub struct FillStyle<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> FillStyle<'a, E> { + pub fn index(&self) -> Option<u32> { + integer(self.element, "index") + } + + /// The first native definition element inside this table entry. + pub fn definition(&self) -> Option<Fill<'_, E>> { + self.element.elements().next().map(|element| Fill { element }) + } +} + +/// Native fill definitions understood by XFL. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FillKind { + SolidColor, + LinearGradient, + RadialGradient, + Bitmap, + Other, +} + +/// A native XFL fill definition. +#[derive(Clone, Copy, Debug)] +pub struct Fill<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Fill<'a, E> { + /// Views any native fill-definition element, including fills nested in primitives or strokes. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + /// Underlying native definition element for consumers that map it into application types. + pub fn element(&self) -> &'a E { + self.element + } + + pub fn kind(&self) -> FillKind { + match self.element.local_name() { + "SolidColor" => FillKind::SolidColor, + "LinearGradient" => FillKind::LinearGradient, + "RadialGradient" => FillKind::RadialGradient, + "BitmapFill" => FillKind::Bitmap, + _ => FillKind::Other, + } + } + + pub fn color(&self) -> Option<&str> { + self.element.attr("color") + } + + pub fn color_value(&self) -> Color { + color(self.element, "color", "alpha") + } + + pub fn alpha(&self) -> Option<f32> { + number(self.element, "alpha") + } + + pub fn matrix(&self) -> Matrix { + matrix(self.element) + } + + pub fn spread_method(&self) -> Option<&str> { + self.element.attr("spreadMethod") + } + + pub fn interpolation_method(&self) -> Option<&str> { + self.element.attr("interpolationMethod") + } + + pub fn focal_point_ratio(&self) -> Option<f32> { + number(self.element, "focalPointRatio") + } + + pub fn bitmap_path(&self) -> Option<&str> { + self.element.attr("bitmapPath") + } + + pub fn bitmap_is_clipped(&self) -> Option<bool> { + boolean(self.element, "bitmapIsClipped") + } + + /// Gradient entries, preserving source order and raw native ratios. + pub fn gradient_entries(&self) -> impl Iterator<Item = GradientEntry<'_, E>> + '_ { + self.element.elements_named("GradientEntry").map(|element| GradientEntry { element }) + } +} + +/// A native gradient ramp entry. +#[derive(Clone, Copy, Debug)] +pub struct GradientEntry<'a, E: XflElement> { + element: &'a E, +} + +impl<E: XflElement> GradientEntry<'_, E> { + pub fn ratio(&self) -> Option<f32> { + number(self.element, "ratio") + } + + pub fn color(&self) -> Option<&str> { + self.element.attr("color") + } + + pub fn color_value(&self) -> Color { + color(self.element, "color", "alpha") + } + + pub fn alpha(&self) -> Option<f32> { + number(self.element, "alpha") + } +} + +/// Native stroke definitions understood by XFL. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StrokeKind { + Solid, + Dashed, + Dotted, + Ragged, + Stipple, + Hatched, + Other, +} + +/// A native `StrokeStyle` table entry. +#[derive(Clone, Copy, Debug)] +pub struct StrokeStyle<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> StrokeStyle<'a, E> { + pub fn index(&self) -> Option<u32> { + integer(self.element, "index") + } + + /// The first native definition element inside this table entry. + pub fn definition(&self) -> Option<Stroke<'_, E>> { + self.element.elements().next().map(|element| Stroke { element }) + } +} + +/// A native XFL stroke definition. +#[derive(Clone, Copy, Debug)] +pub struct Stroke<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Stroke<'a, E> { + /// Views a native stroke-definition element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + /// Underlying native definition element for consumers that map it into application types. + pub fn element(&self) -> &'a E { + self.element + } + + pub fn kind(&self) -> StrokeKind { + match self.element.local_name() { + "SolidStroke" => StrokeKind::Solid, + "DashedStroke" => StrokeKind::Dashed, + "DottedStroke" => StrokeKind::Dotted, + "RaggedStroke" => StrokeKind::Ragged, + "StippleStroke" => StrokeKind::Stipple, + "HatchedStroke" => StrokeKind::Hatched, + _ => StrokeKind::Other, + } + } + + pub fn weight(&self) -> Option<f32> { + number(self.element, "weight") + } + + pub fn caps(&self) -> Option<&str> { + self.element.attr("caps") + } + + pub fn joints(&self) -> Option<&str> { + self.element.attr("joints") + } + + pub fn miter_limit(&self) -> Option<f32> { + number(self.element, "miterLimit") + } + + pub fn dash1(&self) -> Option<f32> { + number(self.element, "dash1") + } + + pub fn dash2(&self) -> Option<f32> { + number(self.element, "dash2") + } + + pub fn dot_space(&self) -> Option<f32> { + number(self.element, "dotSpace") + } + + /// The first fill definition nested in the stroke. + pub fn fill(&self) -> Option<Fill<'_, E>> { + self.element.child("fill")?.elements().next().map(|element| Fill { element }) + } +} + +/// A native `<Edge>` record and its style indices. +#[derive(Clone, Copy, Debug)] +pub struct Edge<'a, E: XflElement> { + element: &'a E, +} + +impl<E: XflElement> Edge<'_, E> { + pub fn fill_style0(&self) -> Option<u32> { + integer(self.element, "fillStyle0") + } + + pub fn fill_style1(&self) -> Option<u32> { + integer(self.element, "fillStyle1") + } + + pub fn stroke_style(&self) -> Option<u32> { + integer(self.element, "strokeStyle") + } + + pub fn encoded_segments(&self) -> Option<&str> { + self.element.attr("edges") + } + + /// Parsed XFL path segments, using the shared bounded edge grammar. + pub fn segments(&self) -> Vec<Segment> { + self.encoded_segments().map(edges::parse_edge_segments).unwrap_or_default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::Options::default().parse(source).unwrap() + } + + #[test] + fn reads_prefixed_shape_fill_stroke_and_edge_schema() { + let root = parse(br##"<x:DOMShape xmlns:x="urn:xfl" isDrawingObject="false"> + <x:matrix><x:Matrix a="2" tx="12"/></x:matrix> + <x:fills><x:FillStyle index="1"><x:LinearGradient spreadMethod="reflect" interpolationMethod="linearRGB"> + <x:GradientEntry ratio="0" color="#102030"/><x:GradientEntry ratio="255" color="#ffffff" alpha=".5"/> + </x:LinearGradient></x:FillStyle><x:FillStyle index="2"><x:BitmapFill bitmapPath="Library/a.png" bitmapIsClipped="true"/></x:FillStyle></x:fills> + <x:strokes><x:StrokeStyle index="3"><x:DashedStroke weight="2" dash1="8" dash2="3" caps="square" joints="miter" miterLimit="7"><x:fill><x:SolidColor color="#abcdef"/></x:fill></x:DashedStroke></x:StrokeStyle></x:strokes> + <x:edges><x:Edge fillStyle0="2" fillStyle1="1" strokeStyle="3" edges="!0 0|200 0"/></x:edges> + </x:DOMShape>"##); + + let shape = Shape::new(&root).unwrap(); + assert_eq!(shape.matrix(), Matrix { a: 2.0, b: 0.0, c: 0.0, d: 1.0, tx: 12.0, ty: 0.0 }); + assert_eq!(shape.is_drawing_object(), Some(false)); + let fills: Vec<_> = shape.fills().collect(); + assert_eq!(fills.iter().map(FillStyle::index).collect::<Vec<_>>(), [Some(1), Some(2)]); + let gradient = fills[0].definition().unwrap(); + assert_eq!(gradient.kind(), FillKind::LinearGradient); + assert_eq!(gradient.spread_method(), Some("reflect")); + assert_eq!(gradient.interpolation_method(), Some("linearRGB")); + assert_eq!(gradient.gradient_entries().map(|entry| entry.ratio()).collect::<Vec<_>>(), [Some(0.0), Some(255.0)]); + let bitmap = fills[1].definition().unwrap(); + assert_eq!(bitmap.kind(), FillKind::Bitmap); + assert_eq!(bitmap.bitmap_path(), Some("Library/a.png")); + assert_eq!(bitmap.bitmap_is_clipped(), Some(true)); + + let stroke_style = shape.strokes().next().unwrap(); + let stroke = stroke_style.definition().unwrap(); + assert_eq!(stroke.kind(), StrokeKind::Dashed); + assert_eq!(stroke.weight(), Some(2.0)); + assert_eq!((stroke.dash1(), stroke.dash2()), (Some(8.0), Some(3.0))); + assert_eq!(stroke.fill().unwrap().color(), Some("#abcdef")); + let color = stroke.fill().unwrap().color_value(); + assert_eq!(color, Color { rgb: 0xabcdef, alpha: 1.0 }); + + let edge = shape.edges().next().unwrap(); + assert_eq!((edge.fill_style0(), edge.fill_style1(), edge.stroke_style()), (Some(2), Some(1), Some(3))); + assert_eq!(edge.segments().len(), 1); + } + + #[test] + fn duplicate_attributes_use_last_value_and_invalid_numbers_are_absent() { + let root = parse(b"<DOMShape isDrawingObject='false' isDrawingObject='true'><matrix><Matrix a='NaN' tx='12'/></matrix><fills><FillStyle index='1' index='4'><SolidColor alpha='Infinity'/></FillStyle></fills></DOMShape>"); + let shape = Shape::new(&root).unwrap(); + assert_eq!(shape.is_drawing_object(), Some(true)); + assert_eq!(shape.matrix(), Matrix { tx: 12.0, ..Matrix::IDENTITY }); + let fill = shape.fills().next().unwrap(); + assert_eq!(fill.index(), Some(4)); + let fill = fill.definition().unwrap(); + assert_eq!(fill.alpha(), None); + assert_eq!(fill.color_value(), Color { rgb: 0, alpha: 1.0 }); + } + + #[test] + fn color_attribute_values_keep_native_defaults_and_clamping() { + assert_eq!(color_from_attributes(Some(" #123456 "), Some("0.4")), Color { rgb: 0x123456, alpha: 0.4 }); + assert_eq!(color_from_attributes(Some("invalid"), Some("NaN")), Color { rgb: 0, alpha: 1.0 }); + assert_eq!(color_from_attributes(Some("#abcdef"), Some("2")), Color { rgb: 0xabcdef, alpha: 1.0 }); + assert_eq!(color_from_attributes(None, Some("-1")), Color { rgb: 0, alpha: 0.0 }); + } + + #[test] + fn style_table_views_keep_the_legacy_first_child_and_index_behavior() { + let root = parse(b"<DOMShape><fills><LegacyFill index='5'><SolidColor color='#123456'/></LegacyFill></fills><strokes><LegacyStroke index='6'><SolidStroke weight='2'/></LegacyStroke></strokes></DOMShape>"); + let shape = Shape::new(&root).unwrap(); + let fill_style = shape.fills().next().unwrap(); + assert_eq!(fill_style.index(), Some(5)); + assert_eq!(fill_style.definition().map(|fill| fill.kind()), Some(FillKind::SolidColor)); + let stroke_style = shape.strokes().next().unwrap(); + assert_eq!(stroke_style.index(), Some(6)); + assert_eq!(stroke_style.definition().map(|stroke| stroke.kind()), Some(StrokeKind::Solid)); + } + + #[test] + fn an_application_element_adapter_can_use_the_same_views() { + #[derive(Debug)] + struct AppElement { + name: String, + attrs: Vec<(String, String)>, + children: Vec<AppElement>, + } + impl XflElement for AppElement { + type Elements<'a> = std::slice::Iter<'a, AppElement>; + fn local_name(&self) -> &str { + self.name.rsplit(':').next().unwrap_or(&self.name) + } + fn attr(&self, name: &str) -> Option<&str> { + self.attrs.iter().rev().find(|(key, _)| key == name).map(|(_, value)| value.as_str()) + } + fn elements(&self) -> Self::Elements<'_> { + self.children.iter() + } + fn text_content(&self) -> Cow<'_, str> { + Cow::Borrowed("") + } + } + let app = AppElement { name: "x:DOMShape".into(), attrs: vec![("isDrawingObject".into(), "true".into())], children: Vec::new() }; + assert_eq!(Shape::new(&app).unwrap().is_drawing_object(), Some(true)); + } + + #[test] + fn reads_native_rectangle_and_oval_geometry_and_styles() { + let root = parse(br##"<DOMRectangleObject x="-2" y="3" objectWidth="20" objectHeight="10" topLeftRadius="4"><matrix><Matrix tx="7"/></matrix><fill><SolidColor color="#123456"/></fill><stroke><DashedStroke weight="2" dash1="5" dash2="3"/></stroke></DOMRectangleObject>"##); + let primitive = Primitive::new(&root).unwrap(); + assert_eq!(primitive.kind(), PrimitiveKind::Rectangle); + assert_eq!( + (primitive.x(), primitive.y(), primitive.width(), primitive.height(), primitive.top_left_radius()), + (Some(-2.0), Some(3.0), Some(20.0), Some(10.0), Some(4.0)) + ); + assert_eq!(primitive.matrix().tx, 7.0); + assert_eq!(primitive.fill().unwrap().kind(), FillKind::SolidColor); + assert_eq!(primitive.stroke().unwrap().kind(), StrokeKind::Dashed); + + let oval = parse(b"<DOMOvalObject objectWidth='10' objectHeight='8'/>"); + assert_eq!(Primitive::new(&oval).unwrap().kind(), PrimitiveKind::Oval); + assert!(Primitive::new(&parse(b"<DOMShape/>")).is_none()); + } + + #[test] + fn native_color_effect_keeps_xfl_values_and_safe_channel_defaults() { + let element = parse( + br##"<x:Color xmlns:x="urn:xfl" tintMultiplier=".25" tintColor="#123456" + brightness="-.4" alphaMultiplier=".5" redMultiplier="Infinity" greenMultiplier="-2" + blueMultiplier=".5" redOffset="255" greenOffset="-255" blueOffset="NaN" alphaOffset=".25"/>"##, + ); + let effect = NativeColorEffect::new(&element); + + assert_eq!(effect.tint_multiplier(), Some(0.25)); + assert_eq!(effect.tint_color(), Color { rgb: 0x123456, alpha: 1.0 }); + assert_eq!(effect.brightness(), Some(-0.4)); + assert_eq!(effect.multipliers(), [1.0, -2.0, 0.5, 0.5]); + assert_eq!(effect.offsets(), [255.0, -255.0, 0.0, 0.25]); + } +} diff --git a/crates/xfl/src/shape_hints.rs b/crates/xfl/src/shape_hints.rs new file mode 100644 index 000000000..681e0c5a9 --- /dev/null +++ b/crates/xfl/src/shape_hints.rs @@ -0,0 +1,119 @@ +//! Borrowed views of native XFL shape-hint records. +//! +//! These parse the native point encodings and hint ordering. Snapping points onto consumer +//! geometry and pairing start/end keyframes remain application responsibilities. + +use crate::shape::{XflElement, integer, number}; + +/// A native XFL point in document coordinates. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Point { + pub x: f32, + pub y: f32, +} + +/// The optional `<shapeHints>` wrapper on a keyframe. +#[derive(Clone, Copy, Debug)] +pub struct ShapeHints<'a, E: XflElement> { + wrapper: Option<&'a E>, +} + +impl<'a, E: XflElement> ShapeHints<'a, E> { + pub fn new(keyframe: &'a E) -> Self { + Self { wrapper: keyframe.child("shapeHints") } + } + + pub fn is_empty(&self) -> bool { + self.wrapper.is_none_or(|wrapper| wrapper.elements().next().is_none()) + } + + /// Records in source order; unrecognized child names are retained because the legacy reader + /// interpreted their point and ordering attributes too. + pub fn iter(&self) -> impl Iterator<Item = ShapeHint<'a, E>> + 'a { + let wrapper = self.wrapper; + wrapper.into_iter().flat_map(XflElement::elements).map(|element| ShapeHint { element }) + } +} + +/// One native shape-hint record. +#[derive(Clone, Copy, Debug)] +pub struct ShapeHint<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> ShapeHint<'a, E> { + /// Native numeric order, or its single-letter `name` fallback (`a` is zero). + pub fn index(&self) -> Option<usize> { + integer(self.element, "index").map(|value| value as usize).or_else(|| self.element.attr("name").and_then(letter_index)) + } + + /// The keyframe's point, in either joined or separate native coordinate attributes. + pub fn start_point(&self) -> Option<Point> { + read_point(self.element, "startPoint", "startX", "startY").or_else(|| read_point(self.element, "point", "x", "y")) + } + + /// The next keyframe's point, when the record contains one. + pub fn end_point(&self) -> Option<Point> { + read_point(self.element, "endPoint", "endX", "endY") + } +} + +fn letter_index(name: &str) -> Option<usize> { + let [byte] = name.as_bytes() else { return None }; + match byte.to_ascii_lowercase() { + b'a'..=b'z' => Some((byte.to_ascii_lowercase() - b'a') as usize), + _ => None, + } +} + +fn read_point(element: &impl XflElement, joined: &str, x: &str, y: &str) -> Option<Point> { + let point = match element.attr(joined) { + Some(value) => { + let mut values = value.split([',', ' ']).filter(|part| !part.trim().is_empty()).map(|part| part.trim().parse::<f32>().ok()); + Point { x: values.next()??, y: values.next()?? } + } + None => Point { x: number(element, x)?, y: number(element, y)? }, + }; + (point.x.is_finite() && point.y.is_finite()).then_some(point) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::parse(source).expect("well-formed test XML") + } + + #[test] + fn reads_joined_and_split_native_points_in_source_order() { + let keyframe = parse(br#"<DOMFrame><shapeHints><Hint name="B" startPoint="12.5, -2" endX="30" endY="40"/><Hint index="0" startX="1" startY="2" endPoint="3 4"/></shapeHints></DOMFrame>"#); + let hints = ShapeHints::new(&keyframe); + assert!(!hints.is_empty()); + let records: Vec<_> = hints.iter().collect(); + assert_eq!(records[0].index(), Some(1)); + assert_eq!(records[0].start_point(), Some(Point { x: 12.5, y: -2.0 })); + assert_eq!(records[0].end_point(), Some(Point { x: 30.0, y: 40.0 })); + assert_eq!(records[1].index(), Some(0)); + assert_eq!(records[1].start_point(), Some(Point { x: 1.0, y: 2.0 })); + assert_eq!(records[1].end_point(), Some(Point { x: 3.0, y: 4.0 })); + } + + #[test] + fn malformed_joined_values_fall_back_to_the_other_native_point_field() { + let keyframe = parse(br#"<DOMFrame><shapeHints><Any name="z" startPoint="bad" x="7" y="8" endPoint="nan, 2"/></shapeHints></DOMFrame>"#); + let hint = ShapeHints::new(&keyframe).iter().next().expect("hint record"); + assert_eq!(hint.index(), Some(25)); + assert_eq!(hint.start_point(), Some(Point { x: 7.0, y: 8.0 })); + assert_eq!(hint.end_point(), None); + } + + #[test] + fn missing_lists_and_non_letter_names_remain_optional() { + let keyframe = parse(b"<DOMFrame/>"); + assert!(ShapeHints::new(&keyframe).is_empty()); + let keyframe = parse(br#"<DOMFrame><shapeHints><Hint name="AB" startX="1" startY="2"/></shapeHints></DOMFrame>"#); + let hint = ShapeHints::new(&keyframe).iter().next().expect("hint record"); + assert_eq!(hint.index(), None); + } +} diff --git a/crates/xfl/src/sound.rs b/crates/xfl/src/sound.rs new file mode 100644 index 000000000..408b000f1 --- /dev/null +++ b/crates/xfl/src/sound.rs @@ -0,0 +1,136 @@ +//! Borrowed views of native XFL frame-sound and envelope records. +//! +//! These parse the frame fields, effect-name spelling, and envelope wire values. Resolving sound +//! library items and mapping effects/envelopes into a consumer's audio model remain application +//! responsibilities. + +use crate::shape::{XflElement, integer, number}; + +/// Native frame-sound synchronization mode. Unknown values use Animate's event behavior. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SyncMode { + Start, + Stop, + Stream, + #[default] + Event, +} + +/// A native sound instruction stored on a `DOMFrame`. +#[derive(Clone, Copy, Debug)] +pub struct FrameSound<'a, E: XflElement> { + frame: &'a E, +} + +impl<'a, E: XflElement> FrameSound<'a, E> { + pub fn new(frame: &'a E) -> Self { + Self { frame } + } + + pub fn name(&self) -> Option<&'a str> { + self.frame.attr("soundName") + } + + pub fn sync_mode(&self) -> SyncMode { + match self.frame.attr("soundSync").map(str::trim) { + Some("start") => SyncMode::Start, + Some("stop") => SyncMode::Stop, + Some("stream") => SyncMode::Stream, + _ => SyncMode::Event, + } + } + + pub fn looping(&self) -> bool { + self.frame.attr("soundLoopMode").map(str::trim) == Some("loop") + } + + pub fn repeat(&self) -> Option<u32> { + integer(self.frame, "soundLoop") + } + + pub fn has_in_point(&self) -> bool { + self.frame.attr("inPoint44").is_some() + } + + pub fn has_out_point(&self) -> bool { + self.frame.attr("outPoint44").is_some() + } + + /// The effect menu label normalized to lowercase ASCII letters and digits, matching the + /// legacy reader's recognition of labels such as `Fade Left to Right`. + pub fn effect_key(&self) -> String { + self.frame + .attr("soundEffect") + .unwrap_or("") + .chars() + .filter(char::is_ascii_alphanumeric) + .map(|character| character.to_ascii_lowercase()) + .collect() + } + + pub fn envelope_points(&self) -> impl Iterator<Item = EnvelopePoint<'a, E>> + 'a { + self.frame + .child("SoundEnvelope") + .into_iter() + .flat_map(|envelope| envelope.elements_named("SoundEnvelopePoint")) + .map(|element| EnvelopePoint { element }) + } +} + +/// One native `SoundEnvelopePoint` record. Levels are raw SWF/XFL integer units. +#[derive(Clone, Copy, Debug)] +pub struct EnvelopePoint<'a, E: XflElement> { + element: &'a E, +} + +impl<E: XflElement> EnvelopePoint<'_, E> { + pub fn mark44(&self) -> Option<f32> { + number(self.element, "mark44") + } + + pub fn level0(&self) -> Option<f32> { + number(self.element, "level0") + } + + pub fn level1(&self) -> Option<f32> { + number(self.element, "level1") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::parse(source).expect("well-formed test XML") + } + + #[test] + fn reads_frame_sound_modes_repeat_trim_and_effect_name() { + let frame = parse(br#"<x:DOMFrame xmlns:x="urn:xfl" soundName="Music" soundSync=" stream " soundLoopMode="loop" soundLoop="12" inPoint44="2" outPoint44="100" soundEffect="Fade Left to Right!"/>"#); + let sound = FrameSound::new(&frame); + assert_eq!(sound.name(), Some("Music")); + assert_eq!(sound.sync_mode(), SyncMode::Stream); + assert!(sound.looping()); + assert_eq!(sound.repeat(), Some(12)); + assert!(sound.has_in_point()); + assert!(sound.has_out_point()); + assert_eq!(sound.effect_key(), "fadelefttoright"); + } + + #[test] + fn defaults_and_envelope_records_keep_native_optional_values() { + let frame = parse(br#"<DOMFrame soundSync="unknown" soundLoopMode="repeat" soundEffect="CuStOm"><SoundEnvelope><SoundEnvelopePoint mark44="44100" level0="32768"/><Other/><SoundEnvelopePoint mark44="bad" level0="0" level1="nan"/></SoundEnvelope></DOMFrame>"#); + let sound = FrameSound::new(&frame); + assert_eq!(sound.sync_mode(), SyncMode::Event); + assert!(!sound.looping()); + assert_eq!(sound.repeat(), None); + assert!(!sound.has_in_point()); + assert!(!sound.has_out_point()); + assert_eq!(sound.effect_key(), "custom"); + let points: Vec<_> = sound.envelope_points().collect(); + assert_eq!(points.len(), 2); + assert_eq!((points[0].mark44(), points[0].level0(), points[0].level1()), (Some(44100.0), Some(32768.0), None)); + assert_eq!((points[1].mark44(), points[1].level0(), points[1].level1()), (None, Some(0.0), None)); + } +} diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs new file mode 100644 index 000000000..5ae0713ba --- /dev/null +++ b/crates/xfl/src/tests.rs @@ -0,0 +1,467 @@ +//! The zip reader against the layouts writers produce and the archives an attacker would +//! (ADR 0054). Archives are made by the independent writer in `tests/support/fla.rs`. + +use super::pack::{self, Raw, write, write_at}; +use super::*; + +fn zip(files: &[(&str, &[u8], bool)]) -> Vec<u8> { + write(&files.iter().map(|(n, b, d)| Raw::new(n, b, *d)).collect::<Vec<_>>(), false) +} + +/// The error opening `z`, or reading every file in it. +fn error(z: &[u8]) -> ZipError { + match Archive::open(z) { + Err(e) => e, + Ok(a) => { + let names: Vec<String> = a.names().map(str::to_string).collect(); + names.iter().find_map(|n| a.read(n).err()).expect("an error") + } + } +} + +#[test] +fn reads_stored_and_deflated_entries() { + let z = zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), ("LIBRARY\\Ball.xml", b"<DOMSymbolItem/>", false)]); + let a = Archive::open(&z).unwrap(); + assert_eq!(a.read("DOMDocument.xml").unwrap().unwrap(), b"<DOMDocument/>"); + assert_eq!(a.read("LIBRARY/Ball.xml").unwrap().unwrap(), b"<DOMSymbolItem/>", "backslashes normalised"); + assert_eq!(a.read("missing").unwrap(), None); +} + +#[test] +fn xfl_package_root_prefers_root_then_selects_one_top_level_folder() { + let root = zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), ("Walk/DOMDocument.xml", b"<DOMDocument/>", true)]); + let archive = Archive::open(&root).unwrap(); + assert_eq!(archive.xfl_package_root(), XflPackageRoot::Document); + + let folder = zip(&[("Walk/DOMDocument.xml", b"<DOMDocument/>", true), ("Walk/LIBRARY/Clip.xml", b"<DOMSymbolItem/>", true)]); + let archive = Archive::open(&folder).unwrap(); + assert_eq!(archive.xfl_package_root(), XflPackageRoot::Folder("Walk")); +} + +#[test] +fn xfl_package_root_reports_sorted_candidates_and_ignores_metadata_and_nested_paths() { + let multiple = zip(&[ + ("Zebra/DOMDocument.xml", b"<DOMDocument/>", true), + ("Apple/DOMDocument.xml", b"<DOMDocument/>", true), + ("__MACOSX/DOMDocument.xml", b"not a project", true), + ]); + let archive = Archive::open(&multiple).unwrap(); + assert_eq!(archive.xfl_package_root(), XflPackageRoot::Multiple(vec!["Apple", "Zebra"])); + + let nested = zip(&[("One/Two/DOMDocument.xml", b"<DOMDocument/>", true), ("__MACOSX/One/DOMDocument.xml", b"metadata", true)]); + let archive = Archive::open(&nested).unwrap(); + assert_eq!(archive.xfl_package_root(), XflPackageRoot::Missing); +} + +#[test] +fn the_checksum_matches_the_published_check_value() { + assert_eq!(crc32(b"123456789"), 0xCBF4_3926); + assert_eq!(crc32(b""), 0); + let bytes: Vec<u8> = (0..5000u32).map(|i| (i * 7 + i / 13) as u8).collect(); + assert_eq!(crc32(&bytes), pack::crc32(&bytes), "the table matches the bitwise form"); +} + +#[test] +fn every_layout_a_writer_uses_reads_the_same() { + let files: std::collections::BTreeMap<String, Vec<u8>> = + [("DOMDocument.xml", "<DOMDocument/>"), ("LIBRARY/Café/Ünïcödé ★.xml", "<DOMSymbolItem/>"), ("bin/M 1 1.dat", "data")] + .iter() + .map(|(p, b)| (p.to_string(), b.as_bytes().to_vec())) + .collect(); + for v in pack::VARIANTS { + let z = pack::pack(&files, v); + let a = Archive::open(&z).unwrap_or_else(|e| panic!("{}: {e}", v.name)); + assert_eq!(a.counts().0, 3 + usize::from(v.mimetype), "{}", v.name); + for (path, body) in &files { + assert_eq!(a.read(path).unwrap_or_else(|e| panic!("{}: {e}", v.name)).as_deref(), Some(body.as_slice()), "{}: {path}", v.name); + } + } +} + +#[test] +fn names_are_cp437_unless_flagged_or_utf8() { + // "Café.xml" in CP437 (é is 0x82), not valid UTF-8, without the flag. + let mut r = Raw::new("", b"x", false); + (r.name, r.utf8) = (b"LIBRARY/Caf\x82.xml".to_vec(), false); + let z = write(&[r.clone()], false); + assert_eq!(Archive::open(&z).unwrap().names().collect::<Vec<_>>(), ["LIBRARY/Café.xml"]); + assert_eq!(pack::cp437("LIBRARY/Café.xml").unwrap(), b"LIBRARY/Caf\x82.xml"); + // Flagged as UTF-8 but isn't: refused, not guessed. + r.utf8 = true; + assert!(matches!(Archive::open(&write(&[r], false)).err(), Some(ZipError::Damaged(_)))); + // A Unicode path field whose checksum doesn't match the name it stands in for is ignored. + let mut r = Raw::new("plain.xml", b"x", false); + r.utf8 = false; + r.extra = [0x75, 0x70, 9, 0, 1, 0, 0, 0, 0, b'o', b't', b'h', b'r'].to_vec(); + assert_eq!(Archive::open(&write(&[r], false)).unwrap().names().collect::<Vec<_>>(), ["plain.xml"]); +} + +#[test] +fn damaged_archives_are_errors() { + assert_eq!(Archive::open(b"not a zip").err(), Some(ZipError::NotZip)); + assert_eq!(Archive::open(b"").err(), Some(ZipError::NotZip)); + let mut z = zip(&[("a", b"hello", true)]); + let n = z.len(); + // Point the directory past the end. + z[n - 6] = 0xff; + assert!(Archive::open(&z).is_err()); +} + +#[test] +fn a_truncated_central_directory_is_damaged() { + let z = zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), ("b.xml", b"<b/>", true), ("c.xml", b"<c/>", false)]); + let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize; + let end = z.len() - 22; + // Every cut inside the directory, keeping the end record (which still claims 3 entries). + for cut in dir_at..end { + let mut t = z[..cut].to_vec(); + t.extend_from_slice(&z[end..]); + let e = Archive::open(&t).err().unwrap_or_else(|| panic!("cut at {cut} opened")); + assert!(!e.to_string().is_empty()); + } + // The end record says more entries than there are. + let mut t = z.clone(); + t[end + 8] = 9; + t[end + 10] = 9; + assert_eq!(Archive::open(&t).err(), Some(ZipError::Damaged("the central directory is cut short"))); + // Cut short anywhere at all: an error, never a panic. + for cut in 0..z.len() { + let _ = Archive::open(&z[..cut]).map(|a| a.read("DOMDocument.xml")); + } +} + +#[test] +fn overlapping_entries_are_refused() { + // Two names for one local header (the overlapping-file zip bomb). + let mut b = Raw::new("b.xml", b"<a/>", true); + b.share = Some(0); + let z = write(&[Raw::new("a.xml", b"<a/>", true), b], false); + assert!(matches!(Archive::open(&z).err(), Some(ZipError::Overlap(..))), "{:?}", Archive::open(&z).err()); + // An entry whose stated compressed size runs into the next one. + let mut z = zip(&[("a.xml", b"aaaaaaaaaa", false), ("b.xml", b"bbbbbbbbbb", false)]); + let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize; + z[dir_at + 20] = 20; // a's compressed size, in its central record + z[dir_at + 24] = 20; + assert!(matches!(Archive::open(&z).err(), Some(ZipError::Overlap(..)))); +} + +#[test] +fn entries_never_reach_past_their_data() { + // An entry's data running into the central directory, or past the end. + for size in [64u32, 0xffff_fff0] { + let mut z = zip(&[("a.xml", b"aaaaaaaaaa", false)]); + let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize; + z[dir_at + 20..dir_at + 24].copy_from_slice(&size.to_le_bytes()); + assert_eq!(Archive::open(&z).err(), Some(ZipError::DamagedEntry("a.xml".into(), "is outside the archive"))); + } + // A local header offset past the end. + let mut z = zip(&[("a.xml", b"aaaaaaaaaa", false)]); + let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize; + z[dir_at + 42..dir_at + 46].copy_from_slice(&0x7fff_0000u32.to_le_bytes()); + assert_eq!(Archive::open(&z).err(), Some(ZipError::DamagedEntry("a.xml".into(), "has no local header"))); +} + +#[test] +fn lying_sizes_and_checksums_are_damaged() { + // Says 100 bytes, inflates to 1000. + let body = vec![b'x'; 1000]; + let mut r = Raw::new("a.xml", &body, true); + r.size = Some(100); + assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "expands past the size it gives")); + // Says 2000, inflates to 1000. + let mut r = Raw::new("a.xml", &body, true); + r.size = Some(2000); + assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "is not the size it gives")); + // A stored entry with two sizes. + let mut r = Raw::new("a.xml", &body, false); + r.size = Some(10); + assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "is stored with two different sizes")); + // The wrong checksum. + let mut r = Raw::new("a.xml", &body, true); + r.crc = Some(12345); + assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "fails its checksum")); + // Garbage instead of deflate data. + let mut r = Raw::new("a.xml", &body, true); + r.compressed = Some(vec![0xff; 40]); + assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "has damaged compressed data")); +} + +#[test] +fn compression_bombs_are_refused() { + // A real 64 MB of zeros deflates past the ratio cap: refused before inflating. + let zeros = vec![0u8; 64 << 20]; + let z = zip(&[("bomb.xml", &zeros, true)]); + assert!(z.len() < 100_000, "{}", z.len()); + assert_eq!(Archive::open(&z).err(), Some(ZipError::Bomb("bomb.xml".into()))); + // A size claim no deflate stream of that length could meet. + let mut r = Raw::new("a.xml", &[7; 100], true); + r.size = Some(200 << 20); + assert_eq!(Archive::open(&write(&[r], false)).err(), Some(ZipError::Bomb("a.xml".into()))); + // One entry larger than an entry may be, at a believable ratio: refused before inflating. + let mut r = Raw::new("big.dat", b"", true); + r.compressed = Some(vec![0; 300 << 10]); + r.size = Some(MAX_ENTRY as u64 + 1); + let z = write(&[r], false); + assert_eq!(error(&z), ZipError::TooLarge("big.dat".into())); +} + +#[test] +fn the_archive_hands_out_at_most_its_budget() { + let body = vec![b'a'; 4096]; + let z = zip(&[("a.xml", &body, true)]); + let a = Archive::open(&z).unwrap(); + a.budget.set(10_000); + assert!(a.read("a.xml").is_ok() && a.read("a.xml").is_ok()); + assert_eq!(a.read("a.xml").err(), Some(ZipError::TooMuch), "a third read passes 10,000 bytes"); +} + +#[test] +fn unsafe_paths_are_refused() { + for name in [ + "../escape.xml", + "LIBRARY/../../escape.xml", + "/etc/passwd", + "\\Windows\\win.ini", + "C:\\Windows\\win.ini", + "C:escape.xml", + "LIBRARY\\..\\..\\x", + "a\0b", + ] { + let z = zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), (name, b"x", false)]); + assert!(matches!(Archive::open(&z).err(), Some(ZipError::Unsafe(_))), "{name:?}: {:?}", Archive::open(&z).err()); + } + // Harmless odd names are tidied, not refused. + let z = zip(&[("./LIBRARY//a.xml", b"x", false)]); + assert_eq!(Archive::open(&z).unwrap().names().collect::<Vec<_>>(), ["LIBRARY/a.xml"]); +} + +#[test] +fn duplicate_names_are_refused() { + let z = zip(&[("LIBRARY/a.xml", b"one", false), ("LIBRARY\\a.xml", b"two", false)]); + assert_eq!(Archive::open(&z).err(), Some(ZipError::Duplicate("LIBRARY\\a.xml".into()))); + // Folders listed twice are harmless. + let z = zip(&[("LIBRARY/", b"", false), ("LIBRARY\\", b"", false), ("LIBRARY/a.xml", b"one", false)]); + assert_eq!(Archive::open(&z).unwrap().counts(), (1, 2)); +} + +#[test] +fn drive_prefix_after_normalized_dot_segments_is_refused() { + for name in ["./C:/LIBRARY/a.xml", "./C:\\LIBRARY\\a.xml"] { + assert!(matches!(Archive::open(&zip(&[(name, b"x", false)])).err(), Some(ZipError::Unsafe(_)))); + } + assert!(Archive::open(&zip(&[("./LIBRARY/a.xml", b"x", false)])).is_ok()); +} + +#[test] +fn invalid_eocd_comment_candidate_does_not_mask_archive_end() { + let mut z = zip(&[("a.xml", b"x", false)]); + let end = z.len() - 22; + z[end + 20..end + 22].copy_from_slice(&22u16.to_le_bytes()); + let fake = z.len(); + z.extend_from_slice(&END.to_le_bytes()); + z.extend_from_slice(&[0; 16]); + z.extend_from_slice(&u16::MAX.to_le_bytes()); + assert!(Archive::open(&z).is_ok()); + assert_eq!(fake + 22, z.len()); +} + +#[test] +fn eocd_signature_inside_comment_is_not_an_empty_archive() { + let mut z = zip(&[("a.xml", b"x", false)]); + let end = z.len() - 22; + z[end + 20..end + 22].copy_from_slice(&22u16.to_le_bytes()); + z.extend_from_slice(&END.to_le_bytes()); + z.extend_from_slice(&[0; 18]); + let archive = Archive::open(&z).unwrap(); + assert_eq!(archive.names().collect::<Vec<_>>(), ["a.xml"]); +} + +#[test] +fn central_directory_must_be_consumed_exactly() { + let mut z = zip(&[("a.xml", b"x", false)]); + let end = z.len() - 22; + let size = u32::from_le_bytes(z[end + 12..end + 16].try_into().unwrap()); + z.insert(end, 0); + z[end + 12 + 1..end + 16 + 1].copy_from_slice(&(size + 1).to_le_bytes()); + assert_eq!(Archive::open(&z).err(), Some(ZipError::Damaged("the central directory has trailing data"))); +} + +#[test] +fn nonempty_comment_eocd_candidate_does_not_mask_valid_archive() { + let mut bytes = zip(&[("a.xml", b"x", false)]); + let end = bytes.len() - 22; + // The fake EOCD sits in the real EOCD's comment and claims the real directory plus the + // real EOCD as a shifted directory. Candidate selection must reject its trailing bytes. + bytes[end + 20..end + 22].copy_from_slice(&22u16.to_le_bytes()); + bytes.extend_from_slice(&END.to_le_bytes()); + bytes.extend_from_slice(&[0; 4]); + bytes.extend_from_slice(&1u16.to_le_bytes()); + bytes.extend_from_slice(&1u16.to_le_bytes()); + bytes.extend_from_slice(&73u32.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.extend_from_slice(&0u16.to_le_bytes()); + + let archive = Archive::open(&bytes).unwrap(); + assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x"); +} + +#[test] +fn repeated_eocd_directory_candidates_reuse_entry_validation() { + let entries = (0..1024).map(|index| Raw::new(&format!("entry-{index:04}.xml"), b"", false)).collect::<Vec<_>>(); + let mut bytes = write(&entries, false); + let eocd = bytes.len() - 22; + bytes[eocd + 20..eocd + 22].copy_from_slice(&1000u16.to_le_bytes()); + bytes.extend_from_slice(&vec![0; 1000]); + let directory_start = u32_at(&bytes, eocd + 16).unwrap() as usize; + let directory_size = u64::from(u32_at(&bytes, eocd + 12).unwrap()); + let count = u64::from(u16_at(&bytes, eocd + 10).unwrap()); + let mut jumps = std::collections::HashMap::new(); + + assert!(directory_is_exact(&bytes, directory_start, directory_size, count, &mut jumps)); + let indexed_records = jumps.len(); + // Each size models a fake shifted EOCD in the archive comment that starts at the same + // central-directory record but claims additional bytes through the real EOCD. + for extra in 1..=1000 { + assert!(!directory_is_exact(&bytes, directory_start, directory_size + extra, count, &mut jumps)); + } + assert_eq!(jumps.len(), indexed_records, "repeated candidates must reuse the indexed entry jumps"); +} + +#[test] +fn deeply_nested_folders_are_refused() { + let ok = format!("{}a.xml", "f/".repeat(MAX_DEPTH)); + assert!(Archive::open(&zip(&[(&ok, b"x", false)])).is_ok()); + let deep = format!("{}a.xml", "f/".repeat(MAX_DEPTH + 1)); + assert!(matches!(Archive::open(&zip(&[(&deep, b"x", false)])).err(), Some(ZipError::TooDeep(_)))); + // As deep as a name can be: refused quickly, not recursed into. + let deepest = "f/".repeat(30_000); + assert!(matches!(Archive::open(&zip(&[(&deepest, b"", false)])).err(), Some(ZipError::TooDeep(_)))); +} + +#[test] +fn unsupported_features_say_what_they_are() { + assert_eq!( + ZipError::UnsupportedArchive("split across several files").to_string(), + "the archive uses a zip feature this XFL reader can't read (split across several files)" + ); + assert_eq!(ZipError::Unsupported("a.xml".into(), "encryption").to_string(), "'a.xml' uses a zip feature this XFL reader can't read (encryption)"); + let mut r = Raw::new("a.xml", b"secret", false); + r.flags = 1; + assert_eq!(error(&write(&[r], false)), ZipError::Unsupported("a.xml".into(), "encryption")); + let mut r = Raw::new("a.xml", b"x", false); + r.method = Some(14); + assert_eq!(error(&write(&[r], false)), ZipError::Unsupported("a.xml".into(), "LZMA compression")); + // Split archives. + let mut z = zip(&[("a.xml", b"x", false)]); + let end = z.len() - 22; + z[end + 4] = 1; + assert_eq!(Archive::open(&z).err(), Some(ZipError::UnsupportedArchive("split across several files"))); + // Too many entries for the directory to hold, and more than the cap. + let mut z = zip(&[("a.xml", b"x", false)]); + let end = z.len() - 22; + z[end + 8..end + 12].copy_from_slice(&[0xfe, 0xff, 0xfe, 0xff]); + assert!(Archive::open(&z).is_err()); +} + +#[test] +fn zip64_archives_open_and_their_damage_is_named() { + let mut a = Raw::new("a.xml", b"<a/>", true); + a.zip64 = true; + let mut b = Raw::new("b.xml", b"<b/>", false); + (b.zip64, b.descriptor) = (true, true); + let z = write(&[a.clone(), b], true); + let arch = Archive::open(&z).unwrap(); + assert_eq!(arch.read("b.xml").unwrap().unwrap(), b"<b/>"); + // The locator gone. + let mut t = z.clone(); + let loc = t.len() - 22 - 20; + t[loc] = 0; + assert_eq!(Archive::open(&t).err(), Some(ZipError::Damaged("the ZIP64 end record is missing"))); + // An entry that says ZIP64 without the extra field. + a.zip64 = false; + let mut t = write(&[a], false); + let dir_at = u32_at(&t, t.len() - 6).unwrap() as usize; + t[dir_at + 24..dir_at + 28].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(Archive::open(&t).err(), Some(ZipError::DamagedEntry("a.xml".into(), "has no ZIP64 sizes"))); +} + +#[test] +fn zip64_count_sentinel_keeps_a_comment_eocd_from_masking_the_archive() { + let mut bytes = write(&[Raw::new("a.xml", b"x", false)], true); + let end = bytes.len() - 22; + let locator = end - 20; + let zip64_end = locator - 56; + let directory_size = u64_at(&bytes, zip64_end + 40).unwrap() as u32; + let directory_offset = u64_at(&bytes, zip64_end + 48).unwrap() as u32; + // Count requires ZIP64, while directory size and offset still fit in the classic fields. + bytes[end + 12..end + 16].copy_from_slice(&directory_size.to_le_bytes()); + bytes[end + 16..end + 20].copy_from_slice(&directory_offset.to_le_bytes()); + bytes[end + 20..end + 22].copy_from_slice(&22u16.to_le_bytes()); + // This valid empty EOCD-shaped signature is inside the real end record's comment. + bytes.extend_from_slice(&END.to_le_bytes()); + bytes.extend_from_slice(&[0; 18]); + + let archive = Archive::open(&bytes).unwrap(); + assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x"); +} + +#[test] +fn empty_relative_zip64_directory_opens_after_sfx_stub() { + let mut bytes = b"MZ self-extracting stub".to_vec(); + bytes.extend_from_slice(&write_at(&[], true, 0)); + let archive = Archive::open(&bytes).unwrap(); + assert_eq!(archive.names().count(), 0); +} + +#[test] +fn self_extracting_archives_support_relative_and_adjusted_offsets() { + let entries = [Raw::new("DOMDocument.xml", b"<DOMDocument/>", true), Raw::new("LIBRARY/a.xml", b"<DOMSymbolItem/>", false)]; + let stub = b"MZ\x90\0 self-extracting program with no ZIP signatures ".repeat(31); + for zip64 in [false, true] { + for adjusted in [false, true] { + let base = if adjusted { stub.len() as u64 } else { 0 }; + let mut bytes = stub.clone(); + bytes.extend_from_slice(&write_at(&entries, zip64, base)); + let archive = Archive::open(&bytes).unwrap_or_else(|error| panic!("ZIP64 {zip64}, adjusted {adjusted}: {error}")); + assert_eq!(archive.read("DOMDocument.xml").unwrap().unwrap(), b"<DOMDocument/>"); + assert_eq!(archive.read("LIBRARY/a.xml").unwrap().unwrap(), b"<DOMSymbolItem/>"); + if !zip64 && !adjusted { + let eocd = bytes.len() - 22; + let stated = u32::from_le_bytes(bytes[eocd + 16..eocd + 20].try_into().unwrap()) as usize; + assert_eq!(&bytes[stated + stub.len()..stated + stub.len() + 4], b"PK\x01\x02"); + } + } + } + + // A gap between the directory and end record cannot be guessed as a prefix shift. + let mut bytes = stub; + bytes.extend_from_slice(&write_at(&entries, false, 0)); + let eocd = bytes.len() - 22; + bytes.splice(eocd..eocd, *b"junk"); + assert!(Archive::open(&bytes).is_err()); +} + +#[test] +fn errors_read_as_sentences() { + let all = [ + ZipError::NotZip, + ZipError::Damaged("the central directory is cut short"), + ZipError::DamagedEntry("a.xml".into(), "fails its checksum"), + ZipError::UnsupportedArchive("split across several files"), + ZipError::Unsupported("a.xml".into(), "encryption"), + ZipError::TooLarge("a.xml".into()), + ZipError::TooMuch, + ZipError::TooMany, + ZipError::Bomb("a.xml".into()), + ZipError::Overlap("a.xml".into(), "b.xml".into()), + ZipError::Unsafe("../a.xml".into()), + ZipError::Duplicate("a.xml".into()), + ZipError::TooDeep("f/f/a.xml".into()), + ]; + for e in all { + let s = e.to_string(); + assert!(s.len() > 12 && !s.contains("{") && s.chars().next().is_some_and(|c| !c.is_uppercase() || c == 'A'), "{s}"); + } + assert_eq!(ZipError::TooMuch.to_string(), "the archive asks for more than 1024 MB in all"); +} diff --git a/crates/xfl/src/text.rs b/crates/xfl/src/text.rs new file mode 100644 index 000000000..8d883fc0c --- /dev/null +++ b/crates/xfl/src/text.rs @@ -0,0 +1,273 @@ +//! Borrowed views of native XFL text-field, run and style records. +//! +//! The views expose format attributes and direct text only. Text layout, font selection, +//! unsupported-style reporting and conversion into an application's text model stay with the +//! consumer. + +use crate::shape::{self, Color, XflElement}; +use std::borrow::Cow; + +/// A native static, dynamic or input text field. +#[derive(Clone, Copy, Debug)] +pub struct TextField<'a, E: XflElement> { + element: &'a E, + kind: TextFieldKind, +} + +/// Kind of native XFL text field. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextFieldKind { + Static, + Dynamic, + Input, +} + +impl<'a, E: XflElement> TextField<'a, E> { + /// Views a recognized XFL text field. + pub fn new(element: &'a E) -> Option<Self> { + let kind = match element.local_name() { + "DOMStaticText" => TextFieldKind::Static, + "DOMDynamicText" => TextFieldKind::Dynamic, + "DOMInputText" => TextFieldKind::Input, + _ => return None, + }; + Some(Self { element, kind }) + } + + pub fn kind(&self) -> TextFieldKind { + self.kind + } + + /// Native field orientation (`horizontal`, `vertical`, etc.). + pub fn orientation(&self) -> Option<&'a str> { + self.element.attr("orientation") + } + + /// Native `autoExpand` flag, if present and parseable. + pub fn auto_expand(&self) -> Option<bool> { + boolean(self.element, "autoExpand") + } + + pub fn width(&self) -> Option<f32> { + number(self.element, "width") + } + + pub fn height(&self) -> Option<f32> { + number(self.element, "height") + } + + pub fn left(&self) -> Option<f32> { + number(self.element, "left") + } + + pub fn top(&self) -> Option<f32> { + number(self.element, "top") + } + + pub fn line_type(&self) -> Option<&'a str> { + self.element.attr("lineType") + } + + pub fn border(&self) -> Option<bool> { + boolean(self.element, "border") + } + + pub fn is_selectable(&self) -> Option<bool> { + boolean(self.element, "isSelectable") + } + + pub fn render_as_html(&self) -> Option<bool> { + boolean(self.element, "renderAsHTML") + } + + pub fn max_characters(&self) -> Option<f32> { + number(self.element, "maxCharacters") + } + + pub fn variable_name(&self) -> Option<&'a str> { + self.element.attr("variableName") + } + + /// Whether the native field has any filter records, which consumers may need to report as + /// unsupported while keeping the field. + pub fn has_filters(&self) -> bool { + self.element.child("filters").is_some_and(|wrapper| wrapper.elements().next().is_some()) + } + + /// Text runs in document order. Non-`DOMTextRun` children are ignored. + pub fn runs(&self) -> impl Iterator<Item = TextRun<'a, E>> + 'a { + self.element.child("textRuns").into_iter().flat_map(|wrapper| wrapper.elements_named("DOMTextRun")).map(|element| TextRun { element }) + } + + /// Number of element records inside the native `<textRuns>` wrapper, including unknown + /// records. This lets consumers retain their prior malformed-record and resource-limit + /// policy while parsing recognized runs through [`Self::runs`]. + pub fn run_entries_count(&self) -> usize { + self.element.child("textRuns").map_or(0, |wrapper| wrapper.elements().count()) + } +} + +/// One native text run and its optional style record. +#[derive(Clone, Copy, Debug)] +pub struct TextRun<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> TextRun<'a, E> { + /// Direct character data of this run's `<characters>` element. + pub fn characters(&self) -> Cow<'a, str> { + self.element.child("characters").map_or(Cow::Borrowed(""), XflElement::text_content) + } + + /// The native text attributes nested under `<textAttrs><DOMTextAttrs .../>`. + pub fn style(&self) -> Option<TextStyle<'a, E>> { + self.element.child("textAttrs").and_then(|wrapper| wrapper.child("DOMTextAttrs")).map(|element| TextStyle { element }) + } +} + +/// Native `DOMTextAttrs` fields. Values are parsed from the wire schema but not laid out or +/// normalized for any application. +#[derive(Clone, Copy, Debug)] +pub struct TextStyle<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> TextStyle<'a, E> { + pub fn face(&self) -> Option<&'a str> { + self.element.attr("face") + } + + pub fn size(&self) -> Option<f32> { + number(self.element, "size") + } + + pub fn bold(&self) -> Option<bool> { + boolean(self.element, "bold") + } + + pub fn italic(&self) -> Option<bool> { + boolean(self.element, "italic") + } + + pub fn fill_color(&self) -> Option<&'a str> { + self.element.attr("fillColor") + } + + /// Parsed native fill color and alpha, with XFL's black/full-opacity defaults. + pub fn color(&self) -> Color { + shape::color(self.element, "fillColor", "alpha") + } + + pub fn alpha(&self) -> Option<f32> { + number(self.element, "alpha") + } + + pub fn alignment(&self) -> Option<&'a str> { + self.element.attr("alignment") + } + + pub fn indent(&self) -> Option<f32> { + number(self.element, "indent") + } + + pub fn character_position(&self) -> Option<&'a str> { + self.element.attr("characterPosition") + } + + pub fn letter_spacing(&self) -> Option<f32> { + number(self.element, "letterSpacing") + } + + pub fn line_spacing(&self) -> Option<f32> { + number(self.element, "lineSpacing") + } + + pub fn left_margin(&self) -> Option<f32> { + number(self.element, "leftMargin") + } + + pub fn right_margin(&self) -> Option<f32> { + number(self.element, "rightMargin") + } +} + +fn number(element: &impl XflElement, name: &str) -> Option<f32> { + element.attr(name)?.trim().parse::<f32>().ok().filter(|value| value.is_finite()) +} + +fn boolean(element: &impl XflElement, name: &str) -> Option<bool> { + element.attr(name).map(|value| value.trim() == "true") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::parse(source).expect("well-formed test XML") + } + + #[test] + fn reads_prefixed_text_fields_runs_and_native_style_values() { + let root = parse( + br##"<x:DOMDynamicText xmlns:x="urn:xfl" orientation="horizontal" autoExpand="true" width="320" height="40" left="12" top="3" lineType="multiline" border="true" isSelectable="false" renderAsHTML="false" maxCharacters="45" variableName="message"><x:filters><x:BlurFilter/></x:filters><x:textRuns><x:DOMTextRun><x:characters>one &amp; two</x:characters><x:textAttrs><x:DOMTextAttrs face="Arial" size="24" bold="true" italic="false" fillColor="#123456" alpha="0.5" alignment="center" indent="3" characterPosition="superscript" letterSpacing="1.25" lineSpacing="2" leftMargin="4" rightMargin="5"/></x:textAttrs></x:DOMTextRun><x:Other/><x:DOMTextRun><x:characters><![CDATA[third]]></x:characters></x:DOMTextRun></x:textRuns></x:DOMDynamicText>"##, + ); + let field = TextField::new(&root).expect("dynamic text field"); + assert_eq!(field.kind(), TextFieldKind::Dynamic); + assert_eq!(field.orientation(), Some("horizontal")); + assert_eq!(field.auto_expand(), Some(true)); + assert_eq!((field.width(), field.height(), field.left(), field.top()), (Some(320.0), Some(40.0), Some(12.0), Some(3.0))); + assert_eq!(field.line_type(), Some("multiline")); + assert_eq!(field.border(), Some(true)); + assert_eq!(field.is_selectable(), Some(false)); + assert_eq!(field.render_as_html(), Some(false)); + assert_eq!(field.max_characters(), Some(45.0)); + assert_eq!(field.variable_name(), Some("message")); + assert!(field.has_filters()); + + let mut runs = field.runs(); + let first = runs.next().expect("first run"); + assert_eq!(first.characters(), "one & two"); + let style = first.style().expect("text style"); + assert_eq!(style.face(), Some("Arial")); + assert_eq!(style.size(), Some(24.0)); + assert_eq!(style.bold(), Some(true)); + assert_eq!(style.italic(), Some(false)); + assert_eq!(style.fill_color(), Some("#123456")); + assert_eq!(style.alpha(), Some(0.5)); + assert_eq!(style.alignment(), Some("center")); + assert_eq!(style.indent(), Some(3.0)); + assert_eq!(style.character_position(), Some("superscript")); + assert_eq!(style.letter_spacing(), Some(1.25)); + assert_eq!(style.line_spacing(), Some(2.0)); + assert_eq!(style.left_margin(), Some(4.0)); + assert_eq!(style.right_margin(), Some(5.0)); + + let second = runs.next().expect("second run"); + assert_eq!(second.characters(), "third"); + assert!(second.style().is_none()); + assert!(runs.next().is_none()); + } + + #[test] + fn recognizes_all_native_field_kinds_and_ignores_non_text_elements() { + for (name, expected) in + [("DOMStaticText", TextFieldKind::Static), ("DOMDynamicText", TextFieldKind::Dynamic), ("DOMInputText", TextFieldKind::Input)] + { + let xml = format!("<{name}/>"); + let root = craft_xml::parse(xml.as_bytes()).expect("test XML"); + assert_eq!(TextField::new(&root).map(|field| field.kind()), Some(expected)); + } + let root = parse(b"<DOMShape/>"); + assert!(TextField::new(&root).is_none()); + } + + #[test] + fn malformed_and_non_finite_numbers_remain_absent() { + let root = parse(b"<DOMStaticText><textRuns><DOMTextRun><textAttrs><DOMTextAttrs size='NaN' letterSpacing='bad'/></textAttrs></DOMTextRun></textRuns></DOMStaticText>"); + let field = TextField::new(&root).expect("text field"); + let style = field.runs().next().and_then(|run| run.style()).expect("style"); + assert_eq!(style.size(), None); + assert_eq!(style.letter_spacing(), None); + } +} diff --git a/crates/xfl/src/tween.rs b/crates/xfl/src/tween.rs new file mode 100644 index 000000000..a894d5c29 --- /dev/null +++ b/crates/xfl/src/tween.rs @@ -0,0 +1,117 @@ +//! Borrowed views of native XFL frame-tween and custom-ease records. +//! +//! This parses the native attributes and point lists. Interpreting easing curves and applying +//! them to an application's timeline model remain consumer responsibilities. + +use crate::shape::{XflElement, boolean, number}; + +/// Native motion/shape tween settings on a `DOMFrame`. +#[derive(Clone, Copy, Debug)] +pub struct FrameTween<'a, E: XflElement> { + frame: &'a E, +} + +impl<'a, E: XflElement> FrameTween<'a, E> { + pub fn new(frame: &'a E) -> Self { + Self { frame } + } + + /// The classic slider value, when present and finite. + pub fn acceleration(&self) -> Option<f32> { + number(self.frame, "acceleration") + } + + pub fn has_custom_ease(&self) -> Option<bool> { + boolean(self.frame, "hasCustomEase") + } + + /// Animate's default is a single curve unless this is explicitly false. + pub fn use_single_ease_curve(&self) -> Option<bool> { + boolean(self.frame, "useSingleEaseCurve") + } + + pub fn orient_to_path(&self) -> Option<bool> { + boolean(self.frame, "motionTweenOrientToPath") + } + + /// Raw native rotation setting; interpretation stays in the consuming application. + pub fn rotate(&self) -> Option<&'a str> { + self.frame.attr("motionTweenRotate") + } + + /// Custom ease curves in source order; unknown tween entries are skipped. + pub fn custom_eases(&self) -> impl Iterator<Item = CustomEase<'a, E>> + 'a { + self.frame.child("tweens").into_iter().flat_map(|wrapper| wrapper.elements_named("CustomEase")).map(|element| CustomEase { element }) + } +} + +/// A native custom-ease curve. +#[derive(Clone, Copy, Debug)] +pub struct CustomEase<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> CustomEase<'a, E> { + /// The property-group name, defaulting to `all` in XFL. + pub fn target(&self) -> &'a str { + self.element.attr("target").map(str::trim).unwrap_or("all") + } + + pub fn points(&self) -> impl Iterator<Item = EasePoint<'a, E>> + 'a { + self.element.elements_named("Point").map(|element| EasePoint { element }) + } +} + +/// One native custom-ease point. +#[derive(Clone, Copy, Debug)] +pub struct EasePoint<'a, E: XflElement> { + element: &'a E, +} + +impl<E: XflElement> EasePoint<'_, E> { + pub fn x(&self) -> Option<f32> { + number(self.element, "x") + } + + pub fn y(&self) -> Option<f32> { + number(self.element, "y") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::parse(source).expect("well-formed test XML") + } + + #[test] + fn reads_frame_tween_settings_and_custom_eases_in_order() { + let frame = parse( + br#"<x:DOMFrame xmlns:x="urn:xfl" acceleration="-45" hasCustomEase="true" useSingleEaseCurve="false" motionTweenOrientToPath="true" motionTweenRotate="clockwise"><x:tweens><x:Other/><x:CustomEase target="position"><x:Point x="0" y="0"/><x:Point x="0.5" y="0.25"/></x:CustomEase><x:CustomEase><x:Point x="1" y="1"/></x:CustomEase></x:tweens></x:DOMFrame>"#, + ); + let tween = FrameTween::new(&frame); + assert_eq!(tween.acceleration(), Some(-45.0)); + assert_eq!(tween.has_custom_ease(), Some(true)); + assert_eq!(tween.use_single_ease_curve(), Some(false)); + assert_eq!(tween.orient_to_path(), Some(true)); + assert_eq!(tween.rotate(), Some("clockwise")); + let curves: Vec<_> = tween.custom_eases().collect(); + assert_eq!(curves.len(), 2); + assert_eq!(curves[0].target(), "position"); + assert_eq!(curves[0].points().map(|point| (point.x(), point.y())).collect::<Vec<_>>(), [(Some(0.0), Some(0.0)), (Some(0.5), Some(0.25))]); + assert_eq!(curves[1].target(), "all"); + assert_eq!(curves[1].points().next().map(|point| (point.x(), point.y())), Some((Some(1.0), Some(1.0)))); + } + + #[test] + fn absent_and_malformed_values_remain_optional() { + let frame = parse(br#"<DOMFrame acceleration="NaN" hasCustomEase="bad" useSingleEaseCurve="false"/>"#); + let tween = FrameTween::new(&frame); + assert_eq!(tween.acceleration(), None); + assert_eq!(tween.has_custom_ease(), Some(false)); + assert_eq!(tween.use_single_ease_curve(), Some(false)); + assert!(tween.custom_eases().next().is_none()); + } +} diff --git a/crates/xfl/tests/support/fla.rs b/crates/xfl/tests/support/fla.rs new file mode 100644 index 000000000..fcf5e2d7f --- /dev/null +++ b/crates/xfl/tests/support/fla.rs @@ -0,0 +1,353 @@ +//! Test support: packs an XFL package into `.fla` (zip) archives in memory, in each of the ways +//! zip writers lay one out (ADR 0054), and writes hand-made entries for hostile archives. +//! +//! Written from the published format (PKWARE APPNOTE 6.3), independently of the reader in +//! `src/zip.rs` (it has its own checksum), so a misreading in one is caught by the other. +//! Shared by the xfl crate's unit and corpus tests and the engine's golden tests (`#[path]`). +#![allow(dead_code)] + +use std::collections::BTreeMap; + +/// How a variant compresses its entries. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Compression { + Deflate, + Stored, + /// XML deflated, images stored (as most writers do), the rest alternating. + Mixed, +} + +/// How a variant writes entry names. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Names { + /// UTF-8 with flag bit 11 set. + Utf8Flag, + /// UTF-8 without the flag (common, though the format says CP437). + Utf8Unflagged, + /// CP437 bytes without the flag, as the format specifies (names CP437 can't spell are + /// written as UTF-8 with the flag). + Cp437, + /// An ASCII stand-in name with the real one in the Info-ZIP Unicode path field. + UnicodeExtra, +} + +/// One way of packing a package. +#[derive(Clone, Copy, Debug)] +pub struct Variant { + pub name: &'static str, + pub compression: Compression, + /// An entry for every folder, before the files in it. + pub folders: bool, + /// The `mimetype` entry first, stored, as Animate writes it. + pub mimetype: bool, + /// `\` between folders, as some Windows tools write. + pub backslashes: bool, + pub names: Names, + /// Sizes and checksums after the data (bit 3), as streaming writers do. + pub descriptors: bool, + /// ZIP64 sizes on every entry and a ZIP64 end record. + pub zip64: bool, +} + +const BASE: Variant = Variant { + name: "", + compression: Compression::Deflate, + folders: false, + mimetype: false, + backslashes: false, + names: Names::Utf8Flag, + descriptors: false, + zip64: false, +}; + +/// Every variant each corpus package is checked in. +pub const VARIANTS: &[Variant] = &[ + Variant { name: "as Animate writes it (mimetype first, deflated)", mimetype: true, ..BASE }, + Variant { name: "stored", compression: Compression::Stored, ..BASE }, + Variant { name: "mixed, with folder entries", compression: Compression::Mixed, folders: true, mimetype: true, ..BASE }, + Variant { name: "Windows separators, unflagged UTF-8 names", backslashes: true, folders: true, names: Names::Utf8Unflagged, ..BASE }, + Variant { name: "CP437 names", names: Names::Cp437, compression: Compression::Mixed, ..BASE }, + Variant { name: "Unicode path fields", names: Names::UnicodeExtra, ..BASE }, + Variant { name: "data descriptors", descriptors: true, compression: Compression::Mixed, ..BASE }, + Variant { name: "ZIP64", zip64: true, compression: Compression::Mixed, ..BASE }, + Variant { + name: "everything at once", + compression: Compression::Mixed, + folders: true, + mimetype: true, + backslashes: true, + names: Names::Cp437, + descriptors: true, + zip64: true, + }, +]; + +/// One entry as written. Fields a hostile test may change are public. +#[derive(Clone, Debug, Default)] +pub struct Raw { + /// The name's bytes as stored. + pub name: Vec<u8>, + /// The uncompressed bytes. + pub body: Vec<u8>, + pub deflate: bool, + /// General purpose flag bits besides 3 and 11 (bit 0: encrypted). + pub flags: u16, + pub utf8: bool, + pub descriptor: bool, + pub zip64: bool, + /// Overrides: the method, the uncompressed size and the checksum the headers give. + pub method: Option<u16>, + pub size: Option<u64>, + pub crc: Option<u32>, + /// Extra field bytes in the central directory (besides ZIP64's). + pub extra: Vec<u8>, + /// Points this entry's central record at entry `n`'s local header instead of its own. + pub share: Option<usize>, + /// Stored as compressed bytes: these instead of compressing `body`. + pub compressed: Option<Vec<u8>>, +} + +impl Raw { + pub fn new(name: &str, body: &[u8], deflate: bool) -> Raw { + Raw { name: name.as_bytes().to_vec(), body: body.to_vec(), deflate, utf8: true, ..Raw::default() } + } +} + +/// CRC-32 (ISO-HDLC), bit by bit. +pub fn crc32(data: &[u8]) -> u32 { + let mut c = !0u32; + for &b in data { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 != 0 { (c >> 1) ^ 0xEDB8_8320 } else { c >> 1 }; + } + } + !c +} + +/// `s` in CP437, if every character is in it. +pub fn cp437(s: &str) -> Option<Vec<u8>> { + const HIGH: &str = + "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u{a0}"; + s.chars().map(|c| if c.is_ascii() { Some(c as u8) } else { HIGH.chars().position(|h| h == c).map(|i| 0x80 + i as u8) }).collect() +} + +fn le16(out: &mut Vec<u8>, v: u16) { + out.extend_from_slice(&v.to_le_bytes()); +} +fn le32(out: &mut Vec<u8>, v: u32) { + out.extend_from_slice(&v.to_le_bytes()); +} +fn le64(out: &mut Vec<u8>, v: u64) { + out.extend_from_slice(&v.to_le_bytes()); +} + +/// Writes `entries` as a zip archive, with a ZIP64 end record if `zip64_end`. +pub fn write(entries: &[Raw], zip64_end: bool) -> Vec<u8> { + write_at(entries, zip64_end, 0) +} + +/// Writes an archive whose offsets count from `base` bytes before the ZIP data. +/// This models a self-extracting archive that has been adjusted to count from file start. +pub fn write_at(entries: &[Raw], zip64_end: bool, base: u64) -> Vec<u8> { + let mut out = Vec::new(); + let mut central = Vec::new(); + let mut offsets = Vec::new(); + // (time, date): 2025-11-11 12:00. + let (time, date) = (0x6000u16, 0x5B6Bu16); + for e in entries { + let data = match &e.compressed { + Some(c) => c.clone(), + None if e.deflate => miniz_oxide::deflate::compress_to_vec(&e.body, 6), + None => e.body.clone(), + }; + let method = e.method.unwrap_or(if e.deflate { 8 } else { 0 }); + let crc = e.crc.unwrap_or_else(|| crc32(&e.body)); + let size = e.size.unwrap_or(e.body.len() as u64); + let comp = data.len() as u64; + let flags = e.flags | if e.descriptor { 8 } else { 0 } | if e.utf8 { 0x800 } else { 0 }; + let version: u16 = if e.zip64 { 45 } else { 20 }; + let offset = base + out.len() as u64; + offsets.push(offset); + // The local header. + le32(&mut out, 0x0403_4b50); + le16(&mut out, version); + le16(&mut out, flags); + le16(&mut out, method); + le16(&mut out, time); + le16(&mut out, date); + let local_extra = if e.zip64 { + let mut x = Vec::new(); + le16(&mut x, 1); + le16(&mut x, 16); + le64(&mut x, if e.descriptor { 0 } else { size }); + le64(&mut x, if e.descriptor { 0 } else { comp }); + x + } else { + Vec::new() + }; + if e.descriptor { + out.extend_from_slice(&[0; 12]); + } else { + le32(&mut out, crc); + le32(&mut out, if e.zip64 { u32::MAX } else { comp as u32 }); + le32(&mut out, if e.zip64 { u32::MAX } else { size as u32 }); + } + le16(&mut out, e.name.len() as u16); + le16(&mut out, local_extra.len() as u16); + out.extend_from_slice(&e.name); + out.extend_from_slice(&local_extra); + out.extend_from_slice(&data); + if e.descriptor { + le32(&mut out, 0x0807_4b50); + le32(&mut out, crc); + if e.zip64 { + le64(&mut out, comp); + le64(&mut out, size); + } else { + le32(&mut out, comp as u32); + le32(&mut out, size as u32); + } + } + // Its central record. + let at = e.share.and_then(|n| offsets.get(n).copied()).unwrap_or(offset); + let mut extra = Vec::new(); + if e.zip64 { + le16(&mut extra, 1); + le16(&mut extra, 24); + le64(&mut extra, size); + le64(&mut extra, comp); + le64(&mut extra, at); + } + extra.extend_from_slice(&e.extra); + le32(&mut central, 0x0201_4b50); + le16(&mut central, version); + le16(&mut central, version); + le16(&mut central, flags); + le16(&mut central, method); + le16(&mut central, time); + le16(&mut central, date); + le32(&mut central, crc); + le32(&mut central, if e.zip64 { u32::MAX } else { comp as u32 }); + le32(&mut central, if e.zip64 { u32::MAX } else { size as u32 }); + le16(&mut central, e.name.len() as u16); + le16(&mut central, extra.len() as u16); + le16(&mut central, 0); // comment + le16(&mut central, 0); // disk + le16(&mut central, 0); // internal attributes + let folder = e.name.last().is_some_and(|&c| c == b'/' || c == b'\\'); + le32(&mut central, if folder { 0x10 } else { 0 }); + le32(&mut central, if e.zip64 { u32::MAX } else { at as u32 }); + central.extend_from_slice(&e.name); + central.extend_from_slice(&extra); + } + let dir_at = base + out.len() as u64; + out.extend_from_slice(&central); + let n = entries.len() as u64; + if zip64_end { + let record = base + out.len() as u64; + le32(&mut out, 0x0606_4b50); + le64(&mut out, 44); + le16(&mut out, 45); + le16(&mut out, 45); + le32(&mut out, 0); + le32(&mut out, 0); + le64(&mut out, n); + le64(&mut out, n); + le64(&mut out, central.len() as u64); + le64(&mut out, dir_at); + le32(&mut out, 0x0706_4b50); + le32(&mut out, 0); + le64(&mut out, record); + le32(&mut out, 1); + } + le32(&mut out, 0x0605_4b50); + le32(&mut out, 0); // disks + let (count, size, at) = if zip64_end { (u16::MAX, u32::MAX, u32::MAX) } else { (n as u16, central.len() as u32, dir_at as u32) }; + le16(&mut out, count); + le16(&mut out, count); + le32(&mut out, size); + le32(&mut out, at); + le16(&mut out, 0); + out +} + +/// The entries `files` (paths inside the package) become in `v`. +pub fn entries(files: &BTreeMap<String, Vec<u8>>, v: &Variant) -> Vec<Raw> { + let mut out = Vec::new(); + let named = |path: &str, body: &[u8], deflate: bool| { + let shown = if v.backslashes { path.replace('/', "\\") } else { path.to_string() }; + let mut r = Raw::new(&shown, body, deflate); + r.descriptor = v.descriptors; + r.zip64 = v.zip64; + match v.names { + Names::Utf8Flag => {} + Names::Utf8Unflagged => r.utf8 = false, + Names::Cp437 => { + if let Some(b) = cp437(&shown) { + (r.name, r.utf8) = (b, false); + } + } + Names::UnicodeExtra => { + let stand_in: Vec<u8> = shown.chars().map(|c| if c.is_ascii() { c as u8 } else { b'_' }).collect(); + le16(&mut r.extra, 0x7075); + le16(&mut r.extra, (5 + shown.len()) as u16); + r.extra.push(1); + le32(&mut r.extra, crc32(&stand_in)); + r.extra.extend_from_slice(shown.as_bytes()); + (r.name, r.utf8) = (stand_in, false); + } + } + r + }; + if v.mimetype { + out.push(named("mimetype", b"application/vnd.adobe.xfl", false)); + } + let mut made = std::collections::BTreeSet::new(); + for (i, (path, body)) in files.iter().enumerate() { + if v.folders { + let parts: Vec<&str> = path.split('/').collect(); + for k in 1..parts.len() { + let folder = format!("{}/", parts[..k].join("/")); + if made.insert(folder.clone()) { + out.push(named(&folder, b"", false)); + } + } + } + let image = [".png", ".jpg", ".jpeg", ".gif"].iter().any(|x| path.to_ascii_lowercase().ends_with(x)); + let deflate = match v.compression { + Compression::Deflate => true, + Compression::Stored => false, + Compression::Mixed => path.ends_with(".xml") || (!image && i % 2 == 0), + }; + out.push(named(path, body, deflate)); + } + out +} + +/// `files` packed as a `.fla` in variant `v`. +pub fn pack(files: &BTreeMap<String, Vec<u8>>, v: &Variant) -> Vec<u8> { + write(&entries(files, v), v.zip64) +} + +/// A package folder's files by their path inside it, leaving out its `golden/` renders. +pub fn package(dir: &std::path::Path) -> BTreeMap<String, Vec<u8>> { + fn walk(dir: &std::path::Path, prefix: &str, out: &mut BTreeMap<String, Vec<u8>>) { + let mut list: Vec<_> = std::fs::read_dir(dir).map(|r| r.flatten().collect()).unwrap_or_default(); + list.sort_by_key(|e| e.file_name()); + for e in list { + let name = e.file_name().to_string_lossy().into_owned(); + let path = if prefix.is_empty() { name.clone() } else { format!("{prefix}/{name}") }; + if e.path().is_dir() { + if path != "golden" { + walk(&e.path(), &path, out); + } + } else if let Ok(b) = std::fs::read(e.path()) { + out.insert(path, b); + } + } + } + let mut out = BTreeMap::new(); + walk(dir, "", &mut out); + out +} diff --git a/crates/xlsx/README.md b/crates/xlsx/README.md index 3d3808ad3..b8669288e 100644 --- a/crates/xlsx/README.md +++ b/crates/xlsx/README.md @@ -83,9 +83,17 @@ for new pictures (`vm = i + 1`) and the `XLDAPR` dynamic-array metadata (`cm = 1 The parts this crate writes use the transitional namespaces; a strict file's kept parts stay as they were. A binary workbook is not written. -A binary workbook gives the same `Workbook`, strings, rows and merged cells, with saved values -only: its formulas are token streams that are not decoded, and its styles are not read (each -cell keeps its format index). +A binary workbook gives the same `Workbook`, strings, rows and merged cells. Its styles are not +read (each cell keeps its format index). Its cell formulas are decoded from their tokens into the +text an `.xlsx` file holds (`_xlfn.` and `_xlpm.` names as written, apart from the four +ISO/IEC 29500 functions `.xlsx` names bare, no implicit `@`, the spaces and line breaks typed in +the formula, numbers as Excel spells them), with +`FormulaKind::Shared` or `FormulaKind::Array` and their ranges, and `BrtCellMeta` as the cell +metadata index. Every cell of a shared formula gets its own text, decoded at the cell, since the +file keeps the tokens once. A formula whose decoding needs something the reader does not read +keeps only its saved result, with a warning saying why: user defined names, table references, +other workbooks, Python code stored outside the cell, data tables. The XLSB function table +(`xlsb/ftab.rs`) and the expression printer are this crate's own, apart from `craft-xls`'s. ## Hostile input @@ -94,8 +102,11 @@ cell keeps its format index). string and what is left of a part, not a sheet's length. - `Limits.binary_records`, `binary_cells`, `binary_text`: a binary workbook, over all its parts (40 million records, 4 million cells and as many shared strings, 256 MiB of text, as - `craft-xls` allows). Fixed caps: 1024 sheets, 100,000 merged ranges per sheet, 64 nested - extension blocks. + `craft-xls` allows). `binary_formula_text`: decoded formula text over the workbook (128 MiB); + past it, formulas keep their saved results. A formula's tokens are bounded at 16 KB, its + nesting at 256 levels and its array constants at 65,536 values in all, each charged before + it is held; once the formula text allowance is spent, no formula is decoded. Fixed caps: 1024 + sheets, 100,000 merged ranges per sheet, 64 nested extension blocks. - Cells and rows outside the 1,048,576 × 16,384 grid are dropped and counted. SpreadsheetML is read leniently: a damaged optional part is a warning, a damaged worksheet keeps diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs index b0771d366..5a64ae0ab 100644 --- a/crates/xlsx/src/lib.rs +++ b/crates/xlsx/src/lib.rs @@ -145,6 +145,10 @@ pub struct Limits { pub binary_cells: usize, /// Bytes of decoded text (shared and inline strings) in a binary workbook, over all its parts. pub binary_text: usize, + /// Bytes of decoded formula text in a binary workbook, over all its sheets. A cell formula + /// may hold 16 KB of tokens, so without a total a million cells of long formulas would cost + /// gigabytes; past it, formulas keep their saved results (the file still opens). + pub binary_formula_text: usize, } impl Default for Limits { @@ -156,6 +160,7 @@ impl Default for Limits { binary_records: 40_000_000, binary_cells: 4_000_000, binary_text: 256 << 20, + binary_formula_text: 128 << 20, } } } diff --git a/crates/xlsx/src/package.rs b/crates/xlsx/src/package.rs index 1c133d0ad..d43a15a8c 100644 --- a/crates/xlsx/src/package.rs +++ b/crates/xlsx/src/package.rs @@ -29,6 +29,9 @@ pub struct Package<'a> { binary: Option<ContentTypes>, workbook_rels: Option<Rels>, budget: xlsb::Budget, + /// What a binary workbook's formulas refer to, once its workbook part is read: `Some(None)` + /// when that couldn't be read (every formula keeps its saved result). + binary_links: Option<Option<xlsb::Links>>, /// Shared strings in a binary workbook, once counted: a cell's index is checked against it. binary_strings: Option<usize>, } @@ -67,6 +70,7 @@ impl<'a> Package<'a> { binary, workbook_rels: None, budget: xlsb::Budget::default(), + binary_links: None, binary_strings: None, }) } @@ -145,7 +149,9 @@ impl<'a> Package<'a> { if self.binary.is_some() { let bytes = self.required(&self.workbook_part.clone())?; let rels = self.workbook_rels()?; - return xlsb::workbook(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings); + let (wb, links) = xlsb::workbook(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings)?; + self.binary_links = Some(links); + return Ok(wb); } let options = self.xml_options(); let root = match self.opc.read_xml(&self.workbook_part, &options)? { @@ -188,9 +194,15 @@ impl<'a> Package<'a> { self.binary_strings = Some(strings.len()); return Ok(strings); } - let Some(rel) = rels.first("sharedStrings").filter(|r| !r.external) else { return Ok(Vec::new()) }; - let Some(bytes) = self.opc.read(&rel.target)? else { - self.warn(format!("missing part {}", rel.target)); + let rel = rels.first("sharedStrings").filter(|r| !r.external); + // Some older spreadsheet writers omit the workbook relationship but still emit the + // conventional shared-string part. The pre-OPC reader accepted that layout, so retain + // compatibility by checking the standard part name only when the relationship is absent. + let target = rel.map_or("xl/sharedStrings.xml", |r| r.target.as_str()); + let Some(bytes) = self.opc.read(target)? else { + if rel.is_some() { + self.warn(format!("missing part {target}")); + } return Ok(Vec::new()); }; let mut items = Vec::new(); @@ -234,8 +246,13 @@ impl<'a> Package<'a> { Some(n) => n, None => self.shared_strings()?.len(), }; + // Formulas name sheets and functions through the workbook part. + if self.binary_links.is_none() { + self.workbook()?; + } let bytes = self.required(&part)?; - let mut sheet = xlsb::worksheet(&bytes, strings, &self.limits, &self.budget, &mut self.warnings, &mut each)?; + let links = self.binary_links.as_ref().and_then(Option::as_ref); + let mut sheet = xlsb::worksheet(&bytes, strings, links, &self.limits, &self.budget, &mut self.warnings, &mut each)?; sheet.part = part; return Ok(sheet); } diff --git a/crates/xlsx/src/sheet.rs b/crates/xlsx/src/sheet.rs index 243430f8e..2691764d5 100644 --- a/crates/xlsx/src/sheet.rs +++ b/crates/xlsx/src/sheet.rs @@ -113,8 +113,10 @@ pub enum FormulaKind { #[derive(Clone, Debug, Default, PartialEq)] pub struct CellFormula { pub kind: FormulaKind, - /// The formula as the file spells it (`_xlfn.` prefixes and all), trimmed. Empty for a - /// cell that shares the formula of its group's first cell. + /// The formula as the file spells it (`_xlfn.` prefixes and all), trimmed. In `.xlsx`, empty + /// for a cell that shares the formula of its group's first cell. A binary workbook (`.xlsb`) + /// stores a shared formula's tokens once, so every cell of the group gets its own text, + /// decoded at the cell. pub text: String, /// `si`: the shared formula group. pub shared_index: Option<u32>, diff --git a/crates/xlsx/src/xlsb.rs b/crates/xlsx/src/xlsb.rs index dbff61dd7..b3f94b5fa 100644 --- a/crates/xlsx/src/xlsb.rs +++ b/crates/xlsx/src/xlsb.rs @@ -1,16 +1,24 @@ //! Binary workbooks ([MS-XLSB]): the workbook part, shared strings and worksheet cells, from -//! their records. Saved values only: formulas are token streams that are not decoded, and -//! styles are not read. A record that does not parse fails the read. +//! their records. Cell formulas are decoded from their tokens ([`formula`]) into the text an +//! `.xlsx` file holds; one that can't be keeps only its saved result, with a warning saying why. +//! Styles are not read. A record that does not parse fails the read. +mod expr; +mod formula; +mod ftab; + +use std::collections::HashMap; use std::sync::Arc; use craft_opc::{ContentTypes, Rels}; use craft_sheet::{CellError, CellRef, MAX_COLS, MAX_ROWS, Range, Visibility}; -use crate::sheet::{Cell, CellValue, Row, SheetPart}; +use crate::sheet::{Cell, CellFormula, CellValue, FormulaKind, Row, SheetPart}; use crate::strings::StringItem; use crate::workbook::{SheetEntry, SheetKind, Workbook}; use crate::{Error, Limits, Warnings}; +pub(crate) use formula::Links; +use formula::{Book, Mode, Name, Xti}; pub(crate) const MAIN: &str = "application/vnd.ms-excel.main"; const BINARY_MAIN: &str = "application/vnd.ms-excel.sheet.binary.macroEnabled.main"; @@ -18,8 +26,14 @@ pub(crate) const WORKSHEET: &str = "application/vnd.ms-excel.worksheet"; pub(crate) const STRINGS: &str = "application/vnd.ms-excel.sharedStrings"; /// Most sheets in the workbook. const MAX_SHEETS: usize = 1024; +/// Supporting links (this workbook, add-ins, other workbooks) read at most; past it, formulas +/// keep their saved results. +const MAX_BOOKS: usize = 65_536; /// Most merged ranges in one worksheet. const MAX_MERGES: usize = 100_000; +/// Defined names (Excel's hidden ones for newer functions included) read at most; past it, the +/// workbook's formulas keep their saved results. +const MAX_NAMES: usize = 65_536; pub(crate) fn invalid(msg: impl Into<String>) -> Error { Error::Invalid(format!("XLSB: {}", msg.into())) @@ -41,9 +55,26 @@ pub(crate) struct Budget { cells: std::cell::Cell<usize>, text: std::cell::Cell<usize>, records: std::cell::Cell<usize>, + formula_text: std::cell::Cell<usize>, } impl Budget { + /// Charges a decoded formula's text if it fits [`Limits::binary_formula_text`]; a formula + /// that doesn't keeps its saved result. + /// Whether formula text of `len` bytes would still fit, without charging it. + fn formula_text_fits(&self, len: usize, limits: &Limits) -> bool { + self.formula_text.get().saturating_add(len) <= limits.binary_formula_text + } + + fn try_formula_text(&self, len: usize, limits: &Limits) -> bool { + let total = self.formula_text.get().saturating_add(len); + let fits = total <= limits.binary_formula_text; + if fits { + self.formula_text.set(total); + } + fits + } + fn text(&self, len: usize, limits: &Limits) -> Result<(), Error> { self.text.set(self.text.get().saturating_add(len)); if self.text.get() > limits.binary_text { @@ -95,6 +126,9 @@ impl<'a> Bytes<'a> { fn u32(&mut self) -> Result<u32, Error> { Ok(u32::from_le_bytes(self.take(4)?.try_into().map_err(|_| invalid("truncated u32"))?)) } + fn i32(&mut self) -> Result<i32, Error> { + Ok(i32::from_le_bytes(self.take(4)?.try_into().map_err(|_| invalid("truncated i32"))?)) + } fn f64(&mut self) -> Result<f64, Error> { let n = f64::from_le_bytes(self.take(8)?.try_into().map_err(|_| invalid("truncated number"))?); @@ -222,12 +256,24 @@ impl<'a, 'l> Records<'a, 'l> { } /// The workbook part: BrtBeginBook, BrtWbProp, the BrtBundleSh list. -pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budget, warnings: &mut Warnings) -> Result<Workbook, Error> { +/// The workbook part, and the tables its formulas refer to ([`Links`]): `None` when those can't +/// be read, so that the workbook still opens, with every formula kept as its saved result. +pub(crate) fn workbook( + bytes: &[u8], + rels: &Rels, + limits: &Limits, + budget: &Budget, + warnings: &mut Warnings, +) -> Result<(Workbook, Option<Links>), Error> { let mut records = Records::new(bytes, limits, budget); records.first(131, warnings)?; let mut wb = Workbook::default(); + let mut links = Some(Links::default()); let mut bundle = false; let mut bundle_seen = false; + // Every BrtBundleSh counts toward the cap, a skipped module sheet too: each keeps a place + // in the sheet links. + let mut bundle_count = 0usize; while let Some((id, payload)) = records.next(warnings)? { let mut b = Bytes::new(payload); match id { @@ -239,7 +285,17 @@ pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budg if wb.sheets.is_empty() { return Err(invalid("no supported worksheets")); } - return Ok(wb); + if links.is_none() { + warnings.warn("XLSB: the workbook's sheet links or names could not be read; formulas keep their saved results"); + } + return Ok((wb, links)); + } + 39 | 355 | 357 | 358 | 362 | 667 => { + if let Some(l) = links.as_mut() + && link_record(id, payload, l).is_err() + { + links = None; + } } 143 => { if bundle_seen { @@ -266,9 +322,10 @@ pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budg if !bundle { return Err(invalid("worksheet outside the worksheet list")); } - if wb.sheets.len() >= MAX_SHEETS { + if bundle_count >= MAX_SHEETS { return Err(Error::TooLarge(format!("XLSB exceeds {MAX_SHEETS} sheets"))); } + bundle_count += 1; let visibility = match b.u32()? { 0 => Visibility::Visible, 1 => Visibility::Hidden, @@ -287,6 +344,10 @@ pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budg return Err(invalid("worksheet relationship is null")); } warnings.warn("XLSB module sheets were skipped"); + // Formulas name sheets by their place in this list, skipped sheets included. + if let Some(l) = links.as_mut() { + l.sheets.push(None); + } continue; }; let rel = rels.by_id(&rel_id).ok_or_else(|| invalid("worksheet relationship is missing"))?; @@ -297,6 +358,11 @@ pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budg if let SheetKind::Other(_) = kind { return Err(invalid("unknown sheet relationship type")); } + // Only worksheets and macro sheets have cells a formula can refer to (a macro's + // name refers to its macro sheet: `Macro1!$A$1`). + if let Some(l) = links.as_mut() { + l.sheets.push(matches!(kind, SheetKind::Worksheet | SheetKind::Macrosheet).then(|| name.clone())); + } wb.sheets.push(SheetEntry { name, sheet_id, visibility, rel_id, kind, part: Some(rel.target.clone()) }); } _ => {} @@ -305,6 +371,51 @@ pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budg Err(invalid("missing workbook end record")) } +/// A supporting link (`BrtSupSelf`, `BrtSupSame`, `BrtSupAddin`, `BrtSupBookSrc`), the sheet links +/// (`BrtExternSheet`) or a defined name (`BrtName`), added to `links`. +fn link_record(id: u16, payload: &[u8], links: &mut Links) -> Result<(), Error> { + let mut b = Bytes::new(payload); + if matches!(id, 355 | 357 | 358 | 667) && links.books.len() >= MAX_BOOKS { + return Err(invalid("too many supporting links")); + } + match id { + 357 | 358 | 667 => { + b.finish()?; + links.books.push(match id { + 357 => Book::This, + 358 => Book::Same, + _ => Book::Addin, + }); + } + 355 => links.books.push(Book::External), + 362 => { + // [MS-XLSB] 2.4.672: cXti "MUST be less than 65536" (PtgRef3d's ixti is 16 bits). + let count = b.u32()?; + if count >= 65_536 || !links.xti.is_empty() { + return Err(invalid("invalid sheet link list")); + } + for _ in 0..count { + let book = b.u32()?; + let (first, last) = (b.i32()?, b.i32()?); + links.xti.push(Xti { book, first, last }); + } + b.finish()?; + } + _ => { + // BrtName ([MS-XLSB] 2.4.718): flags, chKey, itab, then the name; the formula and the + // rest aren't needed to call a function or tell a name from one. + if links.names.len() >= MAX_NAMES { + return Err(invalid("too many defined names")); + } + let flags = b.u32()?; + b.take(5)?; + let text = b.text(255)?; + links.names.push(Name { text, future: flags & (1 << 17) != 0 }); + } + } + Ok(()) +} + /// A `RichStr`: the text; formatting and phonetic runs are skipped. fn rich_string(b: &mut Bytes<'_>) -> Result<String, Error> { let flags = b.u8()?; @@ -395,17 +506,208 @@ fn boolean(b: &mut Bytes<'_>) -> Result<bool, Error> { } } -/// The formula after a cell's saved result: checked for framing, not decoded. -fn skip_formula(b: &mut Bytes<'_>) -> Result<(), Error> { +/// The `grbitFlags` and `CellParsedFormula` after a formula cell's value: its tokens (`rgce`) +/// and their extra data (`rgcb`). The flags' only bit, `fAlwaysCalc`, is the calculator's to know. +fn cell_formula<'a>(b: &mut Bytes<'a>) -> Result<(&'a [u8], &'a [u8]), Error> { b.take(2)?; let cce = b.u32()?; if !(1..=16384).contains(&cce) { return Err(invalid("invalid formula token length")); } - b.take(cce as usize)?; + let rgce = b.take(cce as usize)?; let extra = b.u32()?; - b.take(extra as usize)?; - Ok(()) + let rgcb = b.take(extra as usize)?; + Ok((rgce, rgcb)) +} + +/// A formula's text, or `None` (with a warning saying why) for one that keeps its saved result: +/// the workbook's links couldn't be read, the tokens can't be decoded, or the formula text +/// allowance is spent. +fn decode_formula( + rgce: &[u8], + rgcb: &[u8], + mode: Mode, + links: Option<&Links>, + limits: &Limits, + budget: &Budget, + warnings: &mut Warnings, +) -> Option<String> { + let links = links?; + // Once the allowance is spent no formula fits it, so none is decoded only to be dropped. + if !budget.formula_text_fits(1, limits) { + kept(warnings, "more formula text than the limits allow"); + return None; + } + let text = match formula::decode(rgce, rgcb, links, mode) { + Ok(e) => expr::print(&e), + Err(formula::Unsupported(why)) => { + kept(warnings, why); + return None; + } + }; + if !budget.try_formula_text(text.len(), limits) { + kept(warnings, "more formula text than the limits allow"); + return None; + } + Some(text) +} + +/// Warns, once per reason, that formulas were kept as their saved results. +fn kept(warnings: &mut Warnings, why: &str) { + warnings.warn(format!("XLSB: some formulas were kept as their saved results ({why})")); +} + +/// A `BrtShrFmla`: the cells it may cover, its tokens, its first cell's text length (what a copy +/// is expected to cost) and the group's index (`si`). The tokens are borrowed from the worksheet +/// part, which outlives the sheet's read: a record can be up to 256 MiB, and copying every +/// shared formula's would cost as much again as the part. +#[derive(Clone, Copy)] +struct SharedFormula<'a> { + range: Range, + rgce: &'a [u8], + rgcb: &'a [u8], + len: usize, + si: u32, +} + +/// A formula cell whose tokens are only `PtgExp`: part of a shared or array formula. +enum Part { + /// The first cell: its formula is the `BrtShrFmla` or `BrtArrFmla` record that follows. + First, + /// Another cell of the formula whose first cell is this. + Of(CellRef), +} + +/// `PtgExp` ([MS-XLSB] 2.5.98.40) with its `PtgExtraCol`: the first cell of the shared or array +/// formula this cell belongs to. BIFF12 keeps only the row in the token and the column in rgcb. +fn part_of(rgce: &[u8], rgcb: &[u8], at: CellRef) -> Option<Result<Part, &'static str>> { + let (&ptg, row) = rgce.split_first()?; + if ptg != 0x01 { + return None; + } + let (Ok(row), Ok(col)) = (<[u8; 4]>::try_from(row), <[u8; 4]>::try_from(rgcb)) else { + return Some(Err("malformed shared or array formula references")); + }; + let first = CellRef::new(u32::from_le_bytes(row), u32::from_le_bytes(col)); + Some(Ok(if first == at { Part::First } else { Part::Of(first) })) +} + +/// One sheet's shared and array formulas, by first cell, as the reader meets them. `None` when +/// the formula keeps its values (so its other cells keep theirs). +#[derive(Default)] +struct RangeFormulas<'a> { + shared: HashMap<CellRef, Option<SharedFormula<'a>>>, + arrays: HashMap<CellRef, Option<Range>>, +} + +impl<'a> RangeFormulas<'a> { + /// The formula of another cell `at` of the shared or array formula starting at `first`. A + /// shared formula's copy is decoded from the shared tokens at its own cell, as [MS-XLSB] + /// defines it (relative offsets wrap around the grid), and checked like any formula: its text + /// may be longer than the first cell's. That length estimates its cost, and a copy that can't + /// fit isn't decoded at all, so a long formula shared by a million cells stops costing once + /// the allowance is spent. An array formula's other cells have none, as in `.xlsx`. + fn follower( + &mut self, + at: CellRef, + first: CellRef, + links: Option<&Links>, + limits: &Limits, + budget: &Budget, + warnings: &mut Warnings, + ) -> Option<CellFormula> { + if let Some(shared) = self.shared.get(&first) { + let sh = (*shared)?; + if !sh.range.contains(at) { + kept(warnings, "malformed shared or array formula references"); + return None; + } + if !budget.formula_text_fits(sh.len, limits) { + kept(warnings, "more formula text than the limits allow"); + return None; + } + let Some(text) = decode_formula(sh.rgce, sh.rgcb, Mode::Shared(at), links, limits, budget, warnings) else { + // A copy that was decoded but kept as its value charged nothing: one past the + // allowance (it may be longer than the first cell's estimate) or one that can't be + // decoded. The group's later copies would fail the same way, so they keep their + // values without being decoded: a group costs at most one wasted decode. + self.shared.insert(first, None); + return None; + }; + return Some(CellFormula { kind: FormulaKind::Shared, text, shared_index: Some(sh.si), ..CellFormula::default() }); + } + match self.arrays.get(&first) { + Some(Some(range)) if range.contains(at) => {} + Some(Some(_)) => kept(warnings, "malformed shared or array formula references"), + Some(None) => {} + None => kept(warnings, "a shared or array formula that is missing from the file"), + } + None + } + + /// `BrtShrFmla` (427) or `BrtArrFmla` (426) right after the first cell `first` of its range: + /// the formula that cell keeps, recorded for the range's other cells. A record that can't be + /// read leaves the whole range as values; it never fails the file, as these records were + /// skipped before formulas were read. + #[allow(clippy::too_many_arguments)] + fn range_formula( + &mut self, + id: u16, + payload: &'a [u8], + first: CellRef, + links: Option<&Links>, + limits: &Limits, + budget: &Budget, + warnings: &mut Warnings, + ) -> Option<CellFormula> { + let read = |b: &mut Bytes<'a>| -> Result<(Range, &'a [u8], &'a [u8]), Error> { + let (r0, r1, c0, c1) = (b.u32()?, b.u32()?, b.u32()?, b.u32()?); + if id == 426 { + b.u8()?; // Only fAlwaysCalc, the calculator's to know. + } + let cce = b.u32()?; + if !(1..=16384).contains(&cce) { + return Err(invalid("invalid formula token length")); + } + let rgce = b.take(cce as usize)?; + let cb = b.u32()?; + let rgcb = b.take(cb as usize)?; + if r0 > r1 || c0 > c1 || r1 >= MAX_ROWS || c1 >= MAX_COLS { + return Err(invalid("invalid formula range")); + } + let range = Range::new(CellRef::new(r0, c0), CellRef::new(r1, c1)); + // An array formula's first cell is its range's top-left one. A shared formula's is the + // first cell that uses it, which need not be: the top-left cell may not share it. + let start_ok = if id == 427 { range.contains(first) } else { range.first == first }; + if !start_ok { + return Err(invalid("invalid formula range")); + } + Ok((range, rgce, rgcb)) + }; + let mut b = Bytes::new(payload); + let Ok((range, rgce, rgcb)) = read(&mut b).and_then(|r| b.finish().map(|()| r)) else { + kept(warnings, "malformed shared or array formulas"); + self.shared.insert(first, None); + self.arrays.insert(first, None); + return None; + }; + if id == 427 { + let text = decode_formula(rgce, rgcb, Mode::Shared(first), links, limits, budget, warnings); + let si = u32::try_from(self.shared.len()).unwrap_or(u32::MAX); + let shared = text.as_ref().map(|t| SharedFormula { range, rgce, rgcb, len: t.len(), si }); + self.shared.insert(first, shared); + return text.map(|text| CellFormula { + kind: FormulaKind::Shared, + text, + shared_index: Some(si), + range: Some(range), + ..CellFormula::default() + }); + } + let text = decode_formula(rgce, rgcb, Mode::Cell, links, limits, budget, warnings); + self.arrays.insert(first, text.as_ref().map(|_| range)); + text.map(|text| CellFormula { kind: FormulaKind::Array, text, range: Some(range), ..CellFormula::default() }) + } } fn value(id: u16, b: &mut Bytes<'_>, strings: usize, limits: &Limits, budget: &Budget) -> Result<CellValue, Error> { @@ -442,16 +744,16 @@ fn value(id: u16, b: &mut Bytes<'_>, strings: usize, limits: &Limits, budget: &B } _ => return Err(invalid("unsupported cell record")), }; - if (8..=11).contains(&id) { - skip_formula(b)?; - } Ok(value) } /// A worksheet part: rows (BrtRowHdr) and cells inside BrtBeginSheetData, merged cells after. +/// Formulas refer to the workbook's `links`; with none, each keeps its saved result. +#[allow(clippy::too_many_arguments)] pub(crate) fn worksheet( bytes: &[u8], strings: usize, + links: Option<&Links>, limits: &Limits, budget: &Budget, warnings: &mut Warnings, @@ -464,9 +766,41 @@ pub(crate) fn worksheet( let mut data_seen = false; let mut row: Option<Row> = None; let mut col = None; + // BrtCellMeta applies to the cell record that follows it (a dynamic-array formula), as `cm` + // does in `.xlsx`: a one-based index into the metadata part's cell metadata. Excel may write + // the cell's BrtValueMeta (a rich value, such as a spill error) in between. + let mut meta: Option<u32> = None; + let mut ranges = RangeFormulas::default(); + // The first cell of a shared or array formula, waiting for the record holding the formula. + let mut first: Option<CellRef> = None; while let Some((id, payload)) = records.next(warnings)? { let mut b = Bytes::new(payload); + let cell_metadata = if id == 50 { meta } else { meta.take() }; + if let Some(at) = first.take() { + if matches!(id, 426 | 427) { + let f = ranges.range_formula(id, payload, at, links, limits, budget, warnings); + if let Some(cell) = row.as_mut().and_then(|r| r.cells.last_mut()).filter(|c| c.at == at) { + // A dynamic array's cell metadata describes its formula: with none kept, the + // cell is a value, and `cm` on it would mark a formula that isn't there. + if f.is_none() { + cell.cell_metadata = None; + } + cell.formula = f; + } + continue; + } + // No formula record: the cell stays a value, so its formula's cell metadata goes too. + if let Some(cell) = row.as_mut().and_then(|r| r.cells.last_mut()).filter(|c| c.at == at) { + cell.cell_metadata = None; + } + kept(warnings, "a shared or array formula that is missing from the file"); + } match id { + 49 => { + let icmb = b.i32()?; + b.finish()?; + meta = u32::try_from(icmb).ok().filter(|&i| i >= 1); + } 130 => { if data || !data_seen { return Err(invalid("incomplete worksheet data")); @@ -525,15 +859,44 @@ pub(crate) fn worksheet( } let style = b.u32()?; let value = value(id, &mut b, strings, limits, budget)?; - b.finish()?; + let at = CellRef::new(current.index, c); + let formula = if (8..=11).contains(&id) { + let (rgce, rgcb) = cell_formula(&mut b)?; + b.finish()?; + match part_of(rgce, rgcb, at) { + None => decode_formula(rgce, rgcb, Mode::Cell, links, limits, budget, warnings) + .map(|text| CellFormula { text, ..CellFormula::default() }), + Some(Ok(Part::First)) => { + first = links.map(|_| at); + None + } + Some(Ok(Part::Of(start))) if links.is_some() => ranges.follower(at, start, links, limits, budget, warnings), + Some(Ok(Part::Of(_))) => None, + Some(Err(why)) => { + kept(warnings, why); + None + } + } + } else { + b.finish()?; + None + }; if value != CellValue::Empty { budget.cell(limits)?; } + // A formula record's cell metadata describes its formula (a dynamic array), so a + // formula kept as its value drops it; the first cell of a shared or array formula + // keeps it until its formula record is read. Other cells keep theirs as the file + // has it. + let formula_kept = !(8..=11).contains(&id) || formula.is_some() || first == Some(at); + let cell_metadata = cell_metadata.filter(|_| formula_kept); current.cells.push(Cell { - at: CellRef::new(current.index, c), + at, style: style & 0x00FF_FFFF, phonetic: style & 0x0100_0000 != 0, value, + formula, + cell_metadata, ..Cell::default() }); col = Some(c); diff --git a/crates/xlsx/src/xlsb/expr.rs b/crates/xlsx/src/xlsb/expr.rs new file mode 100644 index 000000000..197644a33 --- /dev/null +++ b/crates/xlsx/src/xlsb/expr.rs @@ -0,0 +1,377 @@ +//! The expression tree an XLSB formula decodes to, and its A1 formula text (without `=`), in the +//! file's spelling (`_xlfn.` and `_xlpm.` names as written). A copy of craft-xls's: the two +//! readers follow separate specifications, and can share one tree when both settle. + +use std::fmt::Write; +use std::sync::Arc; + +use craft_sheet::{CellError, push_col, quote_sheet, sheet_needs_quotes}; + +/// One end of a reference, with `$` anchors. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Anchor { + pub row: u32, + pub col: u32, + pub row_abs: bool, + pub col_abs: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum RefKind { + Cell(Anchor), + Range(Anchor, Anchor), + /// Whole rows `3:5` as (row, absolute) pairs. + Rows(u32, bool, u32, bool), + /// Whole columns `A:C`. + Cols(u32, bool, u32, bool), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum SheetSel { + /// Unqualified: the formula's own sheet. + Current, + Named(String), + /// 3-D span `Sheet1:Sheet3`. + Span(String, String), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Reference { + pub sheet: SheetSel, + pub kind: RefKind, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum UnOp { + Neg, + Plus, + Percent, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum BinOp { + Add, + Sub, + Mul, + Div, + Pow, + Concat, + Eq, + Ne, + Lt, + Gt, + Le, + Ge, + /// `:` between two references. + Range, + /// `,` inside parentheses. + Union, + /// A space between two references. + Intersect, +} + +impl BinOp { + /// How tightly the operator binds, as formula text is read: `:` 90, space 85, `,` 80, `^` 50, + /// `*` `/` 40, `+` `-` 30, `&` 20, comparisons 10. + pub(crate) fn precedence(self) -> u8 { + match self { + BinOp::Range => 90, + BinOp::Intersect => 85, + BinOp::Union => 80, + BinOp::Pow => 50, + BinOp::Mul | BinOp::Div => 40, + BinOp::Add | BinOp::Sub => 30, + BinOp::Concat => 20, + BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge => 10, + } + } + + fn symbol(self) -> &'static str { + match self { + BinOp::Add => "+", + BinOp::Sub => "-", + BinOp::Mul => "*", + BinOp::Div => "/", + BinOp::Pow => "^", + BinOp::Concat => "&", + BinOp::Eq => "=", + BinOp::Ne => "<>", + BinOp::Lt => "<", + BinOp::Gt => ">", + BinOp::Le => "<=", + BinOp::Ge => ">=", + BinOp::Range => ":", + BinOp::Union => ",", + BinOp::Intersect => " ", + } + } +} + +/// A formula's syntax tree. The decoder bounds its depth, so printing and dropping it recurse +/// safely. +#[derive(Debug, PartialEq)] +pub(crate) enum Expr { + Number(f64), + Text(Arc<str>), + Bool(bool), + Error(CellError), + /// Array constant `{1,2;3,4}` (rows of literals). + Array(Vec<Vec<Expr>>), + Ref(Reference), + /// A defined name. + Name(String), + /// Spaces and line breaks typed before and after an expression (`PtgAttrSpace`), which + /// `.xlsx` formula text keeps. + Spaced(String, Box<Expr>, String), + Unary(UnOp, Box<Expr>), + Binary(BinOp, Box<Expr>, Box<Expr>), + Call(String, Vec<Expr>), + /// An omitted argument. + Missing, + Paren(Box<Expr>), +} + +fn push_anchor(s: &mut String, a: &Anchor) { + if a.col_abs { + s.push('$'); + } + push_col(s, a.col); + if a.row_abs { + s.push('$'); + } + let _ = write!(s, "{}", u64::from(a.row) + 1); +} + +fn push_reference(s: &mut String, r: &Reference) { + match &r.sheet { + SheetSel::Current => {} + SheetSel::Named(n) => { + s.push_str(&quote_sheet(n)); + s.push('!'); + } + SheetSel::Span(a, b) => { + let joined = format!("{a}:{b}"); + if sheet_needs_quotes(a) || sheet_needs_quotes(b) { + let _ = write!(s, "'{}'!", joined.replace('\'', "''")); + } else { + let _ = write!(s, "{joined}!"); + } + } + } + let dollar = |abs: bool| if abs { "$" } else { "" }; + match &r.kind { + RefKind::Cell(a) => push_anchor(s, a), + RefKind::Range(a, b) => { + push_anchor(s, a); + s.push(':'); + push_anchor(s, b); + } + RefKind::Rows(r0, a0, r1, a1) => { + let _ = write!(s, "{}{}:{}{}", dollar(*a0), u64::from(*r0) + 1, dollar(*a1), u64::from(*r1) + 1); + } + RefKind::Cols(c0, a0, c1, a1) => { + s.push_str(dollar(*a0)); + push_col(s, *c0); + s.push(':'); + s.push_str(dollar(*a1)); + push_col(s, *c1); + } + } +} + +/// Removes trailing zeros (and a trailing point) from a decimal string. +fn trim_decimal(s: &str) -> String { + if s.contains('.') { + let t = s.trim_end_matches('0').trim_end_matches('.'); + if t == "-0" { "0".into() } else { t.to_string() } + } else { + s.to_string() + } +} + +/// Scientific text like `1.23456789012346E+15` with up to `sig` significant digits. +fn sci_text(n: f64, sig: usize) -> String { + let s = format!("{:.*e}", sig.saturating_sub(1), n); + let Some((mant, exp)) = s.split_once('e') else { return s }; + let mant = trim_decimal(mant); + let e: i32 = exp.parse().unwrap_or(0); + format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs()) +} + +/// A number as Excel spells it in a formula: rounded to 15 significant digits, written out in +/// full (`100000000000000000000`, `0.0000000000000000001`) when that takes at most 21 characters +/// without the sign, and scientific (`1E+21`, `1.5E-19`, `1.23456789012345E-06`) when it would +/// take more. +pub(crate) fn number_to_text(n: f64) -> String { + if n == 0.0 || !n.is_finite() { + return "0".into(); + } + let s = format!("{:.14e}", n.abs()); + let Some((mant, exp)) = s.split_once('e') else { return s }; + let Ok(e) = exp.parse::<i32>() else { return s }; + let digits: String = mant.chars().filter(char::is_ascii_digit).collect(); + let digits = digits.trim_end_matches('0'); + let digits = if digits.is_empty() { "0" } else { digits }; + let k = digits.len() as i32; + let plain_len = if e >= 0 { (e + 1).max(k + i32::from(k > e + 1)) } else { 1 - e + k }; + if plain_len > 21 { + return sci_text(n, 15); + } + let sign = if n < 0.0 { "-" } else { "" }; + let plain = if e >= 0 { + let int = (e + 1) as usize; + if digits.len() <= int { format!("{digits}{}", "0".repeat(int - digits.len())) } else { format!("{}.{}", &digits[..int], &digits[int..]) } + } else { + format!("0.{}{digits}", "0".repeat((-e - 1) as usize)) + }; + format!("{sign}{plain}") +} + +fn number(n: f64) -> String { + let text = number_to_text(n); + // 15 significant digits can round past f64::MAX, which no longer parses. + if text.parse::<f64>().is_ok_and(f64::is_finite) { + return text; + } + let exact = format!("{n:E}"); + match exact.split_once('E') { + Some((m, e)) if !e.starts_with('-') => format!("{m}E+{e}"), + _ => exact, + } +} + +/// Splits a sheet-qualified name at its last `!` outside brackets. +fn sheet_split(n: &str) -> Option<(&str, &str)> { + let mut depth = 0usize; + let mut escaped = false; + let mut at = None; + for (i, c) in n.char_indices() { + if escaped { + escaped = false; + continue; + } + match c { + '\'' if depth > 0 => escaped = true, + '[' => depth = depth.saturating_add(1), + ']' => depth = depth.saturating_sub(1), + '!' if depth == 0 => at = Some(i), + _ => {} + } + } + at.and_then(|i| Some((n.get(..i)?, n.get(i + 1..)?))) +} + +/// Prints an expression in A1 notation, trimmed as the `.xlsx` reader trims formula text. +pub(crate) fn print(e: &Expr) -> String { + let mut s = String::new(); + write_expr(&mut s, e); + match s.trim() { + t if t.len() == s.len() => s, + t => t.to_string(), + } +} + +fn write_args(s: &mut String, args: &[Expr], sep: char) { + for (i, a) in args.iter().enumerate() { + if i > 0 { + s.push(sep); + } + write_expr(s, a); + } +} + +fn write_expr(s: &mut String, e: &Expr) { + match e { + Expr::Number(n) => s.push_str(&number(*n)), + Expr::Text(t) => { + s.push('"'); + s.push_str(&t.replace('"', "\"\"")); + s.push('"'); + } + Expr::Bool(b) => s.push_str(if *b { "TRUE" } else { "FALSE" }), + Expr::Error(err) => s.push_str(err.as_str()), + Expr::Array(rows) => { + s.push('{'); + for (ri, row) in rows.iter().enumerate() { + if ri > 0 { + s.push(';'); + } + write_args(s, row, ','); + } + s.push('}'); + } + Expr::Ref(r) => push_reference(s, r), + Expr::Name(n) => match sheet_split(n) { + // A sheet-qualified name holds the bare sheet name (`My Sheet!Total`): quote it so it parses back. + Some((sheet, name)) => { + s.push_str(&quote_sheet(sheet)); + s.push('!'); + s.push_str(name); + } + None => s.push_str(n), + }, + Expr::Unary(UnOp::Neg, x) => { + s.push('-'); + write_expr(s, x); + } + Expr::Unary(UnOp::Plus, x) => { + s.push('+'); + write_expr(s, x); + } + Expr::Unary(UnOp::Percent, x) => { + write_expr(s, x); + s.push('%'); + } + Expr::Binary(op, a, b) => { + write_expr(s, a); + s.push_str(op.symbol()); + write_expr(s, b); + } + Expr::Call(name, args) => { + s.push_str(name); + s.push('('); + write_args(s, args, ','); + s.push(')'); + } + Expr::Missing => {} + Expr::Paren(x) => { + s.push('('); + write_expr(s, x); + s.push(')'); + } + Expr::Spaced(before, x, after) => { + s.push_str(before); + write_expr(s, x); + s.push_str(after); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numbers_print_with_fifteen_significant_digits() { + assert_eq!(number_to_text(1.0), "1"); + assert_eq!(number_to_text(-2.5), "-2.5"); + assert_eq!(number_to_text(0.1 + 0.2), "0.3"); + assert_eq!(number_to_text(123456789012345.0), "123456789012345"); + // Written out in full up to 21 characters, as Excel writes them in .xlsx. + assert_eq!(number_to_text(1e15), "1000000000000000"); + assert_eq!(number_to_text(1234567890123456.0), "1234567890123460"); + assert_eq!(number_to_text(-1e20), "-100000000000000000000"); + assert_eq!(number_to_text(1e21), "1E+21"); + assert_eq!(number_to_text(1.5e21), "1.5E+21"); + assert_eq!(number_to_text(0.0001), "0.0001"); + assert_eq!(number_to_text(1e-10), "0.0000000001"); + assert_eq!(number_to_text(1e-19), "0.0000000000000000001"); + assert_eq!(number_to_text(1e-20), "1E-20"); + assert_eq!(number_to_text(1.5e-19), "1.5E-19"); + assert_eq!(number_to_text(1.23456789012345e-5), "0.0000123456789012345"); + assert_eq!(number_to_text(1.23456789012345e-6), "1.23456789012345E-06"); + assert_eq!(number_to_text(1234567890.12345), "1234567890.12345"); + assert_eq!(number_to_text(1e100), "1E+100"); + assert!(number(f64::MAX).parse::<f64>().is_ok_and(f64::is_finite)); + } +} diff --git a/crates/xlsx/src/xlsb/formula.rs b/crates/xlsx/src/xlsb/formula.rs new file mode 100644 index 000000000..a7293c0df --- /dev/null +++ b/crates/xlsx/src/xlsb/formula.rs @@ -0,0 +1,771 @@ +//! BIFF12 parsed formulas ([MS-XLSB] 2.2.2, 2.5.98): reverse-Polish `Ptg` tokens back to an +//! expression tree, for cell formulas. The tokens are BIFF8's, but nearly every operand differs +//! (32-bit rows, 14-bit columns, UTF-16 strings, its own array-constant codes, newer functions +//! called through hidden names), so this is its own decoder, with its own function table +//! ([`super::ftab`]) and its own copies of craft-xls's depth guards and limits. Anything outside the +//! token set it knows is reported as unsupported, and the caller keeps the cell's cached value. +//! So is a formula that needs something the reader doesn't read: a user's defined name (XLSB +//! names are not read yet) or Python code stored outside the cell. +//! +//! Names keep their file spelling (`_xlfn.CONCAT`, `_xlpm.x`), as `.xlsx` formula text has them. + +use std::sync::Arc; + +use craft_sheet::{CellError, CellRef, MAX_COLS, MAX_ROWS}; + +use super::expr::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, UnOp}; +use super::ftab::function; + +/// Formula token bytes decoded at most (a cell formula holds at most 16,384). +pub(super) const MAX_RGCE: usize = 16 * 1024; +/// Values in one formula's array constants at most, all of them together: each array is charged +/// before its values are held, so a formula of many arrays can't hold more than this. +const MAX_ARRAY: usize = 65_536; + +/// Why a formula could not be turned back into text. +#[derive(Debug, PartialEq)] +pub(super) struct Unsupported(pub &'static str); + +/// Expression nesting at most: deeper trees would overflow the stack when printed or dropped (a +/// hostile file can chain thousands of PtgParen tokens). +const MAX_DEPTH: usize = 256; + +/// Operand stack entries: an expression and its nesting depth. +type Stack = Vec<(Expr, usize)>; + +/// Pops an operand, recording its depth in `kids` (the deepest operand this token consumed). +fn pop(stack: &mut Stack, kids: &mut usize) -> Result<Expr, Unsupported> { + let (e, d) = stack.pop().ok_or(Unsupported("malformed formula (operand missing)"))?; + *kids = (*kids).max(d); + Ok(e) +} + +fn pop_n(stack: &mut Stack, n: usize, kids: &mut usize) -> Result<Vec<Expr>, Unsupported> { + let at = stack.len().checked_sub(n).ok_or(Unsupported("malformed formula (argument missing)"))?; + let popped = stack.split_off(at); + *kids = popped.iter().map(|(_, d)| *d).fold(*kids, usize::max); + Ok(popped.into_iter().map(|(e, _)| e).collect()) +} + +/// Pushes the result of a token one level above the operands it consumed (two for one with the +/// spacing typed around it, which prints as a level of its own). +fn push(stack: &mut Stack, kids: usize, e: Expr) -> Result<(), Unsupported> { + let depth = kids.saturating_add(1).saturating_add(usize::from(matches!(e, Expr::Spaced(..)))); + if depth > MAX_DEPTH { + return Err(Unsupported("formula nested too deeply")); + } + stack.push((e, depth)); + Ok(()) +} + +/// Spaces and line breaks typed in the formula (`PtgAttrSpace`, [MS-XLSB] 2.5.98.32), waiting +/// for the token they belong to. Excel writes the attribute just before that token: spaces +/// before an operand, an operator's symbol or a function call go in `before`; those before a +/// parenthesis's `(`, or before the `)` of a parenthesis or a call, in `open` and `close`. +#[derive(Default)] +struct Spacing { + before: String, + open: String, + close: String, +} + +/// `e` with `ws` typed before it. +fn spaced_before(e: Expr, ws: String) -> Expr { + match e { + _ if ws.is_empty() => e, + Expr::Spaced(b, x, a) => Expr::Spaced(ws + &b, x, a), + e => Expr::Spaced(ws, Box::new(e), String::new()), + } +} + +/// `e` with `ws` typed after it. +fn spaced_after(e: Expr, ws: String) -> Expr { + match e { + _ if ws.is_empty() => e, + Expr::Spaced(b, x, a) => Expr::Spaced(b, x, a + &ws), + e => Expr::Spaced(String::new(), Box::new(e), ws), + } +} + +/// A call's arguments with the spacing typed before its `)`: after the last argument, or alone +/// between the parentheses (`PI( )`). +fn close_args(mut args: Vec<Expr>, ws: String) -> Vec<Expr> { + if ws.is_empty() { + return args; + } + match args.pop() { + Some(last) => args.push(spaced_after(last, ws)), + None => args.push(Expr::Spaced(String::new(), Box::new(Expr::Missing), ws)), + } + args +} + +/// An error constant's code ([MS-XLSB] 2.5.98.21, `BErr`). +fn error_code(code: u8) -> Option<CellError> { + Some(match code { + 0x00 => CellError::Null, + 0x07 => CellError::Div0, + 0x0F => CellError::Value, + 0x17 => CellError::Ref, + 0x1D => CellError::Name, + 0x24 => CellError::Num, + 0x2A => CellError::NA, + 0x2B => CellError::GettingData, + _ => return None, + }) +} + +/// A supporting link record ([MS-XLSB] 2.2.7.3), in the order of the workbook's externals block. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Book { + /// `BrtSupSelf`: this workbook. + This, + /// `BrtSupSame`: the caller's sheet (macro sheets and names only). + Same, + /// `BrtSupAddin`: add-in functions. + Addin, + /// `BrtSupBookSrc`: another workbook, DDE or OLE. Never followed. + External, +} + +/// Xti ([MS-XLSB] 2.5.173): a supporting link and a range of its sheets. +#[derive(Clone, Copy, Debug)] +pub(super) struct Xti { + pub book: u32, + pub first: i32, + pub last: i32, +} + +/// A `BrtName` as far as cell formulas need it. +#[derive(Clone, Debug)] +pub(super) struct Name { + /// The name as written (`_xlfn.CONCAT`, `_xlpm.x`, `Rate`). + pub text: String, + /// `fFutureFunction`: a hidden name standing for a function newer than the file format. + pub future: bool, +} + +/// Workbook-level tables formulas refer to. +#[derive(Default)] +pub(crate) struct Links { + /// Every sheet's name in `BrtBundleSh` order, `None` for the sheets that hold no cells (chart, + /// dialog and module sheets). + pub(super) sheets: Vec<Option<String>>, + /// Every `BrtName`, in order: `PtgName` indexes them from 1. + pub(super) names: Vec<Name>, + pub(super) books: Vec<Book>, + pub(super) xti: Vec<Xti>, +} + +/// Whether a name stands for a LET parameter (`_xlpm.x`), which only the formula itself defines. +fn is_param(name: &str) -> bool { + name.get(..6).is_some_and(|p| p.eq_ignore_ascii_case("_xlpm.")) +} + +impl Links { + /// The sheets a 3-D reference names, or `None` for a deleted sheet (the reference is `#REF!`). + fn sheet_sel(&self, ixti: u16) -> Result<Option<SheetSel>, Unsupported> { + let x = self.xti.get(usize::from(ixti)).ok_or(Unsupported("reference to a missing sheet link"))?; + match usize::try_from(x.book).ok().and_then(|b| self.books.get(b)) { + Some(Book::This) => {} + Some(Book::External) => return Err(Unsupported("references to other workbooks (external links)")), + Some(_) => return Err(Unsupported("references through add-in or same-sheet links")), + None => return Err(Unsupported("reference to a missing workbook link")), + } + // -1: "the first sheet in the reference cannot be found" (a deleted sheet). + if x.first == -1 || x.last == -1 { + return Ok(None); + } + // -2 (the whole workbook) is for names, not cell references. + let (Ok(first), Ok(last)) = (usize::try_from(x.first), usize::try_from(x.last)) else { + return Err(Unsupported("reference to a missing sheet")); + }; + // A span is spelled by its ends. A sheet between them with no cells (a chart sheet) adds + // nothing to it, and `.xlsx` spells the span the same; an end with no cells can't be named. + let span = self.sheets.get(first..=last).filter(|s| !s.is_empty()).ok_or(Unsupported("reference to a missing sheet"))?; + let (Some(Some(a)), Some(Some(b))) = (span.first(), span.last()) else { + return Err(Unsupported("references to sheets with no cells")); + }; + Ok(Some(if first == last { SheetSel::Named(a.clone()) } else { SheetSel::Span(a.clone(), b.clone()) })) + } +} + +struct Bytes<'a> { + b: &'a [u8], + pos: usize, +} + +const TRUNC: Unsupported = Unsupported("truncated formula"); + +impl Bytes<'_> { + fn take(&mut self, n: usize) -> Result<&[u8], Unsupported> { + let s = self.b.get(self.pos..self.pos.checked_add(n).ok_or(TRUNC)?).ok_or(TRUNC)?; + self.pos += n; + Ok(s) + } + fn u8(&mut self) -> Result<u8, Unsupported> { + self.take(1)?.first().copied().ok_or(TRUNC) + } + fn u16(&mut self) -> Result<u16, Unsupported> { + let s: [u8; 2] = self.take(2)?.try_into().map_err(|_| TRUNC)?; + Ok(u16::from_le_bytes(s)) + } + fn u32(&mut self) -> Result<u32, Unsupported> { + let s: [u8; 4] = self.take(4)?.try_into().map_err(|_| TRUNC)?; + Ok(u32::from_le_bytes(s)) + } + fn f64(&mut self) -> Result<f64, Unsupported> { + let s: [u8; 8] = self.take(8)?.try_into().map_err(|_| TRUNC)?; + let n = f64::from_le_bytes(s); + if !n.is_finite() { + return Err(Unsupported("invalid number constant")); + } + Ok(n) + } + /// `cch` UTF-16 code units; unpaired surrogates are refused, not replaced. + fn chars(&mut self, cch: usize) -> Result<String, Unsupported> { + let units = self.take(cch.checked_mul(2).ok_or(TRUNC)?)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)); + char::decode_utf16(units).collect::<Result<String, _>>().map_err(|_| Unsupported("invalid text constant")) + } +} + +/// The last row and column of the grid: a range from 0 to these is a whole column or row. +const LAST_ROW: u32 = MAX_ROWS - 1; +const LAST_COL: u32 = MAX_COLS - 1; + +/// Where a formula lives: a cell formula's references hold coordinates; a shared formula's +/// relative tokens (`PtgRefN`, `PtgAreaN`) hold offsets from the shared formula's first cell. +#[derive(Clone, Copy, PartialEq)] +pub(super) enum Mode { + Cell, + Shared(CellRef), +} + +/// RgceLoc ([MS-XLSB] 2.5.98.91): a row and a `ColRelShort` (14-bit column, then the +/// column-relative and row-relative flags). In a cell formula the coordinates are absolute +/// whatever the flags say; the flags only decide where `$` goes. +fn anchor(row: u32, col: u16) -> Result<Anchor, Unsupported> { + let c = u32::from(col & 0x3FFF); + if row > LAST_ROW || c > LAST_COL { + return Err(Unsupported("reference outside the grid")); + } + Ok(Anchor { row, col: c, row_abs: col & 0x8000 == 0, col_abs: col & 0x4000 == 0 }) +} + +/// RgceLocRel ([MS-XLSB] 2.5.98.92), in a shared formula: a relative row or column is an offset +/// from `base`, wrapping around the grid (1,048,576 rows, 16,384 columns), as Excel adds them. +/// An absolute one is a coordinate. +fn relative_anchor(row: u32, col: u16, base: CellRef) -> Result<Anchor, Unsupported> { + let (row_rel, col_rel) = (col & 0x8000 != 0, col & 0x4000 != 0); + let r = if row_rel { base.row.wrapping_add(row) % MAX_ROWS } else { row }; + let c = if col_rel { (base.col + u32::from(col & 0x3FFF)) % MAX_COLS } else { u32::from(col & 0x3FFF) }; + anchor(r, (c as u16) | (col & 0xC000)) +} + +fn loc(row: u32, col: u16, mode: Mode) -> Result<Anchor, Unsupported> { + match mode { + Mode::Cell => anchor(row, col), + Mode::Shared(base) => relative_anchor(row, col, base), + } +} + +/// RgceArea: a range spanning every row (or column) is a whole-column (row) reference. +fn area(r0: u32, r1: u32, c0: u16, c1: u16) -> Result<RefKind, Unsupported> { + area_of(anchor(r0, c0)?, anchor(r1, c1)?) +} + +fn area_of(a: Anchor, b: Anchor) -> Result<RefKind, Unsupported> { + Ok(if a.row == 0 && b.row == LAST_ROW { + RefKind::Cols(a.col, a.col_abs, b.col, b.col_abs) + } else if a.col == 0 && b.col == LAST_COL { + RefKind::Rows(a.row, a.row_abs, b.row, b.row_abs) + } else { + RefKind::Range(a, b) + }) +} + +fn reference(sheet: Option<SheetSel>, kind: RefKind) -> Expr { + match sheet { + Some(sheet) => Expr::Ref(Reference { sheet, kind }), + None => Expr::Error(CellError::Ref), + } +} + +/// Decodes a formula's `rgce` (tokens) with its `rgcb` (extra data for array constants and +/// cached areas). Returns the expression, with names in their file spelling, or why it can't be +/// represented. A shared formula's tokens are decoded once for each of its cells +/// (`Mode::Shared` with that cell), whose relative references are offsets from it. +pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Result<Expr, Unsupported> { + if rgce.len() > MAX_RGCE { + return Err(Unsupported("formula too long")); + } + let mut t = Bytes { b: rgce, pos: 0 }; + let mut extra = Bytes { b: rgcb, pos: 0 }; + let mut stack: Stack = Vec::new(); + let mut array_values = MAX_ARRAY; + let mut ws = Spacing::default(); + while t.pos < rgce.len() { + let ptg = t.u8()?; + let mut kids = 0usize; + // Operand classes (reference / value / array) share one token number. + let id = if ptg & 0x60 != 0 { 0x20 | (ptg & 0x1F) } else { ptg }; + // An operand (a constant, reference or name) takes the spacing typed before it; operators, + // calls and parentheses place theirs below, and attribute and cache tokens take none. + let operand = !matches!(id, 0x03..=0x15 | 0x19 | 0x21 | 0x22 | 0x26..=0x29); + let height = stack.len(); + match id { + 0x03..=0x11 => { + let op = match id { + 0x03 => BinOp::Add, + 0x04 => BinOp::Sub, + 0x05 => BinOp::Mul, + 0x06 => BinOp::Div, + 0x07 => BinOp::Pow, + 0x08 => BinOp::Concat, + 0x09 => BinOp::Lt, + 0x0A => BinOp::Le, + 0x0B => BinOp::Eq, + 0x0C => BinOp::Ge, + 0x0D => BinOp::Gt, + 0x0E => BinOp::Ne, + 0x0F => BinOp::Intersect, + 0x10 => BinOp::Union, + _ => BinOp::Range, + }; + let b = pop(&mut stack, &mut kids)?; + let a = pop(&mut stack, &mut kids)?; + // Spacing before the operator's symbol follows the left operand. + let before = std::mem::take(&mut ws.before); + kids = kids.saturating_add(usize::from(!before.is_empty())); + let a = spaced_after(a, before); + push(&mut stack, kids, Expr::Binary(op, Box::new(a), Box::new(b)))?; + } + 0x12..=0x14 => { + let op = match id { + 0x12 => UnOp::Plus, + 0x13 => UnOp::Neg, + _ => UnOp::Percent, + }; + let x = pop(&mut stack, &mut kids)?; + // A sign's spacing comes before it; `%`'s before its symbol, after the operand. + let before = std::mem::take(&mut ws.before); + let e = if op == UnOp::Percent { + kids = kids.saturating_add(usize::from(!before.is_empty())); + Expr::Unary(op, Box::new(spaced_after(x, before))) + } else { + spaced_before(Expr::Unary(op, Box::new(x)), before) + }; + push(&mut stack, kids, e)?; + } + 0x15 => { + let x = pop(&mut stack, &mut kids)?; + let close = std::mem::take(&mut ws.close); + kids = kids.saturating_add(usize::from(!close.is_empty())); + let x = spaced_after(x, close); + let before = std::mem::take(&mut ws.open) + &std::mem::take(&mut ws.before); + push(&mut stack, kids, spaced_before(Expr::Paren(Box::new(x)), before))?; + } + 0x16 => push(&mut stack, kids, Expr::Missing)?, + // PtgStr: cch (u16, at most 255) and always UTF-16, unlike BIFF8. + 0x17 => { + let cch = usize::from(t.u16()?); + if cch > 255 { + return Err(Unsupported("text constant too long")); + } + push(&mut stack, kids, Expr::Text(Arc::from(t.chars(cch)?)))?; + } + 0x19 => { + let kind = t.u8()?; + if kind & 0x04 != 0 { + // PtgAttrChoose: jump table of cOffset + 1 entries. + let n = usize::from(t.u16()?) + 1; + t.take(n * 2)?; + } else { + let data = t.take(2)?; + if kind & 0x40 != 0 { + // PtgAttrSpace / PtgAttrSpaceSemi: PtgAttrSpaceType's `type` and `cch`. + let (kind, n) = (data.first().copied().unwrap_or(0), data.get(1).copied().unwrap_or(0)); + let text = if matches!(kind, 1 | 3 | 5) { "\n" } else { " " }.repeat(usize::from(n)); + match kind { + 0 | 1 | 6 => ws.before.push_str(&text), + 2 | 3 => ws.open.push_str(&text), + 4 | 5 => ws.close.push_str(&text), + _ => return Err(Unsupported("unknown spacing in a formula")), + } + } + } + if kind & 0x10 != 0 { + // PtgAttrSum: SUM of the single operand. + let x = pop(&mut stack, &mut kids)?; + let args = close_args(vec![x], std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call("SUM".into(), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; + } + // Semi (volatile), If, Goto, Baxcel: no effect on the expression. + } + 0x1C => { + let e = t.u8()?; + push(&mut stack, kids, Expr::Error(error_code(e).ok_or(Unsupported("unknown error constant"))?))?; + } + 0x1D => push(&mut stack, kids, Expr::Bool(t.u8()? != 0))?, + 0x1E => push(&mut stack, kids, Expr::Number(f64::from(t.u16()?)))?, + 0x1F => { + let n = t.f64()?; + push(&mut stack, kids, Expr::Number(n))?; + } + 0x20 => { + // PtgArray: 14 unused bytes (Excel leaves junk in them); the values are in rgcb. + t.take(14)?; + push(&mut stack, kids, array_constant(&mut extra, &mut array_values)?)?; + } + 0x21 => { + let iftab = t.u16()?; + let (name, args) = function(iftab).ok_or(Unsupported("unknown function"))?; + let n = usize::try_from(args).map_err(|_| Unsupported("unknown function argument count"))?; + let args = close_args(pop_n(&mut stack, n, &mut kids)?, std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call(name.to_string(), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; + } + 0x22 => { + let n = usize::from(t.u8()?); + let tab = t.u16()?; + if tab & 0x8000 != 0 { + return Err(Unsupported("macro sheet commands")); + } + let mut args = pop_n(&mut stack, n, &mut kids)?; + if tab & 0x7FFF == 0x00FF { + // A function called by name (a newer function, add-in or LAMBDA): the name + // comes first, as a PtgName to a hidden `_xlfn.` name for a newer function. + if args.is_empty() { + return Err(Unsupported("malformed function call")); + } + // Spacing typed after the `(` comes before the name's token: it belongs to the + // first argument. + let (lead, first) = match args.remove(0) { + Expr::Spaced(before, x, _) => (before, *x), + e => (String::new(), e), + }; + let name = match first { + Expr::Name(n) => n, + _ => return Err(Unsupported("function call through an expression")), + }; + if let Some(a) = args.first_mut() { + *a = spaced_before(std::mem::replace(a, Expr::Missing), lead); + } + // `PY(index, …)` runs a script stored elsewhere in the package, which this + // import doesn't read. `PY("code", …)` carries its code and becomes a Python cell. + let py = name.rsplit('.').next().is_some_and(|n| n.eq_ignore_ascii_case("PY")); + if py && !args.first().is_some_and(literal_text) { + return Err(Unsupported("Python code stored outside the cell")); + } + let args = close_args(args, std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call(bare_function(name), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; + } else { + let (name, _) = function(tab & 0x7FFF).ok_or(Unsupported("unknown function"))?; + let args = close_args(args, std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call(name.to_string(), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; + } + } + 0x23 => { + // PtgName: a 1-based index into every BrtName, hidden ones included. + let i = usize::try_from(t.u32()?).ok().and_then(|i| i.checked_sub(1)); + let name = i.and_then(|i| links.names.get(i)).ok_or(Unsupported("reference to a missing defined name"))?; + // Defined names are not imported from XLSB yet: a cell using one would calculate + // to #NAME?, so it keeps its saved result. Newer functions and LET parameters are + // hidden names that the formula text itself defines. + if !name.future && !is_param(&name.text) { + return Err(Unsupported("defined names")); + } + push(&mut stack, kids, Expr::Name(name.text.clone()))?; + } + 0x24 => { + let (r, c) = (t.u32()?, t.u16()?); + push(&mut stack, kids, Expr::Ref(Reference { sheet: SheetSel::Current, kind: RefKind::Cell(anchor(r, c)?) }))?; + } + 0x25 => { + let (r0, r1, c0, c1) = (t.u32()?, t.u32()?, t.u16()?, t.u16()?); + push(&mut stack, kids, Expr::Ref(Reference { sheet: SheetSel::Current, kind: area(r0, r1, c0, c1)? }))?; + } + 0x26 => { + // PtgMemArea: a cache of the sub-expression that follows. Its rgcb entry + // (PtgExtraMem) is a count and 16 bytes per cached area: skip both. + t.take(6)?; + let n = usize::try_from(extra.u32()?).map_err(|_| TRUNC)?; + extra.take(n.checked_mul(16).ok_or(TRUNC)?)?; + } + // PtgMemErr, PtgMemNoMem: 6 bytes; PtgMemFunc: 2. The sub-expression follows them. + 0x27 | 0x28 => { + t.take(6)?; + } + 0x29 => { + t.take(2)?; + } + 0x2A => { + t.take(6)?; + push(&mut stack, kids, Expr::Error(CellError::Ref))?; + } + 0x2B => { + t.take(12)?; + push(&mut stack, kids, Expr::Error(CellError::Ref))?; + } + 0x39 => return Err(Unsupported("names in other workbooks or on other sheets")), + 0x3A => { + let ixti = t.u16()?; + let (r, c) = (t.u32()?, t.u16()?); + let kind = RefKind::Cell(anchor(r, c)?); + push(&mut stack, kids, reference(links.sheet_sel(ixti)?, kind))?; + } + 0x3B => { + let ixti = t.u16()?; + let (r0, r1, c0, c1) = (t.u32()?, t.u32()?, t.u16()?, t.u16()?); + let kind = area(r0, r1, c0, c1)?; + push(&mut stack, kids, reference(links.sheet_sel(ixti)?, kind))?; + } + 0x3C | 0x3D => { + let ixti = t.u16()?; + t.take(if id == 0x3C { 6 } else { 12 })?; + // The sheet link must still be one the reader follows: an external #REF! stays cached. + links.sheet_sel(ixti)?; + push(&mut stack, kids, Expr::Error(CellError::Ref))?; + } + 0x01 => return Err(Unsupported("the shared or array formula form")), + 0x02 => return Err(Unsupported("what-if data tables")), + 0x18 => return Err(Unsupported("structured table references")), + 0x2C => { + let Mode::Shared(_) = mode else { return Err(Unsupported("relative references in a cell formula")) }; + let (r, c) = (t.u32()?, t.u16()?); + push(&mut stack, kids, Expr::Ref(Reference { sheet: SheetSel::Current, kind: RefKind::Cell(loc(r, c, mode)?) }))?; + } + 0x2D => { + let Mode::Shared(_) = mode else { return Err(Unsupported("relative references in a cell formula")) }; + let (r0, r1, c0, c1) = (t.u32()?, t.u32()?, t.u16()?, t.u16()?); + let kind = area_of(loc(r0, c0, mode)?, loc(r1, c1, mode)?)?; + push(&mut stack, kids, Expr::Ref(Reference { sheet: SheetSel::Current, kind }))?; + } + _ => return Err(Unsupported("unknown formula token")), + } + if operand && !ws.before.is_empty() && stack.len() == height + 1 { + let (e, depth) = stack.pop().ok_or(Unsupported("malformed formula (operand missing)"))?; + push(&mut stack, depth, spaced_before(e, std::mem::take(&mut ws.before)))?; + } + if stack.len() > MAX_RGCE { + return Err(Unsupported("formula too complex")); + } + } + let (e, _) = stack.pop().ok_or(Unsupported("malformed formula (operand missing)"))?; + if !stack.is_empty() { + return Err(Unsupported("malformed formula (unused operands)")); + } + Ok(grouped(e, false)) +} + +/// The name a function called through a hidden name is written with in `.xlsx`: that name +/// (`_xlfn.CONCAT`), except for the four ISO/IEC 29500 functions, which `.xlsx` names without the +/// prefix though `.xlsb` calls them as it calls newer functions. +fn bare_function(name: String) -> String { + const ISO: [&str; 4] = ["ISO.CEILING", "ECMA.CEILING", "NETWORKDAYS.INTL", "WORKDAY.INTL"]; + match name.get(..6).filter(|p| p.eq_ignore_ascii_case("_xlfn.")).and(name.get(6..)) { + Some(bare) if ISO.iter().any(|f| f.eq_ignore_ascii_case(bare)) => bare.to_string(), + _ => name, + } +} + +/// Text written out in the formula: a string, or strings joined with `&` (how Python code +/// longer than a string constant is written). +fn literal_text(e: &Expr) -> bool { + match e { + Expr::Text(_) => true, + Expr::Spaced(_, x, _) => literal_text(x), + Expr::Binary(BinOp::Concat, a, b) => literal_text(a) && literal_text(b), + _ => false, + } +} + +/// How many strings a [`literal_text`] chain joins, or `None` for anything else. It accepts +/// what [`literal_text`] does, typed spacing included, so a chain the Python check accepts is +/// one that is written flat. +fn literal_texts(e: &Expr) -> Option<usize> { + match e { + Expr::Text(_) => Some(1), + Expr::Spaced(_, x, _) => literal_texts(x), + Expr::Binary(BinOp::Concat, a, b) => literal_texts(a)?.checked_add(literal_texts(b)?), + _ => None, + } +} + +/// How tightly an expression binds when printed, as the formula parser reads it: binary +/// operators by [`BinOp::precedence`], prefix `+`/`-` at 60 and `%` at 70 (`-2^2` is `(-2)^2`); +/// anything else is one operand. +fn binding(e: &Expr) -> u8 { + match e { + Expr::Binary(op, ..) => op.precedence(), + Expr::Unary(UnOp::Neg | UnOp::Plus, _) => 60, + Expr::Unary(UnOp::Percent, _) => 70, + Expr::Spaced(_, x, _) => binding(x), + _ => u8::MAX, + } +} + +/// The strings of a [`literal_text`] chain, left to right. Spacing typed around a part of the +/// chain stays with that part's first and last strings, where it is written. +fn flatten_texts(e: Expr, out: &mut Vec<Expr>) { + match e { + Expr::Binary(BinOp::Concat, a, b) => { + flatten_texts(*a, out); + flatten_texts(*b, out); + } + Expr::Spaced(before, x, after) if matches!(*x, Expr::Binary(BinOp::Concat, ..)) => { + let start = out.len(); + flatten_texts(*x, out); + if let Some(first) = out.get_mut(start) { + *first = spaced_before(std::mem::replace(first, Expr::Missing), before); + } + if let Some(last) = out.last_mut() { + *last = spaced_after(std::mem::replace(last, Expr::Missing), after); + } + } + text => out.push(text), + } +} + +fn paren(e: Expr) -> Expr { + Expr::Paren(Box::new(e)) +} + +/// The tree with the parentheses its text needs to mean the same. Tokens are reverse Polish, so +/// grouping lives in their order: Excel adds `PtgParen` wherever its text has parentheses, but +/// `1 2 + 3 *` (another writer's, or a crafted file's) would print as `1+2*3`. Binary operators +/// are left-associative; a union in a function's arguments needs parentheses of its own. +/// Recursion follows the decoded tree, which `push` bounds at `MAX_DEPTH` levels. +fn grouped(e: Expr, in_args: bool) -> Expr { + match e { + // Strings joined with `&` are written as one flat chain, however their tokens nest: `&` + // is associative, and `PY("…"&"…")` is read as Python code only in that form. The chain + // nests one level per string, so it is made only up to `MAX_DEPTH` strings, the bound + // `push` keeps on the decoded tree (Excel's 8,192 characters hold at most about 33 + // full-length constants). A longer one prints as its tokens nest, with the parentheses + // that needs: a balanced tree of thousands of strings is only a few levels deep, and + // printing or dropping a chain of thousands would recurse past the stack. + e @ Expr::Binary(BinOp::Concat, ..) if literal_texts(&e).is_some_and(|n| n <= MAX_DEPTH) => { + let mut texts = vec![]; + flatten_texts(e, &mut texts); + let mut texts = texts.into_iter(); + let first = texts.next().unwrap_or(Expr::Missing); + texts.fold(first, |a, b| Expr::Binary(BinOp::Concat, Box::new(a), Box::new(b))) + } + Expr::Binary(op, a, b) => { + let (a, b) = (grouped(*a, in_args), grouped(*b, in_args)); + let a = if binding(&a) < op.precedence() { paren(a) } else { a }; + let b = if binding(&b) <= op.precedence() { paren(b) } else { b }; + let e = Expr::Binary(op, Box::new(a), Box::new(b)); + if in_args && op == BinOp::Union { paren(e) } else { e } + } + Expr::Unary(op, x) => { + let x = grouped(*x, in_args); + // Each of `+`, `-` and `%` takes an operand that binds at least as tightly as a sign. The + // parser reads `-1%` as `-(1%)`, Excel's tokens as `(-1)%`: the same value, so a sign + // under `%` keeps Excel's spelling. + let needs = binding(&x) < 60; + Expr::Unary(op, Box::new(if needs { paren(x) } else { x })) + } + Expr::Paren(x) => paren(grouped(*x, false)), + Expr::Spaced(before, x, after) => Expr::Spaced(before, Box::new(grouped(*x, in_args)), after), + Expr::Call(name, args) => Expr::Call(name, args.into_iter().map(|a| grouped(a, true)).collect()), + other => other, + } +} + +/// PtgExtraArray ([MS-XLSB] 2.5.98.41): row and column counts, then `SerAr` values in row-major +/// order. The type codes are not BIFF8's: 0x00 is a number here, not a missing value. +fn array_constant(b: &mut Bytes<'_>, left: &mut usize) -> Result<Expr, Unsupported> { + let rows = usize::try_from(b.u32()?).map_err(|_| TRUNC)?; + let cols = usize::try_from(b.u32()?).map_err(|_| TRUNC)?; + let values = rows.saturating_mul(cols); + if values == 0 { + return Err(Unsupported("empty array constant")); + } + // Charged before the rows are allocated, against what the formula's arrays may hold in all. + *left = left.checked_sub(values).ok_or(Unsupported("array constants too large"))?; + let mut out = Vec::with_capacity(rows); + for _ in 0..rows { + let mut row = Vec::with_capacity(cols); + for _ in 0..cols { + row.push(match b.u8()? { + 0x00 => Expr::Number(b.f64()?), + 0x01 => { + let cch = usize::from(b.u16()?); + if cch > 255 { + return Err(Unsupported("text constant too long")); + } + Expr::Text(Arc::from(b.chars(cch)?)) + } + 0x02 => Expr::Bool(b.u8()? != 0), + 0x04 => { + let e = b.u8()?; + b.take(3)?; + Expr::Error(error_code(e).ok_or(Unsupported("unknown error constant"))?) + } + _ => return Err(Unsupported("unknown array constant value")), + }); + } + out.push(row); + } + Ok(Expr::Array(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Postfix tokens for `n` empty strings joined by `&` as a balanced tree. + fn balanced_strings(n: usize, out: &mut Vec<u8>) { + if n == 1 { + out.extend([0x17, 0, 0]); + } else { + balanced_strings(n / 2, out); + balanced_strings(n - n / 2, out); + out.push(0x08); + } + } + + #[test] + fn a_spaced_part_of_a_string_chain_is_written_flat() { + // `"x"`, then `"="` typed with a space before it joined to `"1"`, then joined: the tokens + // nest to the right, and the space is on the inner chain. Written flat, as Python code + // must be, with the space where it was typed. + let s = |c: u8| [0x17, 1, 0, c, 0]; + let rgce = [&s(b'x')[..], &[0x19, 0x40, 0, 1], &s(b'=')[..], &s(b'1')[..], &[0x08, 0x08]].concat(); + let e = decode(&rgce, &[], &Links::default(), Mode::Cell).unwrap(); + assert_eq!(super::super::expr::print(&e), "\"x\"& \"=\"&\"1\""); + assert!(literal_text(&e) && literal_texts(&e) == Some(3)); + } + + #[test] + fn a_long_chain_of_strings_stays_within_the_depth_bound() { + // 4,096 strings and 4,095 `&` fill 16,383 token bytes, 13 levels deep as written. Made + // into one flat chain they would be 4,096 levels deep, past what printing and dropping + // the tree may recurse; on a small stack that overflows. They print as written instead. + let mut rgce = vec![]; + balanced_strings(4096, &mut rgce); + assert!(rgce.len() <= MAX_RGCE); + let text = std::thread::Builder::new() + .stack_size(256 * 1024) + .spawn(move || { + let e = decode(&rgce, &[], &Links::default(), Mode::Cell).unwrap(); + let text = super::super::expr::print(&e); + drop(e); + text + }) + .unwrap() + .join() + .unwrap(); + assert_eq!(text.matches("\"\"").count(), 4096); + // A short chain, such as Python code split into constants, is still one flat chain. + let mut short = vec![]; + balanced_strings(4, &mut short); + let e = decode(&short, &[], &Links::default(), Mode::Cell).unwrap(); + assert_eq!(super::super::expr::print(&e), "\"\"&\"\"&\"\"&\"\""); + } +} diff --git a/crates/xlsx/src/xlsb/ftab.rs b/crates/xlsx/src/xlsb/ftab.rs new file mode 100644 index 000000000..efd6e4426 --- /dev/null +++ b/crates/xlsx/src/xlsb/ftab.rs @@ -0,0 +1,521 @@ +//! The XLSB function table ([MS-XLSB] 2.5.98.10, `Ftab`): the functions a `PtgFunc` or +//! `PtgFuncVar` token calls by number. Up to 379 (0x17B) it is the table of [MS-XLS] 2.5.198.17, +//! which craft-xls also carries. The entries from 380 (0x17C) on are the rest of the XLSB table: +//! XLSB files call these functions by number, where `.xls` files call them by name. Kept apart from +//! craft-xls's copy: the two formats follow separate specifications. +//! +//! One entry is not in the specification's table: 468 (0x1D4) is CONVERT. The table has no row +//! for it, but its grammar lists `convert-params` among the fixed-argument functions, and Excel +//! writes `=CONVERT(1,"m","ft")` in `.xlsb` as a `PtgFunc` calling 0x1D4. + +/// (iftab, name, fixed argument count or -1 when the function takes a variable number of +/// arguments), sorted by number. +const FTAB: &[(u16, &str, i8)] = &[ + (0, "COUNT", -1), + (1, "IF", -1), + (2, "ISNA", 1), + (3, "ISERROR", 1), + (4, "SUM", -1), + (5, "AVERAGE", -1), + (6, "MIN", -1), + (7, "MAX", -1), + (8, "ROW", -1), + (9, "COLUMN", -1), + (10, "NA", 0), + (11, "NPV", -1), + (12, "STDEV", -1), + (13, "DOLLAR", -1), + (14, "FIXED", -1), + (15, "SIN", 1), + (16, "COS", 1), + (17, "TAN", 1), + (18, "ATAN", 1), + (19, "PI", 0), + (20, "SQRT", 1), + (21, "EXP", 1), + (22, "LN", 1), + (23, "LOG10", 1), + (24, "ABS", 1), + (25, "INT", 1), + (26, "SIGN", 1), + (27, "ROUND", 2), + (28, "LOOKUP", -1), + (29, "INDEX", -1), + (30, "REPT", 2), + (31, "MID", 3), + (32, "LEN", 1), + (33, "VALUE", 1), + (34, "TRUE", 0), + (35, "FALSE", 0), + (36, "AND", -1), + (37, "OR", -1), + (38, "NOT", 1), + (39, "MOD", 2), + (40, "DCOUNT", 3), + (41, "DSUM", 3), + (42, "DAVERAGE", 3), + (43, "DMIN", 3), + (44, "DMAX", 3), + (45, "DSTDEV", 3), + (46, "VAR", -1), + (47, "DVAR", 3), + (48, "TEXT", 2), + (49, "LINEST", -1), + (50, "TREND", -1), + (51, "LOGEST", -1), + (52, "GROWTH", -1), + (53, "GOTO", 1), + (54, "HALT", -1), + (55, "RETURN", -1), + (56, "PV", -1), + (57, "FV", -1), + (58, "NPER", -1), + (59, "PMT", -1), + (60, "RATE", -1), + (61, "MIRR", 3), + (62, "IRR", -1), + (63, "RAND", 0), + (64, "MATCH", -1), + (65, "DATE", 3), + (66, "TIME", 3), + (67, "DAY", 1), + (68, "MONTH", 1), + (69, "YEAR", 1), + (70, "WEEKDAY", -1), + (71, "HOUR", 1), + (72, "MINUTE", 1), + (73, "SECOND", 1), + (74, "NOW", 0), + (75, "AREAS", 1), + (76, "ROWS", 1), + (77, "COLUMNS", 1), + (78, "OFFSET", -1), + (79, "ABSREF", 2), + (80, "RELREF", 2), + (81, "ARGUMENT", -1), + (82, "SEARCH", -1), + (83, "TRANSPOSE", 1), + (84, "ERROR", -1), + (85, "STEP", 0), + (86, "TYPE", 1), + (87, "ECHO", -1), + (88, "SET.NAME", -1), + (89, "CALLER", 0), + (90, "DEREF", 1), + (91, "WINDOWS", -1), + (92, "SERIES", -1), + (93, "DOCUMENTS", -1), + (94, "ACTIVE.CELL", 0), + (95, "SELECTION", 0), + (96, "RESULT", -1), + (97, "ATAN2", 2), + (98, "ASIN", 1), + (99, "ACOS", 1), + (100, "CHOOSE", -1), + (101, "HLOOKUP", -1), + (102, "VLOOKUP", -1), + (103, "LINKS", -1), + (104, "INPUT", -1), + (105, "ISREF", 1), + (106, "GET.FORMULA", 1), + (107, "GET.NAME", -1), + (108, "SET.VALUE", 2), + (109, "LOG", -1), + (110, "EXEC", -1), + (111, "CHAR", 1), + (112, "LOWER", 1), + (113, "UPPER", 1), + (114, "PROPER", 1), + (115, "LEFT", -1), + (116, "RIGHT", -1), + (117, "EXACT", 2), + (118, "TRIM", 1), + (119, "REPLACE", 4), + (120, "SUBSTITUTE", -1), + (121, "CODE", 1), + (122, "NAMES", -1), + (123, "DIRECTORY", -1), + (124, "FIND", -1), + (125, "CELL", -1), + (126, "ISERR", 1), + (127, "ISTEXT", 1), + (128, "ISNUMBER", 1), + (129, "ISBLANK", 1), + (130, "T", 1), + (131, "N", 1), + (132, "FOPEN", -1), + (133, "FCLOSE", 1), + (134, "FSIZE", 1), + (135, "FREADLN", 1), + (136, "FREAD", 2), + (137, "FWRITELN", 2), + (138, "FWRITE", 2), + (139, "FPOS", -1), + (140, "DATEVALUE", 1), + (141, "TIMEVALUE", 1), + (142, "SLN", 3), + (143, "SYD", 4), + (144, "DDB", -1), + (145, "GET.DEF", -1), + (146, "REFTEXT", -1), + (147, "TEXTREF", -1), + (148, "INDIRECT", -1), + (149, "REGISTER", -1), + (150, "CALL", -1), + (151, "ADD.BAR", -1), + (152, "ADD.MENU", -1), + (153, "ADD.COMMAND", -1), + (154, "ENABLE.COMMAND", -1), + (155, "CHECK.COMMAND", -1), + (156, "RENAME.COMMAND", -1), + (157, "SHOW.BAR", -1), + (158, "DELETE.MENU", -1), + (159, "DELETE.COMMAND", -1), + (160, "GET.CHART.ITEM", -1), + (161, "DIALOG.BOX", 1), + (162, "CLEAN", 1), + (163, "MDETERM", 1), + (164, "MINVERSE", 1), + (165, "MMULT", 2), + (166, "FILES", -1), + (167, "IPMT", -1), + (168, "PPMT", -1), + (169, "COUNTA", -1), + (170, "CANCEL.KEY", -1), + (171, "FOR", -1), + (172, "WHILE", 1), + (173, "BREAK", 0), + (174, "NEXT", 0), + (175, "INITIATE", 2), + (176, "REQUEST", 2), + (177, "POKE", 3), + (178, "EXECUTE", 2), + (179, "TERMINATE", 1), + (180, "RESTART", -1), + (181, "HELP", -1), + (182, "GET.BAR", -1), + (183, "PRODUCT", -1), + (184, "FACT", 1), + (185, "GET.CELL", -1), + (186, "GET.WORKSPACE", 1), + (187, "GET.WINDOW", -1), + (188, "GET.DOCUMENT", -1), + (189, "DPRODUCT", 3), + (190, "ISNONTEXT", 1), + (191, "GET.NOTE", -1), + (192, "NOTE", -1), + (193, "STDEVP", -1), + (194, "VARP", -1), + (195, "DSTDEVP", 3), + (196, "DVARP", 3), + (197, "TRUNC", -1), + (198, "ISLOGICAL", 1), + (199, "DCOUNTA", 3), + (200, "DELETE.BAR", 1), + (201, "UNREGISTER", 1), + (204, "USDOLLAR", -1), + (205, "FINDB", -1), + (206, "SEARCHB", -1), + (207, "REPLACEB", 4), + (208, "LEFTB", -1), + (209, "RIGHTB", -1), + (210, "MIDB", 3), + (211, "LENB", 1), + (212, "ROUNDUP", 2), + (213, "ROUNDDOWN", 2), + (214, "ASC", 1), + (215, "DBCS", 1), + (216, "RANK", -1), + (219, "ADDRESS", -1), + (220, "DAYS360", -1), + (221, "TODAY", 0), + (222, "VDB", -1), + (223, "ELSE", 0), + (224, "ELSE.IF", 1), + (225, "END.IF", 0), + (226, "FOR.CELL", -1), + (227, "MEDIAN", -1), + (228, "SUMPRODUCT", -1), + (229, "SINH", 1), + (230, "COSH", 1), + (231, "TANH", 1), + (232, "ASINH", 1), + (233, "ACOSH", 1), + (234, "ATANH", 1), + (235, "DGET", 3), + (236, "CREATE.OBJECT", -1), + (237, "VOLATILE", -1), + (238, "LAST.ERROR", 0), + (239, "CUSTOM.UNDO", -1), + (240, "CUSTOM.REPEAT", -1), + (241, "FORMULA.CONVERT", -1), + (242, "GET.LINK.INFO", -1), + (243, "TEXT.BOX", -1), + (244, "INFO", 1), + (245, "GROUP", 0), + (246, "GET.OBJECT", -1), + (247, "DB", -1), + (248, "PAUSE", -1), + (251, "RESUME", -1), + (252, "FREQUENCY", 2), + (253, "ADD.TOOLBAR", -1), + (254, "DELETE.TOOLBAR", 1), + (256, "RESET.TOOLBAR", 1), + (257, "EVALUATE", 1), + (258, "GET.TOOLBAR", -1), + (259, "GET.TOOL", -1), + (260, "SPELLING.CHECK", -1), + (261, "ERROR.TYPE", 1), + (262, "APP.TITLE", -1), + (263, "WINDOW.TITLE", -1), + (264, "SAVE.TOOLBAR", -1), + (265, "ENABLE.TOOL", 3), + (266, "PRESS.TOOL", 3), + (267, "REGISTER.ID", -1), + (268, "GET.WORKBOOK", -1), + (269, "AVEDEV", -1), + (270, "BETADIST", -1), + (271, "GAMMALN", 1), + (272, "BETAINV", -1), + (273, "BINOMDIST", 4), + (274, "CHIDIST", 2), + (275, "CHIINV", 2), + (276, "COMBIN", 2), + (277, "CONFIDENCE", 3), + (278, "CRITBINOM", 3), + (279, "EVEN", 1), + (280, "EXPONDIST", 3), + (281, "FDIST", 3), + (282, "FINV", 3), + (283, "FISHER", 1), + (284, "FISHERINV", 1), + (285, "FLOOR", 2), + (286, "GAMMADIST", 4), + (287, "GAMMAINV", 3), + (288, "CEILING", 2), + (289, "HYPGEOMDIST", 4), + (290, "LOGNORMDIST", 3), + (291, "LOGINV", 3), + (292, "NEGBINOMDIST", 3), + (293, "NORMDIST", 4), + (294, "NORMSDIST", 1), + (295, "NORMINV", 3), + (296, "NORMSINV", 1), + (297, "STANDARDIZE", 3), + (298, "ODD", 1), + (299, "PERMUT", 2), + (300, "POISSON", 3), + (301, "TDIST", 3), + (302, "WEIBULL", 4), + (303, "SUMXMY2", 2), + (304, "SUMX2MY2", 2), + (305, "SUMX2PY2", 2), + (306, "CHITEST", 2), + (307, "CORREL", 2), + (308, "COVAR", 2), + (309, "FORECAST", 3), + (310, "FTEST", 2), + (311, "INTERCEPT", 2), + (312, "PEARSON", 2), + (313, "RSQ", 2), + (314, "STEYX", 2), + (315, "SLOPE", 2), + (316, "TTEST", 4), + (317, "PROB", -1), + (318, "DEVSQ", -1), + (319, "GEOMEAN", -1), + (320, "HARMEAN", -1), + (321, "SUMSQ", -1), + (322, "KURT", -1), + (323, "SKEW", -1), + (324, "ZTEST", -1), + (325, "LARGE", 2), + (326, "SMALL", 2), + (327, "QUARTILE", 2), + (328, "PERCENTILE", 2), + (329, "PERCENTRANK", -1), + (330, "MODE", -1), + (331, "TRIMMEAN", 2), + (332, "TINV", 2), + (334, "MOVIE.COMMAND", -1), + (335, "GET.MOVIE", -1), + (336, "CONCATENATE", -1), + (337, "POWER", 2), + (338, "PIVOT.ADD.DATA", -1), + (339, "GET.PIVOT.TABLE", -1), + (340, "GET.PIVOT.FIELD", -1), + (341, "GET.PIVOT.ITEM", -1), + (342, "RADIANS", 1), + (343, "DEGREES", 1), + (344, "SUBTOTAL", -1), + (345, "SUMIF", -1), + (346, "COUNTIF", 2), + (347, "COUNTBLANK", 1), + (348, "SCENARIO.GET", -1), + (349, "OPTIONS.LISTS.GET", 1), + (350, "ISPMT", 4), + (351, "DATEDIF", 3), + (352, "DATESTRING", 1), + (353, "NUMBERSTRING", 2), + (354, "ROMAN", -1), + (355, "OPEN.DIALOG", -1), + (356, "SAVE.DIALOG", -1), + (357, "VIEW.GET", -1), + (358, "GETPIVOTDATA", -1), + (359, "HYPERLINK", -1), + (360, "PHONETIC", 1), + (361, "AVERAGEA", -1), + (362, "MAXA", -1), + (363, "MINA", -1), + (364, "STDEVPA", -1), + (365, "VARPA", -1), + (366, "STDEVA", -1), + (367, "VARA", -1), + (368, "BAHTTEXT", 1), + (369, "THAIDAYOFWEEK", 1), + (370, "THAIDIGIT", 1), + (371, "THAIMONTHOFYEAR", 1), + (372, "THAINUMSOUND", 1), + (373, "THAINUMSTRING", 1), + (374, "THAISTRINGLENGTH", 1), + (375, "ISTHAIDIGIT", 1), + (376, "ROUNDBAHTDOWN", 1), + (377, "ROUNDBAHTUP", 1), + (378, "THAIYEAR", 1), + (379, "RTD", -1), + (380, "CUBEVALUE", -1), + (381, "CUBEMEMBER", -1), + (382, "CUBEMEMBERPROPERTY", 3), + (383, "CUBERANKEDMEMBER", -1), + (384, "HEX2BIN", -1), + (385, "HEX2DEC", 1), + (386, "HEX2OCT", -1), + (387, "DEC2BIN", -1), + (388, "DEC2HEX", -1), + (389, "DEC2OCT", -1), + (390, "OCT2BIN", -1), + (391, "OCT2HEX", -1), + (392, "OCT2DEC", 1), + (393, "BIN2DEC", 1), + (394, "BIN2OCT", -1), + (395, "BIN2HEX", -1), + (396, "IMSUB", 2), + (397, "IMDIV", 2), + (398, "IMPOWER", 2), + (399, "IMABS", 1), + (400, "IMSQRT", 1), + (401, "IMLN", 1), + (402, "IMLOG2", 1), + (403, "IMLOG10", 1), + (404, "IMSIN", 1), + (405, "IMCOS", 1), + (406, "IMEXP", 1), + (407, "IMARGUMENT", 1), + (408, "IMCONJUGATE", 1), + (409, "IMAGINARY", 1), + (410, "IMREAL", 1), + (411, "COMPLEX", -1), + (412, "IMSUM", -1), + (413, "IMPRODUCT", -1), + (414, "SERIESSUM", 4), + (415, "FACTDOUBLE", 1), + (416, "SQRTPI", 1), + (417, "QUOTIENT", 2), + (418, "DELTA", -1), + (419, "GESTEP", -1), + (420, "ISEVEN", 1), + (421, "ISODD", 1), + (422, "MROUND", 2), + (423, "ERF", -1), + (424, "ERFC", 1), + (425, "BESSELJ", 2), + (426, "BESSELK", 2), + (427, "BESSELY", 2), + (428, "BESSELI", 2), + (429, "XIRR", -1), + (430, "XNPV", 3), + (431, "PRICEMAT", -1), + (432, "YIELDMAT", -1), + (433, "INTRATE", -1), + (434, "RECEIVED", -1), + (435, "DISC", -1), + (436, "PRICEDISC", -1), + (437, "YIELDDISC", -1), + (438, "TBILLEQ", 3), + (439, "TBILLPRICE", 3), + (440, "TBILLYIELD", 3), + (441, "PRICE", -1), + (442, "YIELD", -1), + (443, "DOLLARDE", 2), + (444, "DOLLARFR", 2), + (445, "NOMINAL", 2), + (446, "EFFECT", 2), + (447, "CUMPRINC", 6), + (448, "CUMIPMT", 6), + (449, "EDATE", 2), + (450, "EOMONTH", 2), + (451, "YEARFRAC", -1), + (452, "COUPDAYBS", -1), + (453, "COUPDAYS", -1), + (454, "COUPDAYSNC", -1), + (455, "COUPNCD", -1), + (456, "COUPNUM", -1), + (457, "COUPPCD", -1), + (458, "DURATION", -1), + (459, "MDURATION", -1), + (460, "ODDLPRICE", -1), + (461, "ODDLYIELD", -1), + (462, "ODDFPRICE", -1), + (463, "ODDFYIELD", -1), + (464, "RANDBETWEEN", 2), + (465, "WEEKNUM", -1), + (466, "AMORDEGRC", -1), + (467, "AMORLINC", -1), + (468, "CONVERT", 3), + (469, "ACCRINT", -1), + (470, "ACCRINTM", -1), + (471, "WORKDAY", -1), + (472, "NETWORKDAYS", -1), + (473, "GCD", -1), + (474, "MULTINOMIAL", -1), + (475, "LCM", -1), + (476, "FVSCHEDULE", 2), + (477, "CUBEKPIMEMBER", -1), + (478, "CUBESET", -1), + (479, "CUBESETCOUNT", 1), + (480, "IFERROR", 2), + (481, "COUNTIFS", -1), + (482, "SUMIFS", -1), + (483, "AVERAGEIF", -1), + (484, "AVERAGEIFS", -1), +]; + +/// The function a `PtgFunc` or `PtgFuncVar` calls: its name and fixed argument count (-1 when it +/// takes a variable number). `None` for a number the table doesn't assign. +pub(super) fn function(iftab: u16) -> Option<(&'static str, i8)> { + FTAB.binary_search_by_key(&iftab, |(i, _, _)| *i).ok().and_then(|i| FTAB.get(i)).map(|(_, n, a)| (*n, *a)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn xlsb_function_numbers() { + // `function` binary-searches the table: sorted, each number once. + assert!(FTAB.windows(2).all(|w| w[0].0 < w[1].0)); + // The [MS-XLS] part, unchanged. + assert_eq!(function(0), Some(("COUNT", -1))); + assert_eq!(function(379), Some(("RTD", -1))); + // [MS-XLSB] 2.5.98.10 continues the table from 0x17C. Excel writes these by number in + // XLSB: PtgFunc for a fixed argument count, PtgFuncVar otherwise. + assert_eq!(function(0x17C), Some(("CUBEVALUE", -1))); + assert_eq!(function(449), Some(("EDATE", 2))); + assert_eq!(function(480), Some(("IFERROR", 2))); + assert_eq!(function(482), Some(("SUMIFS", -1))); + // Not in the specification's table, but what Excel writes for CONVERT. + assert_eq!(function(0x1D4), Some(("CONVERT", 3))); + assert_eq!(function(0x17B), Some(("RTD", -1))); + assert_eq!(function(0x1E5), None); + } +} diff --git a/crates/xlsx/tests/common/mod.rs b/crates/xlsx/tests/common/mod.rs index 59d3d8372..30703b3cd 100644 --- a/crates/xlsx/tests/common/mod.rs +++ b/crates/xlsx/tests/common/mod.rs @@ -3,12 +3,15 @@ use std::collections::BTreeMap; -use craft_xlsx::{CellRef, Error, Limits, Package, Range, SheetKind, Value, Visibility}; +use craft_xlsx::{CellFormula, CellRef, Error, Limits, Package, Range, SheetKind, Value, Visibility}; pub struct Sheet { pub name: String, pub visibility: Visibility, pub cells: BTreeMap<CellRef, Value>, + /// Every cell's formula, and its cell metadata index (`cm`), where it has one. + pub formulas: BTreeMap<CellRef, CellFormula>, + pub cell_metadata: BTreeMap<CellRef, u32>, pub merges: Vec<Range>, } @@ -16,6 +19,11 @@ impl Sheet { pub fn value(&self, at: CellRef) -> Value { self.cells.get(&at).cloned().unwrap_or_default() } + + /// The formula text at `at`, if the cell has a formula. + pub fn formula(&self, at: CellRef) -> Option<&str> { + self.formulas.get(&at).map(|f| f.text.as_str()) + } } pub struct Book { @@ -37,8 +45,15 @@ pub fn read_with(bytes: &[u8], limits: &Limits) -> Result<Book, Error> { continue; } let mut cells = BTreeMap::new(); + let (mut formulas, mut cell_metadata) = (BTreeMap::new(), BTreeMap::new()); let part = p.sheet(e, |row| { for c in row.cells { + if let Some(f) = c.formula { + formulas.insert(c.at, f); + } + if let Some(m) = c.cell_metadata { + cell_metadata.insert(c.at, m); + } let v = c.value.resolve(&strings, wb.date_1904); if !v.is_empty() { cells.insert(c.at, v); @@ -46,7 +61,7 @@ pub fn read_with(bytes: &[u8], limits: &Limits) -> Result<Book, Error> { } Ok(()) })?; - book.sheets.push(Sheet { name: e.name.clone(), visibility: e.visibility, cells, merges: part.merges }); + book.sheets.push(Sheet { name: e.name.clone(), visibility: e.visibility, cells, formulas, cell_metadata, merges: part.merges }); } book.warnings = p.warnings().to_vec(); Ok(book) diff --git a/crates/xlsx/tests/xlsb.rs b/crates/xlsx/tests/xlsb.rs index cef6d9cbe..748d1b86d 100644 --- a/crates/xlsx/tests/xlsb.rs +++ b/crates/xlsx/tests/xlsb.rs @@ -5,7 +5,7 @@ mod common; use common::{read, read_with}; use craft_xlsx::testing::zip; -use craft_xlsx::{CellError, CellRef, Error, Limits, Range, SheetKind, Value, Visibility, is_xlsb}; +use craft_xlsx::{CellError, CellRef, Error, FormulaKind, Limits, Range, SheetKind, Value, Visibility, is_xlsb}; const ROOT: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="book" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="records/book.bin"/></Relationships>"#; const RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="one" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="../data/one.bin"/><Relationship Id="two" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="../data/two.bin"/><Relationship Id="strings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="../text/strings.bin"/></Relationships>"#; @@ -442,3 +442,641 @@ fn phonetic_runs_use_documented_size_and_tolerate_padding() { } assert!(read(&file(&worksheet(&[row(0), cell(62, 0, &phonetic(2, 12))].concat(), &[]))).is_err()); } + +/// A formula cell (`BrtFmlaNum`, cached 0) with its own tokens and extra data. +fn formula_cell(col: u32, rgce: &[u8], rgcb: &[u8]) -> Vec<u8> { + let mut data = col.to_le_bytes().to_vec(); + data.extend([0; 4]); + data.extend(0f64.to_le_bytes()); + data.extend([0; 2]); + data.extend((rgce.len() as u32).to_le_bytes()); + data.extend(rgce); + data.extend((rgcb.len() as u32).to_le_bytes()); + data.extend(rgcb); + record(9, &data) +} + +fn name(flags: u32, text: &str) -> Vec<u8> { + let mut data = flags.to_le_bytes().to_vec(); + data.push(0); + data.extend(u32::MAX.to_le_bytes()); // Workbook scope. + data.extend(wide(text)); + data.extend([2, 0, 0, 0, 0x1c, 0x1d, 0, 0, 0, 0]); // Formula `#NAME?`, no extra data. + data.extend(u32::MAX.to_le_bytes()); // No comment. + record(39, &data) +} + +/// `book(false)` with a supporting-link block and defined names, as Excel writes them: this +/// workbook, then another; sheet links Data, Hidden, Data:Hidden, a deleted sheet and the other +/// workbook; hidden names for CONCAT, LET and a LET parameter, then the user name Rate. +fn book_with_links(extern_sheet: &[u8]) -> Vec<u8> { + let plain = book(false); + let end = record(132, &[]); + let mut out = plain[..plain.len() - end.len()].to_vec(); + out.extend(record(353, &[])); + out.extend(record(357, &[])); + out.extend(record(355, &wide("rId9"))); + out.extend(record(362, extern_sheet)); + out.extend(record(354, &[])); + const FUTURE: u32 = 0x0002_000b; + out.extend(name(FUTURE, "_xlfn.CONCAT")); + out.extend(name(FUTURE, "_xlfn.LET")); + out.extend(name(0x0002_0019, "_xlpm.x")); + out.extend(name(0, "Rate")); + out.extend(end); + out +} + +fn xti() -> Vec<u8> { + let mut out = 5u32.to_le_bytes().to_vec(); + for (book, first, last) in [(0u32, 0i32, 0i32), (0, 1, 1), (0, 0, 1), (0, -1, -1), (1, 0, 0)] { + out.extend(book.to_le_bytes()); + out.extend(first.to_le_bytes()); + out.extend(last.to_le_bytes()); + } + out +} + +fn loc(row: u32, col: u16) -> Vec<u8> { + [&row.to_le_bytes()[..], &col.to_le_bytes()].concat() +} + +/// Relative row and column flags of a `ColRelShort`. +const REL: u16 = 0xC000; + +fn warned(wb: &common::Book, why: &str) -> bool { + wb.warnings.iter().any(|w| w.contains("kept as their saved results") && w.contains(why)) +} + +#[test] +fn cell_formulas_are_read_in_their_xlsx_spelling() { + let ref3d = |ixti: u16, row: u32, col: u16| [&[0x5Au8][..], &ixti.to_le_bytes(), &loc(row, col)].concat(); + let cells: Vec<(u32, Vec<u8>, Vec<u8>)> = vec![ + (1, [&[0x44u8][..], &loc(0, REL), &[0x1E, 2, 0, 0x05]].concat(), vec![]), + (2, [&[0x25u8][..], &0u32.to_le_bytes(), &1u32.to_le_bytes(), &0u16.to_le_bytes(), &REL.to_le_bytes(), &[0x19, 0x10, 0, 0]].concat(), vec![]), + (3, ref3d(1, 1, 1 | REL), vec![]), + ( + 4, + [ + &[0x3Bu8][..], + &2u16.to_le_bytes(), + &0u32.to_le_bytes(), + &0xFFFFFu32.to_le_bytes(), + &REL.to_le_bytes(), + &REL.to_le_bytes(), + &[0x19, 0x10, 0, 0], + ] + .concat(), + vec![], + ), + (5, [&[0x23u8, 1, 0, 0, 0][..], &[0x17, 1, 0, b'a', 0], &[0x17, 1, 0, b'b', 0], &[0x42, 3, 0xFF, 0]].concat(), vec![]), + (6, vec![0x1E, 1, 0, 0x1E, 0, 0, 0x06, 0x1E, 2, 0, 0x41, 0xE0, 0x01], vec![]), + ( + 7, + [&[0x60u8][..], &[0xAB; 14]].concat(), + [&2u32.to_le_bytes()[..], &2u32.to_le_bytes(), &[0], &1f64.to_le_bytes(), &[1, 1, 0, b'x', 0], &[2, 1], &[4, 0x2A, 0, 0, 0]].concat(), + ), + ( + 8, + [&[0x23u8, 2, 0, 0, 0][..], &[0x23, 3, 0, 0, 0, 0x1E, 1, 0], &[0x23, 3, 0, 0, 0, 0x1E, 1, 0, 0x03], &[0x42, 4, 0xFF, 0]].concat(), + vec![], + ), + (9, ref3d(3, 0, 0), vec![]), + (10, [&[0x25u8][..], &0u32.to_le_bytes(), &1u32.to_le_bytes(), &REL.to_le_bytes(), &REL.to_le_bytes(), &[0x41, 20, 0]].concat(), vec![]), + // Kept as their saved results: + (11, vec![0x43, 4, 0, 0, 0, 0x1E, 2, 0, 0x05], vec![]), + (12, ref3d(4, 0, REL), vec![]), + (13, vec![0x01, 0, 0, 0, 0], vec![0, 0, 0, 0]), // Part of a shared formula at A1 that isn't one. + ]; + let mut data = row(0); + data.extend(cell(5, 0, &3.0f64.to_le_bytes())); + for (col, rgce, rgcb) in &cells { + data.extend(formula_cell(*col, rgce, rgcb)); + } + data.extend(record(49, &1u32.to_le_bytes())); // BrtCellMeta: the next formula is a dynamic array. + data.extend(formula_cell(14, &[0x1E, 1, 0], &[])); + data.extend(formula_cell(15, &[0x18, 0x19, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], &[])); // A table reference. + let wb = read(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + let sheet = &wb.sheets[0]; + let got: Vec<_> = (1..=15).map(|c| sheet.formula(CellRef::new(0, c))).collect(); + // As an `.xlsx` file holds them: names in their file spelling (`_xlfn.`, `_xlpm.`), and no + // implicit `@`, which is how a calculator reads a legacy formula, not how the file spells it. + let want = [ + Some("A1*2"), + Some("SUM($A$1:A2)"), + Some("Hidden!B2"), + Some("SUM(Data:Hidden!A:A)"), + Some("_xlfn.CONCAT(\"a\",\"b\")"), + Some("IFERROR(1/0,2)"), + Some("{1,\"x\";TRUE,#N/A}"), + Some("_xlfn.LET(_xlpm.x,1,_xlpm.x+1)"), + Some("#REF!"), + Some("SQRT(A1:A2)"), + None, + None, + None, + // A BrtCellMeta before a cell gives it cell metadata, as `cm` does in .xlsx. + Some("1"), + None, + ]; + assert_eq!(got, want); + assert!(sheet.formulas.values().all(|f| f.kind == FormulaKind::Normal)); + assert_eq!(sheet.cell_metadata.iter().collect::<Vec<_>>(), [(&CellRef::new(0, 14), &1)]); + // Every formula cell keeps its saved result as its value. + assert!((1..=15).all(|c| sheet.value(CellRef::new(0, c)) == Value::Number(0.0))); + for why in ["defined names", "other workbooks", "missing from the file", "structured table references"] { + assert!(warned(&wb, why), "{why}: {:?}", wb.warnings); + } +} + +#[test] +fn unreadable_links_keep_every_formula_as_its_value() { + // A sheet-link count past the spec's limit, and a truncated list: the file opens as it did + // before formulas were read, with values only. + let mut truncated = xti(); + truncated.truncate(20); + for extern_sheet in [70_000u32.to_le_bytes().to_vec(), truncated] { + let data = [row(0), formula_cell(0, &[0x1E, 1, 0], &[])].concat(); + let wb = read(&package(&book_with_links(&extern_sheet), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None); + assert_eq!(wb.sheets[0].value(CellRef::new(0, 0)), Value::Number(0.0)); + assert!(wb.warnings.iter().any(|w| w.contains("could not be read")), "{:?}", wb.warnings); + } +} + +#[test] +fn formula_grouping_follows_token_order() { + // Reverse-Polish tokens group by their order alone. Excel writes PtgParen wherever its text + // has parentheses, but another writer need not: the text gets the ones it needs to mean the + // same, and no more. + let a = |row: u32| [&[0x24u8][..], &loc(row, REL)].concat(); + let int = |n: u8| vec![0x1E, n, 0]; + let cases: Vec<(Vec<u8>, &str)> = vec![ + ([int(1), int(2), vec![0x03], int(3), vec![0x05]].concat(), "(1+2)*3"), + ([int(1), int(2), int(3), vec![0x04, 0x04]].concat(), "1-(2-3)"), + ([int(1), int(2), vec![0x04], int(3), vec![0x04]].concat(), "1-2-3"), + ([int(2), vec![0x13], int(2), vec![0x07]].concat(), "-2^2"), + ([int(2), int(2), vec![0x07, 0x13]].concat(), "-(2^2)"), + // Excel's tokens for its own `-1%`: the parser groups it the other way, to the same value. + ([int(1), vec![0x13, 0x14]].concat(), "-1%"), + ([int(1), int(2), vec![0x03, 0x14]].concat(), "(1+2)%"), + ([a(0), a(1), vec![0x10], vec![0x19, 0x10, 0, 0]].concat(), "SUM((A1,A2))"), + ([int(1), int(2), vec![0x03, 0x15], int(3), vec![0x05]].concat(), "(1+2)*3"), + ]; + let data: Vec<u8> = + [row(0)].into_iter().chain(cases.iter().enumerate().map(|(i, (rgce, _))| formula_cell(i as u32, rgce, &[]))).flatten().collect(); + let wb = read(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + for (i, (_, want)) in cases.iter().enumerate() { + assert_eq!(wb.sheets[0].formula(CellRef::new(0, i as u32)), Some(*want)); + } +} + +#[test] +fn functions_past_0x17b_are_called_by_number() { + // [MS-XLSB] 2.5.98.10's numbers past the .xls table: IFERROR (PtgFunc) and SUMIFS (PtgFuncVar). + let sumifs = [&[0x1Eu8, 1, 0][..], &[0x1E, 2, 0], &[0x17, 2, 0, b'>', 0, b'0', 0], &[0x42, 3, 0xE2, 0x01]].concat(); + let data = [row(0), formula_cell(0, &[0x1E, 1, 0, 0x1E, 2, 0, 0x41, 0xE0, 0x01], &[]), formula_cell(1, &sumifs, &[])].concat(); + let wb = read(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), Some("IFERROR(1,2)")); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 1)), Some("SUMIFS(1,2,\">0\")")); +} + +#[test] +fn hostile_formula_tokens_keep_the_saved_result() { + let mut deep = vec![0x1E, 1, 0]; + deep.resize(16384, 0x15); // Thousands of parentheses: refused by the depth guard. + let empty_array = [&[0x60u8][..], &[0; 14]].concat(); + let bad: Vec<(Vec<u8>, Vec<u8>)> = vec![ + (vec![0x1E, 1], vec![]), // Truncated PtgInt. + (vec![0x17, 1, 0, 0x00, 0xD8], vec![]), // Unpaired surrogate. + (vec![0x17, 0, 1], vec![]), // Text constant over 255. + ([&[0x24u8][..], &loc(1_048_576, 0)].concat(), vec![]), // Row past the grid. + (empty_array.clone(), vec![0; 8]), // Empty array constant. + (empty_array, vec![0xFF; 8]), // Huge one. + (vec![0x1E, 1, 0, 0x1E, 2, 0], vec![]), // Unused operand. + (vec![0x21, 0xD4, 0x01], vec![]), // Unassigned function number. + (vec![0x2C, 0, 0, 0, 0, 0, 0], vec![]), // PtgRefN outside a shared formula. + (vec![0x23, 0xFF, 0xFF, 0xFF, 0xFF], vec![]), // Name index past the list. + ([&[0x5Au8][..], &9u16.to_le_bytes(), &loc(0, 0)].concat(), vec![]), // Missing sheet link. + (deep, vec![]), + ]; + for (rgce, rgcb) in bad { + let data = [row(0), formula_cell(0, &rgce, &rgcb)].concat(); + let wb = read(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None, "{rgce:?}"); + assert_eq!(wb.sheets[0].value(CellRef::new(0, 0)), Value::Number(0.0)); + } +} + +#[test] +fn python_formulas_need_their_code_in_the_cell() { + // `PY("code", 0)` carries its code; `PY(0, 0)` names a script elsewhere in the package, which + // the reader doesn't read, and keeps its saved result. + let mut book = book_with_links(&xti()); + let end = record(132, &[]); + book.truncate(book.len() - end.len()); + book.extend(name(0x0002_000b, "_xlfn._xlws.PY")); + book.extend(end); + let py = |arg: &[u8]| [&[0x23u8, 5, 0, 0, 0][..], arg, &[0x1E, 0, 0, 0x42, 3, 0xFF, 0]].concat(); + // Code longer than one string constant is written as constants joined with `&`. + let joined = [&[0x17u8, 1, 0, b'1', 0][..], &[0x17, 2, 0, b'+', 0, b'1', 0], &[0x08]].concat(); + // The same strings nested to the right, `"1"&("+"&"1")` by token order: still one flat chain. + let nested = [&[0x17u8, 1, 0, b'1', 0][..], &[0x17, 1, 0, b'+', 0], &[0x17, 1, 0, b'1', 0], &[0x08, 0x08]].concat(); + let data = [ + row(0), + formula_cell(0, &py(&[0x17, 1, 0, b'1', 0]), &[]), + formula_cell(1, &py(&[0x1E, 0, 0]), &[]), + formula_cell(2, &py(&joined), &[]), + formula_cell(3, &py(&nested), &[]), + ] + .concat(); + let wb = read(&package(&book, &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + let formula = |c| wb.sheets[0].formula(CellRef::new(0, c)); + assert_eq!(formula(0), Some("_xlfn._xlws.PY(\"1\",0)")); + assert_eq!(formula(1), None); + assert_eq!(formula(2), Some("_xlfn._xlws.PY(\"1\"&\"+1\",0)")); + assert_eq!(formula(3), Some("_xlfn._xlws.PY(\"1\"&\"+\"&\"1\",0)")); + assert!(warned(&wb, "Python code stored outside"), "{:?}", wb.warnings); +} + +#[test] +fn formula_text_past_the_allowance_keeps_the_saved_result() { + // `1` takes the last byte of a one-byte allowance; the next formula doesn't fit. + let data = [row(0), formula_cell(0, &[0x1E, 1, 0], &[]), formula_cell(1, &[0x1E, 1, 0], &[])].concat(); + let limits = Limits { binary_formula_text: 1, ..Limits::default() }; + let wb = read_with(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES), &limits).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), Some("1")); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 1)), None); + assert!(warned(&wb, "more formula text than the limits allow"), "{:?}", wb.warnings); +} + +fn range_formula(id: u16, (r0, c0, r1, c1): (u32, u32, u32, u32), rgce: &[u8]) -> Vec<u8> { + let mut data = vec![]; + for n in [r0, r1, c0, c1] { + data.extend(n.to_le_bytes()); + } + if id == 426 { + data.push(0x08); // The flags Excel writes for an ordinary array. + } + data.extend((rgce.len() as u32).to_le_bytes()); + data.extend(rgce); + data.extend(0u32.to_le_bytes()); + record(id, &data) +} + +/// A cell of the shared or array formula whose first cell is `row`, `col` (PtgExp + PtgExtraCol). +fn part(col: u32, (row, first_col): (u32, u32)) -> Vec<u8> { + formula_cell(col, &[&[0x01u8][..], &row.to_le_bytes()].concat(), &first_col.to_le_bytes()) +} + +fn ref_n(row: i32, col: u16) -> Vec<u8> { + [&[0x4Cu8][..], &row.to_le_bytes(), &col.to_le_bytes()].concat() +} + +fn at(a1: &str) -> CellRef { + CellRef::parse(a1).unwrap() +} + +#[test] +fn shared_array_and_dynamic_formulas_read_as_from_xlsx() { + // As Excel writes them: C1:C3 share `A1*10` (PtgRefN, column offset -2 as 16382); D1:E2 + // share `$A1+A$1`; F1:F2 hold the Ctrl+Shift+Enter array {=A1:A2*2}; G1 spills `=A1:A2`. + let area = [&[0x45u8][..], &0u32.to_le_bytes(), &1u32.to_le_bytes(), &REL.to_le_bytes(), &REL.to_le_bytes()].concat(); + let mut data = row(0); + data.extend(cell(5, 0, &1.0f64.to_le_bytes())); + data.extend(part(2, (0, 2))); + data.extend(range_formula(427, (0, 2, 2, 2), &[ref_n(0, 16382 | REL), vec![0x1E, 10, 0, 0x05]].concat())); + data.extend(part(3, (0, 3))); + data.extend(range_formula(427, (0, 3, 1, 4), &[ref_n(0, 0x8000), ref_n(0, 16381 | 0x4000), vec![0x03]].concat())); + data.extend(part(4, (0, 3))); + data.extend(part(5, (0, 5))); + data.extend(range_formula(426, (0, 5, 1, 5), &[area.clone(), vec![0x1E, 2, 0, 0x05]].concat())); + data.extend(record(49, &1u32.to_le_bytes())); + data.extend(record(50, &1u32.to_le_bytes())); // BrtValueMeta in between, as Excel writes for a spill error. + data.extend(part(6, (0, 6))); + data.extend(range_formula(426, (0, 6, 1, 6), &area)); + data.extend(row(1)); + data.extend(cell(5, 0, &2.0f64.to_le_bytes())); + for (col, first) in [(2, (0, 2)), (3, (0, 3)), (4, (0, 3)), (5, (0, 5)), (6, (0, 6))] { + data.extend(part(col, first)); + } + data.extend(row(2)); + data.extend(part(2, (0, 2))); + let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + let sheet = &wb.sheets[0]; + let formula = |a: &str| sheet.formulas.get(&at(a)); + // Each cell of a shared formula has its own text, decoded at the cell: the first with the + // group's range, all with its index. + for (a, want, si) in [ + ("C1", "A1*10", 0), + ("C2", "A2*10", 0), + ("C3", "A3*10", 0), + ("D1", "$A1+A$1", 1), + ("E1", "$A1+B$1", 1), + ("D2", "$A2+A$1", 1), + ("E2", "$A2+B$1", 1), + ] { + let f = formula(a).unwrap_or_else(|| panic!("{a}")); + assert_eq!((f.kind, f.text.as_str(), f.shared_index), (FormulaKind::Shared, want, Some(si)), "{a}"); + } + assert_eq!(formula("C1").and_then(|f| f.range), Range::parse("C1:C3")); + assert_eq!(formula("D1").and_then(|f| f.range), Range::parse("D1:E2")); + assert_eq!(formula("C2").and_then(|f| f.range), None); + // An array formula's first cell has it, with its range; a dynamic array's has its cell + // metadata too, as `cm` in .xlsx, though Excel wrote a BrtValueMeta in between. + let f1 = formula("F1").unwrap(); + assert_eq!((f1.kind, f1.text.as_str(), f1.range), (FormulaKind::Array, "A1:A2*2", Range::parse("F1:F2"))); + let g1 = formula("G1").unwrap(); + assert_eq!((g1.kind, g1.text.as_str(), g1.range), (FormulaKind::Array, "A1:A2", Range::parse("G1:G2"))); + assert_eq!(sheet.cell_metadata.get(&at("G1")), Some(&1)); + assert_eq!(sheet.cell_metadata.get(&at("F1")), None); + // Their other cells have no formula and keep their saved results, as in .xlsx. + for a in ["F2", "G2"] { + assert!(formula(a).is_none(), "{a}"); + assert_eq!(sheet.value(at(a)), Value::Number(0.0), "{a}"); + } + assert!(!wb.warnings.iter().any(|w| w.contains("kept as their saved results")), "{:?}", wb.warnings); +} + +#[test] +fn unreadable_shared_formulas_keep_their_values() { + // A shared formula with an unsupported token, a range that doesn't start at its first cell, + // a truncated record, and a first cell with no formula record after it: every cell of each + // keeps its saved result, and the file opens. + let unknown = range_formula(427, (0, 0, 1, 0), &[0xFF]); + let wrong_start = range_formula(427, (0, 1, 1, 1), &[0x1E, 1, 0]); + // A well-framed record whose payload stops before rgcb's length. + let short: Vec<u8> = [&[0u8; 4][..], &1u32.to_le_bytes(), &[0; 8], &3u32.to_le_bytes(), &[0x1E, 1, 0]].concat(); + let truncated = record(427, &short); + for after_first in [unknown, wrong_start, truncated, cell(5, 1, &1.0f64.to_le_bytes())] { + let data = [row(0), part(0, (0, 0)), after_first, row(1), part(0, (0, 0))].concat(); + let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + for r in [0, 1] { + assert_eq!(wb.sheets[0].formula(CellRef::new(r, 0)), None); + assert_eq!(wb.sheets[0].value(CellRef::new(r, 0)), Value::Number(0.0)); + } + assert!(wb.warnings.iter().any(|w| w.contains("kept as their saved results")), "{:?}", wb.warnings); + } +} + +#[test] +fn shared_formulas_wrap_and_may_start_inside_their_range() { + // `=` the cell to the left (column offset -1, written 16383), shared over A1:B2 from B1: A1 + // isn't part of it. In column A the offset wraps around the grid, as [MS-XLSB] defines it. + let left = ref_n(0, 16383 | REL); + let data = [ + row(0), + cell(5, 0, &1.0f64.to_le_bytes()), + part(1, (0, 1)), + range_formula(427, (0, 0, 1, 1), &left), + row(1), + part(0, (0, 1)), + part(1, (0, 1)), + ] + .concat(); + let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + let text = |a: &str| wb.sheets[0].formula(at(a)); + assert_eq!((text("A1"), text("B1"), text("A2"), text("B2")), (None, Some("A1"), Some("XFD2"), Some("A2"))); + assert!(!wb.warnings.iter().any(|w| w.contains("kept as their saved results")), "{:?}", wb.warnings); +} + +#[test] +fn a_shared_formula_copy_may_be_longer_than_its_first_cell() { + // SUM of nine SUMs of 255 references to the cell on the left: about 6,900 characters at B9, + // over 18,000 at B999999, where each `A9` is `A999999`. Each copy has its own text. + let mut rgce = vec![]; + for _ in 0..9 { + for _ in 0..255 { + rgce.extend(ref_n(0, 16383 | REL)); + } + rgce.extend([0x22, 255, 4, 0]); + } + rgce.extend([0x22, 9, 4, 0]); + let data = [row(8), part(1, (8, 1)), range_formula(427, (8, 1, 999_998, 1), &rgce), row(999_998), part(1, (8, 1))].concat(); + let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + let (b9, last) = (wb.sheets[0].formula(at("B9")).unwrap(), wb.sheets[0].formula(at("B999999")).unwrap()); + assert!(b9.len() < 8192 && last.len() > 18_000, "{} {}", b9.len(), last.len()); + assert!(last.starts_with("SUM(SUM(A999999,A999999"), "{}", &last[..40]); +} + +#[test] +fn shared_formula_copies_are_charged_before_they_are_made() { + // A1:A3 share `1+1` (3 bytes); with 6 bytes allowed, the first cell and one copy fit, and the + // last copy keeps its value without being decoded. + let one_plus_one = [0x1E, 1, 0, 0x1E, 1, 0, 0x03]; + let data = [row(0), part(0, (0, 0)), range_formula(427, (0, 0, 2, 0), &one_plus_one), row(1), part(0, (0, 0)), row(2), part(0, (0, 0))].concat(); + let limits = Limits { binary_formula_text: 6, ..Limits::default() }; + let wb = read_with(&file(&worksheet(&data, &[])), &limits).unwrap(); + let got: Vec<_> = (0..3).map(|r| wb.sheets[0].formula(CellRef::new(r, 0))).collect(); + assert_eq!(got, [Some("1+1"), Some("1+1"), None]); + assert!(warned(&wb, "more formula text than the limits allow"), "{:?}", wb.warnings); +} + +#[test] +fn a_shared_formula_stops_decoding_copies_once_one_is_kept_as_its_value() { + // A1:Z2 share `=` the cell to the right. A1 is `B1` (2 bytes), Z1's copy is `AA1` (3): it + // passes the estimate from the first cell but not the allowance, after being decoded. The + // group's later copies keep their values without being decoded, though B2's (`C2`) would fit. + let right = ref_n(0, 1 | REL); + let data = [row(0), part(0, (0, 0)), range_formula(427, (0, 0, 1, 25), &right), part(25, (0, 0)), row(1), part(1, (0, 0))].concat(); + let limits = Limits { binary_formula_text: 4, ..Limits::default() }; + let wb = read_with(&file(&worksheet(&data, &[])), &limits).unwrap(); + let text = |a: &str| wb.sheets[0].formula(at(a)); + assert_eq!((text("A1"), text("Z1"), text("B2")), (Some("B1"), None, None)); + assert!(warned(&wb, "more formula text than the limits allow"), "{:?}", wb.warnings); +} + +#[test] +fn convert_is_called_by_its_number_as_excel_writes_it() { + // Excel's tokens for `=CONVERT(1,"m","ft")` in .xlsb: PtgFunc 0x1D4, which the + // specification's Ftab table leaves out. + let rgce = [0x1E, 0x01, 0x00, 0x17, 0x01, 0x00, 0x6D, 0x00, 0x17, 0x02, 0x00, 0x66, 0x00, 0x74, 0x00, 0x41, 0xD4, 0x01]; + let wb = read(&file(&worksheet(&[row(0), formula_cell(0, &rgce, &[])].concat(), &[]))).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), Some("CONVERT(1,\"m\",\"ft\")")); +} + +#[test] +fn a_dynamic_array_kept_as_its_value_has_no_cell_metadata() { + let meta = record(49, &1u32.to_le_bytes()); + let table_ref = [0x18, 0x19, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]; + let data = [ + row(0), + // A1: a dynamic-array formula the reader can't decode (a table reference). + meta.clone(), + formula_cell(0, &table_ref, &[]), + // B1:B2: a dynamic array whose BrtArrFmla holds an unknown token. + meta.clone(), + part(1, (0, 1)), + range_formula(426, (0, 1, 1, 1), &[0xFF]), + // C1: a value with cell metadata keeps it, as the file has it. + meta.clone(), + cell(5, 2, &1.0f64.to_le_bytes()), + // D1: the first cell of a dynamic array with no BrtArrFmla after it, then a value, E1. + meta.clone(), + part(3, (0, 3)), + cell(5, 4, &1.0f64.to_le_bytes()), + // F1: the same as the last cell of its row. + meta, + part(5, (0, 5)), + row(1), + cell(5, 0, &1.0f64.to_le_bytes()), + ] + .concat(); + let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + let sheet = &wb.sheets[0]; + for a in ["A1", "B1", "D1", "F1"] { + assert_eq!(sheet.formula(at(a)), None, "{a}"); + } + assert_eq!(sheet.cell_metadata.iter().collect::<Vec<_>>(), [(&at("C1"), &1)]); + assert!(warned(&wb, "missing from the file"), "{:?}", wb.warnings); +} + +/// `PtgAttrSpace` ([MS-XLSB] 2.5.98.31): its type (0 spaces before the next token, 1 line breaks +/// before it, 2 spaces before a `(`, 4 spaces before a `)`) and count. +fn space(kind: u8, n: u8) -> Vec<u8> { + vec![0x19, 0x40, kind, n] +} + +#[test] +fn typed_spacing_numbers_and_iso_functions_read_as_in_xlsx() { + let a1 = || [&[0x24u8][..], &loc(0, REL)].concat(); + let b1 = || [&[0x24u8][..], &loc(0, 1 | REL)].concat(); + let num = |n: f64| [&[0x1Fu8][..], &n.to_le_bytes()].concat(); + let area = |c: u16| [&[0x25u8][..], &0u32.to_le_bytes(), &1u32.to_le_bytes(), &(c | REL).to_le_bytes(), &(c | REL).to_le_bytes()].concat(); + let goto = [0x19u8, 0x08, 0, 0]; + let cells: Vec<Vec<u8>> = vec![ + // Spacing goes before the next token: an operand, or an operator's symbol. + [&[0x1Eu8, 1, 0][..], &space(0, 2), &[0x1E, 2, 0], &space(0, 1), &[0x03]].concat(), + // ... or a call's `)`, and inside a call's parentheses. + [space(0, 1), a1(), space(0, 1), b1(), space(4, 1), vec![0x42, 2, 4, 0]].concat(), + // Line breaks. + [ + a1(), + vec![0x1E, 0, 0, 0x0D, 0x19, 0x02, 0, 0], + space(1, 1), + space(0, 2), + vec![0x1E, 1, 0], + goto.to_vec(), + space(1, 1), + space(0, 2), + vec![0x1E, 2, 0], + goto.to_vec(), + vec![0x42, 3, 1, 0], + ] + .concat(), + // Inside and before parentheses. + [space(0, 1), vec![0x1E, 1, 0], space(0, 1), vec![0x1E, 2, 0], space(0, 1), vec![0x03], space(4, 1), vec![0x15]].concat(), + [vec![0x1E, 1, 0, 0x1E, 2, 0], space(2, 1), vec![0x15, 0x03]].concat(), + // A call with no arguments, and one through PtgAttrSum. + [space(4, 1), vec![0x41, 19, 0]].concat(), + [area(0), area(1), space(0, 1), vec![0x0F, 0x19, 0x10, 0, 0]].concat(), + // A sign, `%`, and leading spacing (trimmed, as `.xlsx` text is read). + [space(0, 1), vec![0x1E, 1, 0, 0x13], space(0, 1), vec![0x14]].concat(), + [space(0, 3), a1()].concat(), + // A newer function: spacing before its name's token is the first argument's. + [vec![0x1E, 1, 0], space(0, 1), vec![0x23, 5, 0, 0, 0], num(1.5), space(0, 1), vec![0x42, 2, 0xFF, 0, 0x03]].concat(), + vec![0x23, 1, 0, 0, 0, 0x17, 1, 0, b'a', 0, 0x42, 2, 0xFF, 0], + // Numbers written out up to 21 characters, scientific past them. + [num(1e20), num(1e21), vec![0x03], num(1e-19), vec![0x03], num(1.5e-19), vec![0x03], num(1234567890123456.0), vec![0x03]].concat(), + ]; + let mut data = row(0); + for (i, rgce) in cells.iter().enumerate() { + data.extend(formula_cell(i as u32 + 1, rgce, &[])); + } + // Name 5: the hidden name ISO.CEILING is called through, as Excel writes it. + let mut book = book_with_links(&xti()); + let end = record(132, &[]); + book.truncate(book.len() - end.len()); + book.extend(name(0x0002_000b, "_xlfn.ISO.CEILING")); + book.extend(end); + let wb = read(&package(&book, &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + let got: Vec<_> = (1..=cells.len() as u32).map(|c| wb.sheets[0].formula(CellRef::new(0, c))).collect(); + let want = [ + "1 + 2", + "SUM( A1, B1 )", + "IF(A1>0,\n 1,\n 2)", + "( 1 + 2 )", + "1+ (2)", + "PI( )", + "SUM(A1:A2 B1:B2)", + "- 1 %", + "A1", + "1+ ISO.CEILING( 1.5)", + "_xlfn.CONCAT(\"a\")", + "100000000000000000000+1E+21+0.0000000000000000001+1.5E-19+1234567890123460", + ]; + assert_eq!(got, want.map(Some)); +} + +#[test] +fn references_to_macro_sheets_and_spans_over_chart_sheets_are_named() { + // Sheets Data, a chart sheet, an XLM macro sheet, Hidden; sheet links Macro1, Data:Hidden + // (over the chart sheet) and Chart1 (no cells). + let mut book = record(131, &[]); + book.extend(record(153, &[[0u8; 8].as_slice(), &wide("")].concat())); + book.extend(record(143, &[])); + for (id, rel, name) in [(1u32, "one", "Data"), (3, "c", "Chart1"), (4, "m", "Macro1"), (2, "two", "Hidden")] { + book.extend(record(156, &[&0u32.to_le_bytes()[..], &id.to_le_bytes(), &wide(rel), &wide(name)].concat())); + } + book.extend(record(144, &[])); + let mut xti = 3u32.to_le_bytes().to_vec(); + for (first, last) in [(2i32, 2i32), (0, 3), (1, 1)] { + xti.extend([0u32.to_le_bytes(), first.to_le_bytes(), last.to_le_bytes()].concat()); + } + book.extend([record(353, &[]), record(357, &[]), record(362, &xti), record(354, &[]), record(132, &[])].concat()); + let rels = RELS.replace( + "</Relationships>", + r#"<Relationship Id="c" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="../data/c.bin"/><Relationship Id="m" Type="http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet" Target="../data/m.bin"/></Relationships>"#, + ); + let ref3d = |ixti: u16| [&[0x5Au8][..], &ixti.to_le_bytes(), &loc(0, 0)].concat(); + let data = [row(0), formula_cell(1, &ref3d(0), &[]), formula_cell(2, &ref3d(1), &[]), formula_cell(3, &ref3d(2), &[])].concat(); + let wb = read(&package(&book, &worksheet(&data, &[]), &sst(), ROOT, &rels, TYPES)).unwrap(); + let got: Vec<_> = (1..=3).map(|c| wb.sheets[0].formula(CellRef::new(0, c))).collect(); + assert_eq!(got, [Some("Macro1!$A$1"), Some("Data:Hidden!$A$1"), None]); + assert!(warned(&wb, "references to sheets with no cells"), "{:?}", wb.warnings); +} + +#[test] +fn a_formulas_array_constants_share_one_allowance() { + // Two arrays of 40,000 Boolean values, each within what one array may hold, added together: + // charged before their values are held, together they pass what a formula's arrays may hold + // (65,536 values), so the cell keeps its saved result. One of them alone decodes. + let array = |n: u32| [&n.to_le_bytes()[..], &1u32.to_le_bytes(), &[2u8, 1].repeat(n as usize)].concat(); + let ptg = [&[0x60u8][..], &[0; 14]].concat(); + let two = [&ptg[..], &ptg, &[0x03]].concat(); + let data = [row(0), formula_cell(0, &two, &[array(40_000), array(40_000)].concat()), formula_cell(1, &ptg, &array(40_000))].concat(); + let wb = read(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None); + assert_eq!(wb.sheets[0].value(CellRef::new(0, 0)), Value::Number(0.0)); + assert!(wb.sheets[0].formula(CellRef::new(0, 1)).is_some_and(|f| f.starts_with("{TRUE;TRUE"))); + assert!(warned(&wb, "array constants too large"), "{:?}", wb.warnings); +} + +#[test] +fn a_spent_formula_allowance_skips_decoding() { + // With no allowance, a formula is not decoded at all: an unknown token is never reached. + let data = [row(0), formula_cell(0, &[0xFF], &[])].concat(); + let limits = Limits { binary_formula_text: 0, ..Limits::default() }; + let wb = read_with(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES), &limits).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None); + assert!(warned(&wb, "more formula text than the limits allow"), "{:?}", wb.warnings); + assert!(!warned(&wb, "unknown formula token"), "{:?}", wb.warnings); +} + +#[test] +fn module_sheets_and_supporting_links_are_bounded() { + // 1,025 very hidden module sheets (no relationship) before the worksheets: each keeps a place + // in the sheet links, so together they are past the 1,024-sheet cap. + let plain = book(false); + let at = plain.windows(3).position(|w| w == record(143, &[]).as_slice()).unwrap() + 3; + let module = record(156, &[&2u32.to_le_bytes()[..], &9u32.to_le_bytes(), &u32::MAX.to_le_bytes(), &wide("Module")].concat()); + let modules = [&plain[..at], &module.repeat(1025), &plain[at..]].concat(); + assert!(matches!(read(&package(&modules, &worksheet(&[], &[]), &sst(), ROOT, RELS, TYPES)), Err(Error::TooLarge(_)))); + // 65,537 supporting links: past the cap the links aren't read, and formulas keep their values. + let end = record(132, &[]); + let selves = [&plain[..plain.len() - end.len()], &record(353, &[]), &record(357, &[]).repeat(65_537), &record(354, &[]), &end].concat(); + let data = [row(0), formula_cell(0, &[0x1E, 1, 0], &[])].concat(); + let wb = read(&package(&selves, &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None); + assert!(wb.warnings.iter().any(|w| w.contains("sheet links or names could not be read")), "{:?}", wb.warnings); +} diff --git a/crates/xlsx/tests/xlsx.rs b/crates/xlsx/tests/xlsx.rs index c8355fd8c..ef932026e 100644 --- a/crates/xlsx/tests/xlsx.rs +++ b/crates/xlsx/tests/xlsx.rs @@ -168,6 +168,41 @@ fn a_missing_shared_strings_part_is_a_warning() { assert!(wb.warnings.iter().any(|w| w.contains("missing part xl/sharedStrings.xml")), "{:?}", wb.warnings); } +#[test] +fn shared_strings_at_the_conventional_path_work_without_a_relationship() { + const REL_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships"; + const DOC_REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + const MAIN: &str = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; + let root_rels = + format!(r#"<Relationships xmlns="{REL_NS}"><Relationship Id="w" Type="{DOC_REL}/officeDocument" Target="xl/workbook.xml"/></Relationships>"#); + let workbook = format!(r#"<workbook xmlns="{MAIN}" xmlns:r="{DOC_REL}"><sheets><sheet name="S" sheetId="1" r:id="s"/></sheets></workbook>"#); + let workbook_rels = format!( + r#"<Relationships xmlns="{REL_NS}"><Relationship Id="s" Type="{DOC_REL}/worksheet" Target="worksheets/sheet1.xml"/></Relationships>"# + ); + let worksheet = format!(r#"<worksheet xmlns="{MAIN}"><sheetData><row r="1"><c r="A1" t="s"><v>0</v></c></row></sheetData></worksheet>"#); + let strings = format!(r#"<sst xmlns="{MAIN}"><si><t>Tea</t></si></sst>"#); + let bytes = zip(&[ + ("_rels/.rels", root_rels.as_bytes()), + ("xl/workbook.xml", workbook.as_bytes()), + ("xl/_rels/workbook.xml.rels", workbook_rels.as_bytes()), + ("xl/worksheets/sheet1.xml", worksheet.as_bytes()), + ("xl/sharedStrings.xml", strings.as_bytes()), + ]); + + let mut package = Package::open(&bytes, &Limits::default()).unwrap(); + let strings = package.shared_strings().unwrap(); + assert_eq!(strings.iter().map(|item| item.text.as_ref()).collect::<Vec<_>>(), ["Tea"]); + let workbook = package.workbook().unwrap(); + let mut values = Vec::new(); + package + .sheet(&workbook.sheets[0], |row| { + values.extend(row.cells.into_iter().map(|cell| cell.value.resolve(&strings, false))); + Ok(()) + }) + .unwrap(); + assert_eq!(values, [Value::text("Tea")]); +} + #[test] fn limits_are_errors() { let rows: String = (1..=2000).map(|r| format!(r#"<row r="{r}"><c r="A{r}"><v>{r}</v></c></row>"#)).collect(); diff --git a/crates/xml/Cargo.toml b/crates/xml/Cargo.toml index f957fa625..02d68985b 100644 --- a/crates/xml/Cargo.toml +++ b/crates/xml/Cargo.toml @@ -13,3 +13,4 @@ workspace = true [dependencies] quick-xml = { version = "0.41", default-features = false } thiserror = { workspace = true } +serde = { workspace = true, features = ["derive"] } diff --git a/crates/xml/src/dtd.rs b/crates/xml/src/dtd.rs new file mode 100644 index 000000000..9fa1dd497 --- /dev/null +++ b/crates/xml/src/dtd.rs @@ -0,0 +1,1063 @@ +//! DTD content-model parsing and XML validation. + +//! Document Type Definitions: element declarations (content models) and required attributes, and +//! validation of an XML document against them (Structure ▸ Validate). + +use std::collections::{HashMap, HashSet}; + +/// How much text parameter entities may add during expansion (a pass count is not an output +/// bound: each pass replaces whole strings, so references can inflate multiplicatively). +const MAX_EXPANDED_BYTES: usize = 1024 * 1024; +const MAX_DTD_BYTES: usize = 1024 * 1024; +const MAX_VALIDATION_XML_BYTES: usize = 16 * 1024 * 1024; +const MAX_VALIDATION_NODES: usize = 100_000; +const MAX_VALIDATION_DEPTH: usize = 256; +const MAX_VALIDATION_ATTRIBUTES: usize = 1_000_000; +const MAX_MATCH_WORK: usize = 20_000_000; +const MAX_MATCH_POSITIONS: usize = 5_000_000; +const MAX_MATCH_STATES: usize = 100_000; + +/// A content particle: a name, a sequence, a choice, or one of those repeated (`?`, `*`, `+`). +#[derive(Clone, Debug, PartialEq)] +enum Cp { + Name(String), + Seq(Vec<Cp>), + Choice(Vec<Cp>), + Rep(Box<Cp>, char), +} + +#[derive(Clone, Debug, PartialEq)] +enum Model { + Empty, + Any, + /// `(#PCDATA | a | b)*`: text and these elements in any order. + Mixed(Vec<String>), + Children(Cp), +} + +/// A parsed DTD. +#[derive(Clone, Debug, Default)] +pub struct Dtd { + elements: Vec<(String, Model)>, + /// Element → its `#REQUIRED` attributes. + required: HashMap<String, Vec<String>>, +} + +/// A problem found by validation: where (an element path such as `Root/story[2]`) and what. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct Problem { + pub path: String, + pub message: String, +} + +impl Dtd { + /// Declared element names, in order. + pub fn element_names(&self) -> impl Iterator<Item = &str> { + self.elements.iter().map(|(n, _)| n.as_str()) + } + + fn model(&self, name: &str) -> Option<&Model> { + self.elements.iter().find(|(n, _)| n == name).map(|(_, m)| m) + } +} + +/// Markup declarations (`<!…>`) with comments removed and quoted strings kept whole. +fn declarations(src: &str) -> Result<Vec<String>, String> { + let mut out = Vec::new(); + let mut rest = src; + while let Some(i) = rest.find("<!") { + rest = &rest[i..]; + if rest.starts_with("<!--") { + let Some(j) = rest.find("-->") else { + return Err("unterminated DTD comment".into()); + }; + rest = &rest[j + 3..]; + continue; + } + let mut quote = None; + let mut end = None; + for (k, c) in rest.char_indices().skip(2) { + match (quote, c) { + (Some(q), c) if c == q => quote = None, + (None, '"' | '\'') => quote = Some(c), + (None, '>') => { + end = Some(k); + break; + } + _ => {} + } + } + let Some(end) = end else { + return Err("unterminated DTD declaration".into()); + }; + out.push(rest[2..end].to_string()); + rest = &rest[end + 1..]; + } + Ok(out) +} + +fn tokens(s: &str) -> Vec<String> { + let mut out = Vec::new(); + let mut cur = String::new(); + for c in s.chars() { + if c.is_whitespace() || "(),|?*+".contains(c) { + if !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + if !c.is_whitespace() { + out.push(c.to_string()); + } + } else { + cur.push(c); + } + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +/// How deeply groups may nest in a content model; parsing, matching (`ends`) and printing (`show`) +/// recurse once per level. +const MAX_CONTENT_MODEL_DEPTH: usize = 64; + +/// Parse a content particle from `t[*i..]`, inside `depth` enclosing groups. +fn particle(t: &[String], i: &mut usize, depth: usize) -> Result<Cp, String> { + let base = match t.get(*i).map(String::as_str) { + Some("(") => { + if depth >= MAX_CONTENT_MODEL_DEPTH { + return Err(format!("content model nested more than {MAX_CONTENT_MODEL_DEPTH} levels")); + } + *i += 1; + let mut items = vec![particle(t, i, depth + 1)?]; + let mut sep = None; + loop { + match t.get(*i).map(String::as_str) { + Some(")") => { + *i += 1; + break; + } + Some(s @ ("," | "|")) => { + if sep.is_some_and(|p| p != s) { + return Err("mixed `,` and `|` in one group".into()); + } + sep = Some(if s == "," { "," } else { "|" }); + *i += 1; + items.push(particle(t, i, depth + 1)?); + } + other => return Err(format!("unexpected `{}` in a content model", other.unwrap_or("end"))), + } + } + if sep == Some("|") { Cp::Choice(items) } else { Cp::Seq(items) } + } + Some(n) if !"),|?*+".contains(n) => { + *i += 1; + Cp::Name(n.to_string()) + } + other => return Err(format!("unexpected `{}` in a content model", other.unwrap_or("end"))), + }; + Ok(match t.get(*i).map(String::as_str) { + Some(r @ ("?" | "*" | "+")) => { + *i += 1; + Cp::Rep(Box::new(base), r.chars().next().unwrap_or('*')) + } + _ => base, + }) +} + +fn parse_model(s: &str) -> Result<Model, String> { + let s = s.trim(); + match s { + "EMPTY" => return Ok(Model::Empty), + "ANY" => return Ok(Model::Any), + _ => {} + } + if s.contains("#PCDATA") { + let t = tokens(s); + if t.first().map(String::as_str) != Some("(") || t.get(1).map(String::as_str) != Some("#PCDATA") { + return Err("malformed mixed content model".into()); + } + let mut i = 2; + let mut allowed = Vec::new(); + if t.get(i).map(String::as_str) == Some(")") { + i += 1; + if t.get(i).map(String::as_str) == Some("*") { + i += 1; + } + if i != t.len() { + return Err("unexpected token after mixed content model".into()); + } + return Ok(Model::Mixed(allowed)); + } + loop { + if t.get(i).map(String::as_str) != Some("|") { + return Err("expected `|` in mixed content model".into()); + } + i += 1; + let Some(name) = t.get(i).filter(|name| !"(),|?*+".contains(name.as_str())) else { + return Err("expected element name in mixed content model".into()); + }; + if allowed.contains(name) { + return Err(format!("duplicate `{name}` in mixed content model")); + } + allowed.push(name.clone()); + i += 1; + match t.get(i).map(String::as_str) { + Some("|") => continue, + Some(")") => { + i += 1; + break; + } + _ => return Err("expected `|` or `)` in mixed content model".into()), + } + } + if t.get(i).map(String::as_str) != Some("*") || i + 1 != t.len() { + return Err("mixed content with element names must end in `*`".into()); + } + return Ok(Model::Mixed(allowed)); + } + let t = tokens(s); + let mut i = 0; + let cp = particle(&t, &mut i, 0)?; + if i != t.len() { + return Err(format!("unexpected `{}` after the content model", t[i])); + } + Ok(Model::Children(cp)) +} + +/// How deeply parameter entities may nest: a reference in the DTD is level 1, a reference in its +/// value level 2, and so on. +const MAX_PARAMETER_ENTITY_DEPTH: usize = 64; + +/// Expand `%name;` references, one level per round, until a round changes nothing. +fn expand_parameter_entities(src: &str, ents: &[(String, String)]) -> Result<String, String> { + let mut entities = HashMap::new(); + for (name, value) in ents { + entities.entry(name.as_str()).or_insert(value.as_str()); + } + let limit = src.len().saturating_add(MAX_EXPANDED_BYTES); + let append = |out: &mut String, value: &str| -> Result<(), String> { + if value.len() > limit.saturating_sub(out.len()) { + return Err(format!("parameter entities expand the DTD beyond {limit} bytes")); + } + out.push_str(value); + Ok(()) + }; + let too_deep = || format!("parameter entities refer to themselves or nest deeper than {MAX_PARAMETER_ENTITY_DEPTH} levels"); + let mut text = src.to_string(); + // The round after the deepest level changes nothing, hence one more round than levels. + for _ in 0..=MAX_PARAMETER_ENTITY_DEPTH { + let mut out = String::with_capacity(text.len()); + let mut rest = text.as_str(); + let mut changed = false; + loop { + let mut special = None; + for (i, c) in rest.char_indices() { + if c == '%' { + special = Some((i, false)); + break; + } + if c == '<' && rest[i..].starts_with("<!--") { + special = Some((i, true)); + break; + } + } + let Some((i, is_comment)) = special else { + append(&mut out, rest)?; + rest = ""; + break; + }; + if is_comment { + append(&mut out, &rest[..i])?; + let comment_tail = &rest[i..]; + let Some(end) = comment_tail.find("-->") else { + return Err("unterminated DTD comment".into()); + }; + append(&mut out, &comment_tail[..end + 3])?; + rest = &comment_tail[end + 3..]; + continue; + } + let (prefix, reference) = rest.split_at(i); + append(&mut out, prefix)?; + // `find` points to an ASCII `%`, so both split positions are UTF-8 boundaries. + rest = reference.split_at(1).1; + // A name has no whitespace and no `%` (`parse` ends a name at whitespace), whatever its + // length: the search for the closing `;` stops at the first of those, so the searches of + // a round never overlap and a round stays linear in the text. + let end = + rest.bytes().position(|b| matches!(b, b';' | b'%') || b.is_ascii_whitespace()).filter(|&k| rest.as_bytes().get(k) == Some(&b';')); + if let Some(end) = end + && let Some(value) = rest.get(..end).and_then(|name| entities.get(name)) + { + // A value that is its own reference (`<!ENTITY % a "%a;">`) never gets anywhere. + if reference.get(..end + 2) == Some(*value) { + return Err(too_deep()); + } + append(&mut out, value)?; + changed = true; + rest = rest.split_at(end + 1).1; + continue; + } + append(&mut out, "%")?; + } + append(&mut out, rest)?; + text = out; + if !changed { + return Ok(text); + } + } + Err(too_deep()) +} + +/// Parse a DTD (its element and attribute-list declarations; parameter entities are expanded). +pub fn parse(src: &str) -> Result<Dtd, String> { + if src.len() > MAX_DTD_BYTES { + return Err(format!("DTD exceeds the {MAX_DTD_BYTES} byte parsing limit")); + } + // Parameter entities first, then expand references and read the declarations again. + let mut ents: Vec<(String, String)> = Vec::new(); + for d in declarations(src)? { + if let Some(rest) = d.strip_prefix("ENTITY") { + let rest = rest.trim_start(); + if let Some(rest) = rest.strip_prefix('%') { + let rest = rest.trim_start(); + let name: String = rest.chars().take_while(|c| !c.is_whitespace()).collect(); + let val = rest[name.len()..].trim(); + let q = val.chars().next().unwrap_or('"'); + if let Some(v) = val.strip_prefix(q).and_then(|v| v.find(q).map(|e| &v[..e])) { + ents.push((name, v.to_string())); + } + } + } + } + let text = expand_parameter_entities(src, &ents)?; + let mut dtd = Dtd::default(); + for d in declarations(&text)? { + if let Some(rest) = d.strip_prefix("ELEMENT") { + let rest = rest.trim_start(); + let name: String = rest.chars().take_while(|c| !c.is_whitespace()).collect(); + let model = parse_model(&rest[name.len()..]).map_err(|e| format!("<!ELEMENT {name}>: {e}"))?; + dtd.elements.push((name, model)); + } else if let Some(rest) = d.strip_prefix("ATTLIST") { + // name (attr type default)*; only `#REQUIRED` matters here. + let mut words = Vec::new(); + let mut cur = String::new(); + let mut quote = None; + let mut group = 0; + for c in rest.chars() { + match (quote, c) { + (Some(q), c) if c == q => { + quote = None; + cur.push(c); + } + (Some(_), c) => cur.push(c), + (None, '"' | '\'') => { + quote = Some(c); + cur.push(c); + } + (None, '(') => { + group += 1; + cur.push(c); + } + (None, ')') => { + group -= 1; + cur.push(c); + } + (None, c) if c.is_whitespace() && group == 0 => { + if !cur.is_empty() { + words.push(std::mem::take(&mut cur)); + } + } + (None, c) => cur.push(c), + } + } + if !cur.is_empty() { + words.push(cur); + } + let Some((el, attrs)) = words.split_first() else { continue }; + let mut k = 0; + while k < attrs.len() { + let name = &attrs[k]; + let Some(ty) = attrs.get(k + 1) else { + return Err(format!("incomplete ATTLIST for `{el}`")); + }; + k += 2; + // NOTATION is a two-token type: the keyword followed by its enumeration. + if ty == "NOTATION" { + if attrs.get(k).is_none_or(|group| !group.starts_with('(') || !group.ends_with(')')) { + return Err(format!("malformed NOTATION type for `{name}`")); + } + k += 1; + } + let Some(default) = attrs.get(k).map(String::as_str) else { + return Err(format!("missing default declaration for `{name}`")); + }; + k += 1; + if default == "#REQUIRED" { + dtd.required.entry(el.clone()).or_default().push(name.clone()); + } else if default == "#FIXED" { + if k >= attrs.len() { + return Err(format!("missing #FIXED value for `{name}`")); + } + k += 1; + } + } + } + } + if dtd.elements.is_empty() { + return Err("no element declarations".into()); + } + Ok(dtd) +} + +/// What `ends` has worked out for one sequence of children: the end positions of a group (by the +/// address of its node, which lives as long as the model) from a position. +type EndsMemo = HashMap<(usize, usize), Vec<usize>>; + +#[derive(Default)] +struct MatchBudget { + work: usize, + positions: usize, + states: usize, + exhausted: bool, + reported: bool, +} + +impl MatchBudget { + fn spend(&mut self, work: usize, positions: usize) -> Result<(), &'static str> { + if self.exhausted { + return Err("content model matching exceeded its resource budget"); + } + self.work = self.work.saturating_add(work); + self.positions = self.positions.saturating_add(positions); + if self.work > MAX_MATCH_WORK { + self.exhausted = true; + return Err("content model matching exceeded its work limit"); + } + if self.positions > MAX_MATCH_POSITIONS { + self.exhausted = true; + return Err("content model matching exceeded its memory limit"); + } + Ok(()) + } + + fn retain_state(&mut self) -> Result<(), &'static str> { + self.states = self.states.saturating_add(1); + if self.states > MAX_MATCH_STATES { + self.exhausted = true; + return Err("content model matching exceeded its state limit"); + } + Ok(()) + } +} + +/// End positions after `cp` matches a prefix of `seq[i..]`. +/// +/// The positions of each group are worked out once per start position (`memo`): nested repetitions +/// such as `((a*)*)*` ask the inner group for the same positions again and again, which is +/// exponential in their depth without it. +fn ends(cp: &Cp, seq: &[&str], i: usize, memo: &mut EndsMemo, budget: &mut MatchBudget) -> Result<Vec<usize>, &'static str> { + budget.spend(1, 0)?; + if let Cp::Name(n) = cp { + if seq.get(i) == Some(&n.as_str()) { + budget.spend(0, 1)?; + return Ok(vec![i + 1]); + } + return Ok(vec![]); + } + let key = (std::ptr::from_ref(cp) as usize, i); + if let Some(done) = memo.get(&key) { + budget.spend(0, done.len())?; + return Ok(done.clone()); + } + let mut out: Vec<usize> = match cp { + Cp::Name(_) => vec![], + // Keep the positions after each item a set: as a list of every path, `(a?, a?, …)` doubles per item. + Cp::Seq(items) => { + let mut at = vec![i]; + for c in items { + let mut next = Vec::new(); + for p in at { + let found = ends(c, seq, p, memo, budget)?; + budget.spend(found.len(), found.len())?; + next.extend(found); + } + next.sort_unstable(); + next.dedup(); + at = next; + } + at + } + Cp::Choice(items) => { + let mut all = Vec::new(); + for c in items { + let found = ends(c, seq, i, memo, budget)?; + budget.spend(found.len(), found.len())?; + all.extend(found); + } + all + } + Cp::Rep(c, r) => { + let mut all = if *r == '+' { vec![] } else { vec![i] }; + let mut seen: HashSet<usize> = all.iter().copied().collect(); + let mut frontier = ends(c, seq, i, memo, budget)?; + budget.spend(frontier.len(), frontier.len())?; + if *r == '?' { + all.extend(frontier); + } else { + while !frontier.is_empty() { + let mut new = Vec::new(); + for p in frontier.iter().copied() { + budget.spend(1, 0)?; + if seen.insert(p) { + budget.spend(0, 1)?; + new.push(p); + } + } + budget.spend(new.len(), new.len())?; + all.extend(&new); + let mut next = Vec::new(); + let mut next_seen = HashSet::new(); + for p in new.into_iter().filter(|&p| p > i) { + for found in ends(c, seq, p, memo, budget)? { + budget.spend(1, 0)?; + if !seen.contains(&found) && next_seen.insert(found) { + budget.spend(0, 1)?; + next.push(found); + } + } + } + // Two paths to one position are one position: kept apart they multiply per round. + next.sort_unstable(); + next.dedup(); + frontier = next; + } + } + all + } + }; + out.sort_unstable(); + out.dedup(); + budget.spend(out.len(), out.len())?; + budget.retain_state()?; + memo.insert(key, out.clone()); + Ok(out) +} + +fn show(cp: &Cp) -> String { + match cp { + Cp::Name(n) => n.clone(), + Cp::Seq(v) => format!("({})", v.iter().map(show).collect::<Vec<_>>().join(", ")), + Cp::Choice(v) => format!("({})", v.iter().map(show).collect::<Vec<_>>().join(" | ")), + Cp::Rep(c, r) => format!("{}{r}", show(c)), + } +} + +/// An element of the document being validated. +struct Node { + name: String, + attrs: Vec<String>, + children: Vec<Node>, + text: bool, + content: bool, +} + +fn bounded_node(e: &quick_xml::events::BytesStart<'_>, depth: usize, nodes: &mut usize, attributes: &mut usize) -> Result<Node, String> { + if depth >= MAX_VALIDATION_DEPTH { + return Err(format!("XML nesting exceeds the {MAX_VALIDATION_DEPTH} level validation limit")); + } + *nodes = nodes.saturating_add(1); + if *nodes > MAX_VALIDATION_NODES { + return Err(format!("XML exceeds the {MAX_VALIDATION_NODES} node validation limit")); + } + let mut attrs = Vec::new(); + for attr in e.attributes().with_checks(true) { + let attr = attr.map_err(|err| format!("invalid attribute: {err}"))?; + attrs.push(String::from_utf8_lossy(attr.key.as_ref()).to_string()); + } + *attributes = attributes.saturating_add(attrs.len()); + if *attributes > MAX_VALIDATION_ATTRIBUTES { + return Err(format!("XML exceeds the {MAX_VALIDATION_ATTRIBUTES} attribute validation limit")); + } + Ok(Node { name: String::from_utf8_lossy(e.name().as_ref()).to_string(), attrs, children: vec![], text: false, content: false }) +} + +fn read_tree(xml: &str) -> Result<Node, String> { + use quick_xml::events::Event; + if xml.len() > MAX_VALIDATION_XML_BYTES { + return Err(format!("XML exceeds the {} byte validation limit", MAX_VALIDATION_XML_BYTES)); + } + let mut r = quick_xml::Reader::from_str(xml); + let mut stack: Vec<Node> = Vec::new(); + let mut root = None; + let mut nodes = 0usize; + let mut attributes = 0usize; + loop { + match r.read_event().map_err(|e| e.to_string())? { + Event::Start(e) => { + if stack.is_empty() && root.is_some() { + return Err("multiple root elements".into()); + } + let n = bounded_node(&e, stack.len(), &mut nodes, &mut attributes)?; + if let Some(parent) = stack.last_mut() { + parent.content = true; + } + stack.push(n); + } + Event::Empty(e) => { + if stack.is_empty() && root.is_some() { + return Err("multiple root elements".into()); + } + let n = bounded_node(&e, stack.len(), &mut nodes, &mut attributes)?; + match stack.last_mut() { + Some(p) => { + p.content = true; + p.children.push(n); + } + None => root = Some(n), + } + } + Event::End(e) => { + let n = stack.pop().ok_or("unbalanced end tag")?; + if n.name.as_bytes() != e.name().as_ref() { + return Err("mismatched end tag".into()); + } + match stack.last_mut() { + Some(p) => p.children.push(n), + None => root = Some(n), + } + } + Event::Text(t) => { + if let Some(p) = stack.last_mut() { + p.content = true; + if !t.iter().all(u8::is_ascii_whitespace) { + p.text = true; + } + } else if !t.iter().all(u8::is_ascii_whitespace) { + return Err("text outside the root element".into()); + } + } + Event::CData(_) => { + if let Some(p) = stack.last_mut() { + p.text = true; + p.content = true; + } + } + Event::GeneralRef(reference) => { + let name = reference.decode().map_err(|e| e.to_string())?; + let accepted = if let Some(character) = reference.resolve_char_ref().map_err(|e| e.to_string())? { + crate::is_xml_char(character) + } else { + matches!(name.as_ref(), "amp" | "lt" | "gt" | "apos" | "quot") + }; + if !accepted { + return Err(format!("unsupported general entity reference `&{name};`")); + } + if let Some(p) = stack.last_mut() { + p.text = true; + p.content = true; + } else { + return Err("reference outside the root element".into()); + } + } + Event::Comment(_) | Event::PI(_) => { + if let Some(parent) = stack.last_mut() { + parent.content = true; + } + } + Event::Eof => { + if !stack.is_empty() { + return Err("unclosed element".into()); + } + return root.ok_or_else(|| "no root element".into()); + } + _ => {} + } + } +} + +fn check(dtd: &Dtd, n: &Node, path: &str, out: &mut Vec<Problem>, budget: &mut MatchBudget) { + let mut problem = |m: String| out.push(Problem { path: path.to_string(), message: m }); + match dtd.model(&n.name) { + None => problem(format!("`{}` isn't declared in the DTD", n.name)), + Some(Model::Any) => {} + Some(Model::Empty) => { + if n.content { + problem(format!("`{}` should be empty", n.name)); + } + } + Some(Model::Mixed(allowed)) => { + for c in &n.children { + if !allowed.contains(&c.name) { + problem(format!("`{}` isn't allowed in `{}`", c.name, n.name)); + } + } + } + Some(Model::Children(cp)) => { + if n.text { + problem(format!("`{}` can't contain text", n.name)); + } + let seq: Vec<&str> = n.children.iter().map(|c| c.name.as_str()).collect(); + let matched = ends(cp, &seq, 0, &mut EndsMemo::new(), budget); + match matched { + Ok(positions) if positions.contains(&seq.len()) => {} + Ok(_) => { + let got = if seq.is_empty() { "nothing".to_string() } else { seq.join(", ") }; + problem(format!("`{}` contains {got}; the DTD asks for {}", n.name, show(cp))); + } + Err(error) => { + if !budget.reported { + problem(format!("`{}`: {error}", n.name)); + budget.reported = true; + } + } + } + } + } + for a in dtd.required.get(&n.name).into_iter().flatten() { + if !n.attrs.contains(a) { + problem(format!("`{}` is missing the required attribute `{a}`", n.name)); + } + } + let mut seen: HashMap<&str, usize> = HashMap::new(); + for c in &n.children { + let k = seen.entry(c.name.as_str()).or_default(); + *k += 1; + check(dtd, c, &format!("{path}/{}[{k}]", c.name), out, budget); + } +} + +/// Validate `xml` against `dtd`; an empty list when it's valid. +/// +/// Validation rejects input above the internal byte, depth, node, attribute and content-model +/// matching budgets. Only predefined entities and numeric character references are resolved; a +/// general entity reference is reported as unsupported rather than expanded or fetched. +pub fn validate(dtd: &Dtd, xml: &str) -> Vec<Problem> { + match read_tree(xml) { + Ok(root) => { + let mut out = Vec::new(); + let path = root.name.clone(); + check(dtd, &root, &path, &mut out, &mut MatchBudget::default()); + out + } + Err(e) => vec![Problem { path: String::new(), message: format!("not well-formed XML: {e}") }], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const DTD: &str = r##"<!-- an article --> +<!ENTITY % inline "#PCDATA | em | term"> +<!ELEMENT Root (story+, figure*)> +<!ELEMENT story (title, (para | list)*)> +<!ELEMENT title (%inline;)*> +<!ELEMENT para (%inline;)*> +<!ELEMENT list (para+)> +<!ELEMENT em (#PCDATA)> +<!ELEMENT term (#PCDATA)> +<!ELEMENT figure EMPTY> +<!ATTLIST figure href CDATA #REQUIRED alt CDATA "a > b" kind (photo|chart) "photo">"##; + + #[test] + fn content_models_and_required_attributes() { + let dtd = parse(DTD).unwrap(); + assert_eq!(dtd.element_names().count(), 8); + let ok = r#"<Root><story><title>T <em>x</em></title><para>a</para><list><para>b</para></list></story><figure href="a.png"/></Root>"#; + assert_eq!(validate(&dtd, ok), vec![]); + let bad = r#"<Root><story><para>no title</para></story><figure/><figure href="b"><em>x</em></figure><aside/></Root>"#; + let p = validate(&dtd, bad); + let msgs: Vec<String> = p.iter().map(|p| format!("{}: {}", p.path, p.message)).collect(); + assert!(msgs.iter().any(|m| m.starts_with("Root/story[1]: `story` contains para; the DTD asks for (title, (para | list)*)")), "{msgs:?}"); + assert!(msgs.iter().any(|m| m == "Root/figure[1]: `figure` is missing the required attribute `href`"), "{msgs:?}"); + assert!(msgs.iter().any(|m| m == "Root/figure[2]: `figure` should be empty"), "{msgs:?}"); + assert!(msgs.iter().any(|m| m == "Root/aside[1]: `aside` isn't declared in the DTD"), "{msgs:?}"); + // The root's model fails too (aside isn't in it). + assert!(msgs.iter().any(|m| m.starts_with("Root: ")), "{msgs:?}"); + // Text where only elements are allowed; an element not in a mixed model. + let p = validate(&dtd, "<Root><story>loose<title><list/></title></story></Root>"); + assert!(p.iter().any(|p| p.message == "`story` can't contain text"), "{p:?}"); + assert!(p.iter().any(|p| p.message == "`list` isn't allowed in `title`"), "{p:?}"); + assert!(parse("<!ELEMENT a (b, c | d)>").is_err()); + assert!(parse("just text").is_err()); + } + + /// A few hundred bytes of nested parameter entities used to inflate multiplicatively across + /// the eight wholly-string-replacing passes (#713); expansion is capped. + #[test] + fn parameter_entities_cannot_expand_without_a_budget() { + let mut src = String::from("<!ENTITY % e1 \"xx\">\n"); + for i in 2..=6 { + src.push_str(&format!("<!ENTITY % e{i} \"{}\">\n", format!("%e{};", i - 1).repeat(16))); + } + src.push_str("<!ELEMENT r (%e6;)>"); + assert!(src.len() < 500, "the payload is small: {} bytes", src.len()); + let err = parse(&src).unwrap_err(); + assert!(err.contains("expand the DTD beyond"), "{err}"); + // Entities that expand a little still parse. + let dtd = parse("<!ENTITY % inline \"#PCDATA | em\">\n<!ELEMENT r (%inline;)*>").unwrap(); + assert_eq!(dtd.element_names().collect::<Vec<_>>(), ["r"]); + } + + #[test] + fn repetition_matches_like_a_regular_expression() { + let dtd = parse("<!ELEMENT r ((a, b?)+, c*)><!ELEMENT a EMPTY><!ELEMENT b EMPTY><!ELEMENT c EMPTY>").unwrap(); + for (xml, ok) in [ + ("<r><a/></r>", true), + ("<r><a/><b/><a/><c/><c/></r>", true), + ("<r><a/><a/><b/></r>", true), + ("<r><b/></r>", false), + ("<r><a/><b/><b/></r>", false), + ("<r><a/><c/><a/></r>", false), + ("<r/>", false), + ] { + assert_eq!(validate(&dtd, xml).is_empty(), ok, "{xml}"); + } + } + + #[test] + fn parameter_entity_bomb_is_rejected() { + let mut src = String::new(); + for i in (0..10).rev() { + let value = if i == 0 { "x".to_string() } else { format!("%e{};", i - 1).repeat(8) }; + src.push_str(&format!("<!ENTITY % e{i} \"{value}\">\n")); + } + src.push_str("<!ELEMENT root (%e9;)>"); + match parse(&src) { + Err(error) => assert!(error.contains("parameter entities expand"), "{error}"), + Ok(_) => panic!("parameter entity expansion bomb was accepted"), + } + } + + /// `n` parameter entities, `e{i}` referring to `e{i-1}` and `e0` being `x`, declared in ascending + /// or descending order, and an element `root` whose model uses the last one. + fn entity_chain(n: usize, ascending: bool) -> String { + let mut order: Vec<usize> = (0..n).collect(); + if !ascending { + order.reverse(); + } + let mut src = String::new(); + for i in order { + let value = if i == 0 { "x".to_string() } else { format!("%e{};", i - 1) }; + src.push_str(&format!("<!ENTITY % e{i} \"{value}\">\n")); + } + src.push_str(&format!("<!ELEMENT root (%e{};)><!ELEMENT x EMPTY>", n - 1)); + src + } + + #[test] + fn parameter_entity_reverse_chain_expands_completely() { + let dtd = parse(&entity_chain(20, false)).unwrap(); + assert_eq!(validate(&dtd, "<root><x/></root>"), vec![]); + } + + #[test] + fn parameter_entity_ascending_chain_expands_completely() { + // With `e0` declared first, replacing the entities in declaration order resolves one level per pass. + let dtd = parse(&entity_chain(20, true)).unwrap(); + assert_eq!(validate(&dtd, "<root><x/></root>"), vec![]); + } + + #[test] + fn parameter_entity_cycle_is_refused() { + // Two entities that refer to each other, and one whose value is its own reference. + for src in ["<!ENTITY % a \"%b;\"><!ENTITY % b \"%a;\"><!ELEMENT root (%a;)>", "<!ENTITY % a \"%a;\"><!ELEMENT root (%a;)>"] { + match parse(src) { + Err(error) => assert!(error.contains("refer to themselves"), "{src}: {error}"), + Ok(dtd) => panic!("a cycle was accepted ({src}): {:?}", dtd.model("root")), + } + } + } + + #[test] + fn parameter_entity_chain_deeper_than_the_limit_is_refused() { + for ascending in [true, false] { + for n in [65, 70] { + match parse(&entity_chain(n, ascending)) { + Err(error) => assert!(error.contains("deeper than 64 levels"), "{n}, {ascending}: {error}"), + Ok(dtd) => panic!("a chain of {n} ({ascending}) was accepted: {:?}", dtd.model("root")), + } + } + let dtd = parse(&entity_chain(64, ascending)).unwrap(); + assert_eq!(validate(&dtd, "<root><x/></root>"), vec![], "{ascending}"); + } + } + + #[test] + fn parameter_entity_name_scan_stops_at_the_next_percent() { + // A name never contains `%`, so the search for the closing `;` stops at the next one: the + // searches of a run of `%` don't overlap and a round stays linear. (Looking past the next + // `%` would expand this reference to an entity that is named `a%b`.) + let entities = [("a%b".to_string(), "X".to_string())]; + assert_eq!(expand_parameter_entities("%a%b;", &entities), Ok("%a%b;".to_string())); + // A run of `%` around a real reference still finds it. + let entities = [("model".to_string(), "EMPTY".to_string())]; + assert_eq!(expand_parameter_entities("%%%model;%%", &entities), Ok("%%EMPTY%%".to_string())); + } + + #[test] + fn parameter_entity_with_a_long_name_expands() { + // A name can be any length: the search for the closing `;` has no window. + let name = "n".repeat(300); + let dtd = parse(&format!("<!ENTITY % {name} \"EMPTY\"><!ELEMENT root %{name};>")).unwrap(); + assert_eq!(dtd.model("root"), Some(&Model::Empty)); + } + + #[test] + fn percent_in_text_without_a_reference_is_left_alone() { + // `100% sure` (a space ends the search) and a `%` followed by 1 MiB without a `;` are text. + let text = format!("100% sure, %{}", "a".repeat(1 << 20)); + let entities = [("a".to_string(), "X".to_string())]; + assert_eq!(expand_parameter_entities(&text, &entities), Ok(text.clone())); + } + + /// `a` inside `levels` groups, each repeated: `((a)*)*…`. + fn nested_repetitions(levels: usize) -> String { + format!("{}a{}", "(".repeat(levels), ")*".repeat(levels)) + } + + #[test] + fn nested_repetitions_validate_without_going_exponential() { + // Ten levels over 100 children: each level asked the one below for the same positions again + // and again, about 10^14 steps without the memo of `ends`. + let dtd = parse(&format!("<!ELEMENT root {}><!ELEMENT a EMPTY><!ELEMENT b EMPTY>", nested_repetitions(10))).unwrap(); + assert_eq!(validate(&dtd, &format!("<root>{}</root>", "<a/>".repeat(100))), vec![]); + let problems = validate(&dtd, &format!("<root>{}<b/></root>", "<a/>".repeat(100))); + assert_eq!(problems.len(), 1, "{problems:?}"); + } + + #[test] + fn repetition_of_a_sequence_of_optional_elements_validates() { + // `(a, a?, a?, a?, a?, a?)*` over 90 children: every way to split the children among the + // repetitions reaches the same positions, and the paths used to be kept apart in each round. + let dtd = parse("<!ELEMENT r (a, a?, a?, a?, a?, a?)*><!ELEMENT a EMPTY><!ELEMENT b EMPTY>").unwrap(); + assert_eq!(validate(&dtd, &format!("<r>{}</r>", "<a/>".repeat(90))), vec![]); + let problems = validate(&dtd, &format!("<r>{}<b/></r>", "<a/>".repeat(90))); + assert_eq!(problems.len(), 1, "{problems:?}"); + } + + #[test] + fn parameter_entity_first_declaration_wins() { + let dtd = parse("<!ENTITY % model \"EMPTY\"><!ENTITY % model \"ANY\"><!ELEMENT root %model;>").unwrap(); + assert_eq!(dtd.model("root"), Some(&Model::Empty)); + } + + #[test] + fn parameter_entity_unknown_and_lone_percent_are_preserved() { + let src = "%nothing; <!ELEMENT root EMPTY> %"; + let dtd = parse(src).unwrap(); + assert_eq!(dtd.model("root"), Some(&Model::Empty)); + assert_eq!(expand_parameter_entities("%nothing; %", &[]), Ok("%nothing; %".to_string())); + } + + #[test] + fn parameter_entity_many_flat_declarations_parse() { + let mut src = String::new(); + for i in 0..5000 { + src.push_str(&format!("<!ENTITY % e{i} \"x\">\n")); + } + src.push_str("<!ELEMENT root (%e0;, %e2499;, %e4999;)><!ELEMENT x EMPTY>"); + let dtd = parse(&src).unwrap(); + assert_eq!(validate(&dtd, "<root><x/><x/><x/></root>"), vec![]); + } + + /// An element `root` whose content model is `a` inside `depth` nested groups. + fn nested_model(depth: usize) -> String { + format!("<!ELEMENT root {}a{}><!ELEMENT a EMPTY>", "(".repeat(depth), ")".repeat(depth)) + } + + #[test] + fn content_model_nested_100000_deep_is_refused() { + // One recursion per `(` overflowed the stack: an abort, not a panic. + match parse(&nested_model(100_000)) { + Err(error) => assert!(error.contains("nested more than 64 levels"), "{error}"), + Ok(_) => panic!("a content model nested 100000 deep was accepted"), + } + } + + #[test] + fn content_model_nesting_limit() { + let dtd = parse(&nested_model(64)).unwrap(); + assert_eq!(validate(&dtd, "<root><a/></root>"), vec![]); + assert_eq!(validate(&dtd, "<root/>").len(), 1); + match parse(&nested_model(65)) { + Err(error) => assert_eq!(error, "<!ELEMENT root>: content model nested more than 64 levels"), + Ok(_) => panic!("a content model nested 65 deep was accepted"), + } + } + + #[test] + fn sequence_of_40_optional_elements_validates() { + // Keeping every path through the sequence meant 2^40 positions here. + let dtd = parse(&format!("<!ELEMENT r ({})><!ELEMENT a EMPTY>", ["a?"; 40].join(", "))).unwrap(); + assert_eq!(validate(&dtd, &format!("<r>{}</r>", "<a/>".repeat(40))), vec![]); + let problems = validate(&dtd, &format!("<r>{}</r>", "<a/>".repeat(41))); + assert_eq!(problems.len(), 1, "{problems:?}"); + assert!(problems[0].message.starts_with("`r` contains a, a, a"), "{problems:?}"); + } + + #[test] + fn incomplete_declarations_and_malformed_mixed_models_are_rejected() { + assert!(parse("<!ELEMENT r EMPTY").is_err()); + assert!(parse("<!-- unterminated").is_err()); + for model in ["(#PCDATA | a)", "(#PCDATA, a)*", "(#PCDATA | )*", "(#PCDATA | a)* junk"] { + assert!(parse(&format!("<!ELEMENT r {model}>")).is_err(), "{model}"); + } + assert!(parse("<!ELEMENT r (#PCDATA)>").is_ok()); + assert!(parse("<!ELEMENT r (#PCDATA)*>").is_ok()); + assert!(parse("<!ELEMENT r (#PCDATA | a)*>").is_ok()); + } + + #[test] + fn parameter_entities_are_not_expanded_inside_comments() { + let dtd = parse( + r#"<!ENTITY % e "--> <!ELEMENT r ANY> <!--"> +<!-- %e; --> +<!ELEMENT r EMPTY> +<!ELEMENT a EMPTY>"#, + ) + .unwrap(); + assert_eq!(dtd.model("r"), Some(&Model::Empty)); + assert!(!validate(&dtd, "<r><a/></r>").is_empty()); + } + + #[test] + fn notation_attribute_type_keeps_following_required_attribute_aligned() { + let dtd = parse("<!ELEMENT r ANY><!ATTLIST r kind NOTATION (png|jpeg) #IMPLIED id CDATA #REQUIRED>").unwrap(); + assert!(validate(&dtd, "<r kind='png'/>").iter().any(|p| p.message.contains("required attribute `id`"))); + assert!(validate(&dtd, "<r id='x'/>").is_empty()); + } + + #[test] + fn malformed_or_unbounded_xml_is_rejected_before_validation() { + let dtd = parse("<!ELEMENT r ANY><!ELEMENT a EMPTY>").unwrap(); + for xml in ["<r/><broken", "<r></r><a/>", "<r a='1' a='2'/>"] { + assert!(!validate(&dtd, xml).is_empty(), "{xml}"); + } + let deep = format!("{}{}", "<r>".repeat(MAX_VALIDATION_DEPTH + 1), "</r>".repeat(MAX_VALIDATION_DEPTH + 1)); + let problems = validate(&dtd, &deep); + assert!(problems.iter().any(|p| p.message.contains("nesting exceeds")), "{problems:?}"); + } + + #[test] + fn references_must_be_declared_and_empty_elements_must_have_no_content() { + let dtd = parse("<!ELEMENT r ANY><!ELEMENT e EMPTY><!ENTITY known 'value'>").unwrap(); + assert!(validate(&dtd, "<r>&missing;</r>").iter().any(|p| p.message.contains("unsupported general entity"))); + assert!(validate(&dtd, "<r>&known;</r>").iter().any(|p| p.message.contains("unsupported general entity"))); + assert!(validate(&dtd, "<r>&#x41;&amp;</r>").is_empty()); + assert!(!validate(&dtd, "<r>&#0;</r>").is_empty()); + for xml in ["<e> </e>", "<e><!--x--></e>", "<e><?work x?></e>", "<e>&amp;</e>"] { + assert!(validate(&dtd, xml).iter().any(|p| p.message.contains("should be empty")), "{xml}"); + } + assert!(validate(&dtd, "<e/>").is_empty()); + } + + #[test] + fn ambiguous_content_matching_stops_at_its_budget() { + let dtd = parse("<!ELEMENT r ((a*)*)*><!ELEMENT a EMPTY>").unwrap(); + let xml = format!("<r>{}</r>", "<a/>".repeat(10_000)); + let problems = validate(&dtd, &xml); + assert!(problems.iter().any(|p| p.message.contains("matching exceeded its ")), "{}", problems.len()); + } +} diff --git a/crates/xml/src/lib.rs b/crates/xml/src/lib.rs index 87057b387..8d0913342 100644 --- a/crates/xml/src/lib.rs +++ b/crates/xml/src/lib.rs @@ -25,6 +25,7 @@ #[doc = include_str!("../README.md")] struct ReadmeExamples; +pub mod dtd; mod read; mod tree; pub mod value; @@ -49,6 +50,9 @@ pub enum Error { /// The tree would hold more than [`Limits::max_nodes`] nodes. #[error("the XML holds more than {0} nodes")] TooManyNodes(usize), + /// The tree would hold more than [`Limits::max_elements`] elements. + #[error("the XML holds more than {0} elements")] + TooManyElements(usize), /// One start tag has more than [`Limits::max_attrs`] attributes. #[error("an XML element has more than {0} attributes")] TooManyAttrs(usize), @@ -76,6 +80,14 @@ pub enum Error { impl Error { /// Was a limit exceeded (as opposed to the markup being wrong)? pub fn is_limit(&self) -> bool { - matches!(self, Error::TooLarge(_) | Error::TooDeep(_) | Error::TooManyNodes(_) | Error::TooManyAttrs(_) | Error::TooManyAttrsTotal(_)) + matches!( + self, + Error::TooLarge(_) + | Error::TooDeep(_) + | Error::TooManyNodes(_) + | Error::TooManyElements(_) + | Error::TooManyAttrs(_) + | Error::TooManyAttrsTotal(_) + ) } } diff --git a/crates/xml/src/read.rs b/crates/xml/src/read.rs index e155099e8..3b79a8751 100644 --- a/crates/xml/src/read.rs +++ b/crates/xml/src/read.rs @@ -25,6 +25,10 @@ pub struct Limits { /// 2,000,000: a tree node costs about 72 bytes before its strings, and text lies between /// elements at most, so this is about a million elements of an indented document. pub max_nodes: usize, + /// Most elements kept in a tree at once, independent of text nodes. Elements handed to a + /// streaming callback leave the count with everything inside them. Default unlimited; the + /// node limit already bounds element count for callers using default limits. + pub max_elements: usize, /// Most attributes on one start tag, namespace declarations and malformed ones included. /// With [`Names::Canonical`] it is also the most namespace declarations in scope at once. /// Default 1024. @@ -38,8 +42,14 @@ pub struct Limits { } impl Limits { - pub const DEFAULT: Limits = - Limits { max_input: 256 * 1024 * 1024, max_depth: 256, max_nodes: 2_000_000, max_attrs: 1024, max_attrs_total: 4_000_000 }; + pub const DEFAULT: Limits = Limits { + max_input: 256 * 1024 * 1024, + max_depth: 256, + max_nodes: 2_000_000, + max_elements: usize::MAX, + max_attrs: 1024, + max_attrs_total: 4_000_000, + }; } impl Default for Limits { @@ -174,6 +184,11 @@ pub struct Options<'a> { /// malformed attribute is skipped, and bytes that are not UTF-8 become U+FFFD. Strict: each /// of those is an error, as are a second root element and text outside the root. pub strict: bool, + /// Require closing tags to match their opening tags, and reject unclosed elements at EOF, + /// while keeping the other lenient behaviors (including stopping after the first root). + /// This is useful when a format historically accepted a single-root prefix but rejected + /// malformed nesting. + pub strict_end_tags: bool, pub unknown_entity: UnknownEntity, pub doctype: Doctype, /// Keep CDATA sections as [`Node::CData`] instead of joining them to the text around them. @@ -197,6 +212,7 @@ impl Default for Options<'_> { names: Names::AsWritten, ns_decls: true, strict: false, + strict_end_tags: false, unknown_entity: UnknownEntity::Drop, doctype: Doctype::Ignore, cdata: false, @@ -269,9 +285,12 @@ impl<'a> Options<'a> { if bytes.len() > self.limits.max_input { return (None, Some(Error::TooLarge(self.limits.max_input).into())); } + if doctype_refused(bytes, self.doctype) { + return (None, Some(Error::Doctype.into())); + } let text = to_utf8(bytes); let mut events = Events::new(*self, &text, false); - let mut tree = Builder { opts: self, split, stack: Vec::new(), marks: Vec::new(), kept: 0, attrs: 0, root: None, at: 0 }; + let mut tree = Builder { opts: self, split, stack: Vec::new(), marks: Vec::new(), kept: 0, elements: 0, attrs: 0, root: None, at: 0 }; let mut err = tree.run(&mut events, &mut each).err(); // What was open when the read stopped goes into its parent as it is. while let Some(el) = tree.stack.pop() { @@ -313,6 +332,103 @@ impl<'a> Options<'a> { } } +/// Check declarations before handing input to the XML parser. Some parser implementations stop +/// on malformed XML declarations before reporting a later DOCTYPE; formats that reject internal +/// subsets need the security decision to take precedence over that unrelated syntax error. +fn doctype_refused(input: &[u8], policy: Doctype) -> bool { + if policy == Doctype::Ignore { + return false; + } + let mut at = 0; + while at < input.len() { + let Some(rel) = input.get(at..).and_then(|bytes| bytes.iter().position(|b| *b == b'<')) else { + break; + }; + at += rel; + let Some(rest) = input.get(at..) else { break }; + if rest.starts_with(b"<!--") { + at = after(input, at + 4, b"-->"); + } else if rest.starts_with(b"<![CDATA[") { + at = after(input, at + 9, b"]]>"); + } else if rest.starts_with(b"<?") { + at = after_instruction(input, at + 2); + } else if rest.starts_with(b"<!DOCTYPE") && rest.get(9).is_some_and(|b| b.is_ascii_whitespace()) { + if policy == Doctype::Reject { + return true; + } + let (end, subset) = doctype_end(input, at + 9); + if subset { + return true; + } + at = end; + } else { + at = after_markup(input, at + 1); + } + } + false +} + +fn after(input: &[u8], start: usize, terminator: &[u8]) -> usize { + input + .get(start..) + .and_then(|rest| rest.windows(terminator.len()).position(|w| w == terminator)) + .map_or(input.len(), |i| start + i + terminator.len()) +} + +fn after_instruction(input: &[u8], mut at: usize) -> usize { + let mut quote = None; + while let Some(&byte) = input.get(at) { + if let Some(q) = quote { + if byte == q { + quote = None; + } + } else if matches!(byte, b'\'' | b'"') { + quote = Some(byte); + } else if input.get(at..).is_some_and(|rest| rest.starts_with(b"?>")) { + return at + 2; + } + at += 1; + } + input.len() +} + +fn doctype_end(input: &[u8], mut at: usize) -> (usize, bool) { + let mut quote = None; + let mut subset = false; + while let Some(&byte) = input.get(at) { + if let Some(q) = quote { + if byte == q { + quote = None; + } + } else if matches!(byte, b'\'' | b'"') { + quote = Some(byte); + } else if byte == b'[' { + subset = true; + } else if byte == b'>' { + return (at + 1, subset); + } + at += 1; + } + (input.len(), subset) +} + +fn after_markup(input: &[u8], mut at: usize) -> usize { + let mut quote = None; + while let Some(&byte) = input.get(at) { + if let Some(q) = quote { + if byte == q { + quote = None; + } + } else if matches!(byte, b'\'' | b'"') { + quote = Some(byte); + } else if byte == b'>' { + return at + 1; + } + at += 1; + } + input.len() +} + /// One step of a document. See [`Options::events`]. #[derive(Clone, Debug, PartialEq)] pub enum Event { @@ -443,9 +559,9 @@ impl<'o, 'i> Events<'o, 'i> { } Q::End(e) => { let Some(top) = self.open.last() else { - return if self.opts.strict { self.syntax("an end tag has no start tag") } else { Ok(None) }; + return if self.opts.strict || self.opts.strict_end_tags { self.syntax("an end tag has no start tag") } else { Ok(None) }; }; - if self.opts.strict && top.raw != e.name().as_ref() { + if (self.opts.strict || self.opts.strict_end_tags) && top.raw != e.name().as_ref() { return self.syntax(format!("the end tag `{}` does not match its start tag", String::from_utf8_lossy(e.name().as_ref()))); } self.end() @@ -485,7 +601,11 @@ impl<'o, 'i> Events<'o, 'i> { } Q::Decl(_) => return Ok(None), Q::Eof => { - return if self.opts.strict && !self.open.is_empty() { self.syntax("an element is not closed") } else { Ok(Some(None)) }; + return if (self.opts.strict || self.opts.strict_end_tags) && !self.open.is_empty() { + self.syntax("an element is not closed") + } else { + Ok(Some(None)) + }; } }; Ok(Some(Some(event))) @@ -614,7 +734,7 @@ impl<'o, 'i> Events<'o, 'i> { let keep_name = self.end_names || canonical.is_some_and(|c| c.element.is_some()); self.open.push(Open { scope, - raw: if self.opts.strict { raw.as_ref().to_vec() } else { Vec::new() }, + raw: if self.opts.strict || self.opts.strict_end_tags { raw.as_ref().to_vec() } else { Vec::new() }, name: if keep_name { name.clone() } else { String::new() }, }); Ok(Event::Start { name, attrs: out }) @@ -626,8 +746,9 @@ struct Builder<'b, 'o> { split: &'b [&'b str], stack: Vec<El>, /// The node and attribute counts when each open element started. - marks: Vec<(usize, usize)>, + marks: Vec<(usize, usize, usize)>, kept: usize, + elements: usize, /// Attributes in the elements built so far and not handed out. attrs: usize, root: Option<El>, @@ -686,7 +807,11 @@ impl Builder<'_, '_> { if self.root.is_some() { return Err(Error::Syntax { at: self.at, msg: "more than one root element".into() }.into()); } - self.marks.push((self.kept, self.attrs)); + self.marks.push((self.kept, self.attrs, self.elements)); + self.elements = self.elements.saturating_add(1); + if self.elements > self.opts.limits.max_elements { + return Err(Error::TooManyElements(self.opts.limits.max_elements).into()); + } self.attrs = self.attrs.saturating_add(attrs.len()); if self.attrs > self.opts.limits.max_attrs_total { return Err(Error::TooManyAttrsTotal(self.opts.limits.max_attrs_total).into()); @@ -710,7 +835,7 @@ impl Builder<'_, '_> { /// Attaches a complete element to its parent, hands it out, or makes it the root. fn finish<E: From<Error>>(&mut self, mut el: El, each: &mut impl FnMut(El) -> Result<(), E>) -> Result<(), E> { - let (mark, attrs_mark) = self.marks.pop().unwrap_or((0, 0)); + let (mark, attrs_mark, elements_mark) = self.marks.pop().unwrap_or((0, 0, 0)); if self.opts.drop_blank_text && el.children.iter().any(|n| matches!(n, Node::El(_))) { let is_text = |n: &Node| matches!(n, Node::Text(_)); if el.children.iter().all(|n| !is_text(n) || matches!(n, Node::Text(t) if t.trim().is_empty())) { @@ -727,6 +852,7 @@ impl Builder<'_, '_> { each(el)?; // The element and everything inside it have left the tree. self.kept = mark; + self.elements = elements_mark; self.attrs = attrs_mark; } else { self.push(Node::El(el))?; diff --git a/crates/xml/tests/hostile.rs b/crates/xml/tests/hostile.rs index 8535d5835..2d387519b 100644 --- a/crates/xml/tests/hostile.rs +++ b/crates/xml/tests/hostile.rs @@ -22,14 +22,40 @@ fn text_len(e: &El) -> usize { fn the_defaults_are_the_documented_ones() { assert_eq!( Limits::default(), - Limits { max_input: 256 * 1024 * 1024, max_depth: 256, max_nodes: 2_000_000, max_attrs: 1024, max_attrs_total: 4_000_000 } + Limits { + max_input: 256 * 1024 * 1024, + max_depth: 256, + max_nodes: 2_000_000, + max_elements: usize::MAX, + max_attrs: 1024, + max_attrs_total: 4_000_000 + } ); - for e in [Error::TooLarge(1), Error::TooDeep(1), Error::TooManyNodes(1), Error::TooManyAttrs(1), Error::TooManyAttrsTotal(1)] { + for e in [ + Error::TooLarge(1), + Error::TooDeep(1), + Error::TooManyNodes(1), + Error::TooManyElements(1), + Error::TooManyAttrs(1), + Error::TooManyAttrsTotal(1), + ] { assert!(e.is_limit(), "{e}"); } assert!(!Error::NoRoot.is_limit() && !Error::Doctype.is_limit()); } +#[test] +fn strict_end_tags_keep_first_root_and_entity_compatibility() { + let opts = Options { strict_end_tags: true, unknown_entity: UnknownEntity::Literal, doctype: Doctype::Ignore, ..Options::default() }; + let root = opts.parse(b"<!DOCTYPE a [<!ENTITY ignored 'x'>]><a>&unknown;<b/></a><tail/>").unwrap(); + assert_eq!(root.name, "a"); + assert_eq!(root.text().as_ref(), "&unknown;"); + + for malformed in [b"<a><b></a>".as_slice(), b"<a><b/>".as_slice(), b"</a><b/>".as_slice()] { + assert!(opts.parse(malformed).is_err(), "{}", String::from_utf8_lossy(malformed)); + } +} + #[test] fn a_depth_bomb_is_refused_at_the_limit() { let limits = Limits { max_depth: 8, ..Limits::DEFAULT }; @@ -412,6 +438,23 @@ fn a_node_count_charges_a_budget_shared_by_several_parts() { assert_eq!(short.parse(part.as_bytes()), Err(Error::TooManyNodes(200))); } +#[test] +fn element_limits_are_independent_and_streamed_rows_release_them() { + let limited = Options::default().with_limits(Limits { max_elements: 2, ..Limits::DEFAULT }); + assert_eq!(limited.parse(b"<r><a/><b/></r>"), Err(Error::TooManyElements(2))); + + let streaming = Options::default().with_limits(Limits { max_elements: 3, ..Limits::DEFAULT }); + let mut rows = 0; + let root = streaming + .parse_streaming(b"<s><row><a/></row><row><b/></row></s>", &["row"], |_| { + rows += 1; + Ok::<(), Error>(()) + }) + .unwrap(); + assert_eq!(rows, 2); + assert!(root.children.is_empty()); +} + /// A part that cannot be read to its end still gives what came before the failure. #[test] fn a_failed_streaming_read_returns_what_it_had() { diff --git a/crates/zip/src/write.rs b/crates/zip/src/write.rs index 2b32e1e74..e1fdfad9e 100644 --- a/crates/zip/src/write.rs +++ b/crates/zip/src/write.rs @@ -20,11 +20,12 @@ pub enum Compression { /// timestamp on every entry. Entries are written in the order they are added. pub struct Writer { zip: zip::ZipWriter<Cursor<Vec<u8>>>, + legacy_utf8: bool, } impl Default for Writer { fn default() -> Writer { - Writer { zip: zip::ZipWriter::new(Cursor::new(Vec::new())) } + Writer { zip: zip::ZipWriter::new(Cursor::new(Vec::new())), legacy_utf8: false } } } @@ -33,6 +34,14 @@ impl Writer { Writer::default() } + /// Writes the UTF-8 flag and version fields used by the previous dotLottie writer. + /// + /// This keeps stored archives byte-for-byte stable for existing users while still using the + /// shared writer for entry encoding and validation. + pub fn legacy_utf8() -> Writer { + Writer { legacy_utf8: true, ..Writer::default() } + } + /// Adds an entry from a byte slice. A name the archive already has is an error. pub fn add(&mut self, name: &str, data: &[u8], compression: Compression) -> Result<(), Error> { let (method, level) = match compression { @@ -70,6 +79,87 @@ impl Writer { /// The finished archive. pub fn finish(self) -> Result<Vec<u8>, Error> { - self.zip.finish().map(Cursor::into_inner).map_err(|e| Error::Write(e.to_string())) + let mut bytes = self.zip.finish().map(Cursor::into_inner).map_err(|e| Error::Write(e.to_string()))?; + if self.legacy_utf8 { + patch_legacy_utf8_headers(&mut bytes)?; + } + Ok(bytes) } } + +fn get_u16(bytes: &[u8], at: usize) -> Option<u16> { + Some(u16::from_le_bytes(bytes.get(at..at.checked_add(2)?)?.try_into().ok()?)) +} + +fn get_u32(bytes: &[u8], at: usize) -> Option<u32> { + Some(u32::from_le_bytes(bytes.get(at..at.checked_add(4)?)?.try_into().ok()?)) +} + +fn put_u32(bytes: &mut [u8], at: usize, value: u32) -> Result<(), Error> { + let dst = bytes + .get_mut(at..at.checked_add(4).ok_or_else(|| Error::Write("ZIP header offset overflow".into()))?) + .ok_or_else(|| Error::Write("short ZIP header".into()))?; + dst.copy_from_slice(&value.to_le_bytes()); + Ok(()) +} + +fn put_u16(bytes: &mut [u8], at: usize, value: u16) -> Result<(), Error> { + let dst = bytes + .get_mut(at..at.checked_add(2).ok_or_else(|| Error::Write("ZIP header offset overflow".into()))?) + .ok_or_else(|| Error::Write("short ZIP header".into()))?; + dst.copy_from_slice(&value.to_le_bytes()); + Ok(()) +} + +/// Patches the two header versions and UTF-8 bit to match the former dotLottie writer. +fn patch_legacy_utf8_headers(bytes: &mut [u8]) -> Result<(), Error> { + const EOCD: u32 = 0x0605_4b50; + const CENTRAL: u32 = 0x0201_4b50; + const LOCAL: u32 = 0x0403_4b50; + let eocd = bytes + .windows(4) + .rposition(|window| u32::from_le_bytes([window[0], window[1], window[2], window[3]]) == EOCD) + .ok_or_else(|| Error::Write("missing ZIP end record".into()))?; + let central_start = usize::try_from(get_u32(bytes, eocd + 16).ok_or_else(|| Error::Write("short ZIP end record".into()))?) + .map_err(|_| Error::Write("ZIP central directory offset overflow".into()))?; + let central_size = usize::try_from(get_u32(bytes, eocd + 12).ok_or_else(|| Error::Write("short ZIP end record".into()))?) + .map_err(|_| Error::Write("ZIP central directory size overflow".into()))?; + let central_end = + central_start.checked_add(central_size).filter(|end| *end <= eocd).ok_or_else(|| Error::Write("invalid ZIP central directory".into()))?; + let mut at = central_start; + while at < central_end { + if get_u32(bytes, at) != Some(CENTRAL) { + return Err(Error::Write("invalid ZIP central directory entry".into())); + } + let name = usize::from(get_u16(bytes, at + 28).ok_or_else(|| Error::Write("short ZIP entry".into()))?); + let extra = usize::from(get_u16(bytes, at + 30).ok_or_else(|| Error::Write("short ZIP entry".into()))?); + let comment = usize::from(get_u16(bytes, at + 32).ok_or_else(|| Error::Write("short ZIP entry".into()))?); + let length = 46usize + .checked_add(name) + .and_then(|n| n.checked_add(extra)) + .and_then(|n| n.checked_add(comment)) + .ok_or_else(|| Error::Write("ZIP entry size overflow".into()))?; + let next = at.checked_add(length).filter(|next| *next <= central_end).ok_or_else(|| Error::Write("short ZIP entry".into()))?; + let local = usize::try_from(get_u32(bytes, at + 42).ok_or_else(|| Error::Write("short ZIP entry".into()))?) + .map_err(|_| Error::Write("ZIP local-header offset overflow".into()))?; + if get_u32(bytes, local) != Some(LOCAL) { + return Err(Error::Write("invalid ZIP local header".into())); + } + // Version 45 is required by ZIP64; retain it. Ordinary entries use 2.0 to match dotLottie. + if get_u16(bytes, at + 6).is_some_and(|version| version < 45) { + put_u16(bytes, at + 6, 20)?; + put_u16(bytes, local + 4, 20)?; + } + put_u16(bytes, at + 4, 20)?; + put_u32(bytes, at + 38, 0)?; + let central_flags = get_u16(bytes, at + 8).ok_or_else(|| Error::Write("short ZIP entry".into()))? | 0x0800; + let local_flags = get_u16(bytes, local + 6).ok_or_else(|| Error::Write("short ZIP local header".into()))? | 0x0800; + put_u16(bytes, at + 8, central_flags)?; + put_u16(bytes, local + 6, local_flags)?; + at = next; + } + if at != central_end { + return Err(Error::Write("invalid ZIP central directory size".into())); + } + Ok(()) +} diff --git a/licenses/dwg/acadrust-MPL-2.0.txt b/licenses/dwg/acadrust-MPL-2.0.txt new file mode 100644 index 000000000..16bfd9043 --- /dev/null +++ b/licenses/dwg/acadrust-MPL-2.0.txt @@ -0,0 +1,374 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under the name "LEGAL", and included in all Covered Software +distributed in Source Code Form. Except to the extent prohibited by +statute or regulation, such description must be sufficiently detailed +for a recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md b/licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md new file mode 100644 index 000000000..35fd822bb --- /dev/null +++ b/licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md @@ -0,0 +1,40 @@ +# Third-Party Notices + +## ACadSharp + +The DWG reader and writer include code ported and adapted from ACadSharp. The repository +history's initial DWG support commit identifies the source classes explicitly, including +`DwgStreamReaderBase`, `DwgLZ77AC21Decompressor`, `DwgFileHeaderWriterAC18`, and +`DwgObjectWriter`. Their current Rust implementations are in `src/io/dwg`. + +Copyright (c) 2021 Albert Domenech + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## DWG Format References + +DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG +specification and reverse engineering, including comparison with drawings produced by CAD +applications. LibreDWG is used as a secondary cross-check for selected field names and +layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's +`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not +translated routines. The repository history and source review found no LibreDWG routines +ported into the implementation. The source comments identify the specific cross-checks. diff --git a/scripts/fetch-opus-vectors.sh b/scripts/fetch-opus-vectors.sh index d9f92befc..cce3d1489 100755 --- a/scripts/fetch-opus-vectors.sh +++ b/scripts/fetch-opus-vectors.sh @@ -11,7 +11,7 @@ URL=https://opus-codec.org/static/testvectors/opus_testvectors-rfc8251.tar.gz SHA256=6b26a22f9ba87b2b836906a9bb7afec5f8e54d49553b1200382520ee6fedfa55 DEST=${1:-target/fixtures/opus/vectors} -if [ -f "$DEST/testvector01.bit" ] && [ -f "$DEST/testvector12m.dec" ]; then +if [[ -f "$DEST/testvector01.bit" && -f "$DEST/testvector12m.dec" ]]; then echo "Opus vectors already in $DEST" exit 0 fi @@ -20,7 +20,7 @@ tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT len=$(curl -fsSIL --proto '=https' --proto-redir '=https' --retry 10 --retry-delay 2 --retry-all-errors --connect-timeout 20 --max-time 60 "$URL" | tr -d '\r' | awk 'tolower($1) == "content-length:" { n = $2 } END { print n }') -[ -n "$len" ] || { echo "could not read the archive size" >&2; exit 1; } +[[ -n "$len" ]] || { echo "could not read the archive size" >&2; exit 1; } # Small ranges, eight at a time: a range whose connection drops below 50 KB/s for 15 s is # abandoned and fetched again, which costs little for a 2 MB range. @@ -46,12 +46,12 @@ for attempt in 1 2 3 4 5; do range=${ranges[$i]} want=$((${range#*-} - ${range%-*} + 1)) part=$(printf '%s/part.%04d' "$tmp" "$i") - if [ "$(wc -c < "$part" 2> /dev/null || echo 0)" -ne "$want" ]; then + if [[ "$(wc -c < "$part" 2> /dev/null || echo 0)" -ne "$want" ]]; then short=1 fetch "$range" "$part" || true fi done - [ "$short" -eq 0 ] && break + [[ "$short" -eq 0 ]] && break done cat "$tmp"/part.* > "$tmp/vectors.tar.gz" diff --git a/scripts/test-workspace-concurrency.py b/scripts/test-workspace-concurrency.py new file mode 100644 index 000000000..96bfae304 --- /dev/null +++ b/scripts/test-workspace-concurrency.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Check the Workspace workflow's pull-request-only cancellation policy. + +The policy is the top-level `concurrency` block of .github/workflows/workspace.yml. This script +reads those fields, requires the documented expression shapes, and checks which group each event +would be given. The rest of the workflow is left to diff review, not frozen here. + +Use --workflow PATH to read a baseline or a deliberately wrong variant without touching this +checkout. +""" + +import argparse +import re +import sys +import unittest +from pathlib import Path + +try: # cross-check only; the reader below is what a plain `python3` run needs + import yaml +except ImportError: + yaml = None + +DEFAULT_WORKFLOW = Path(__file__).resolve().parent.parent / ".github" / "workflows" / "workspace.yml" +PULL_REQUEST, PUSH, DISPATCH = "pull_request", "push", "workflow_dispatch" + +# The two shapes this policy may use. GitHub reads `a && b || c` as "b, or c when a is false"; these +# patterns are the whole of that expression language this script understands, so a reworded policy +# has to be reworded here too, on purpose. github.ref, never github.head_ref or github.sha. +GROUP_SHAPE = re.compile( + r"(?P<prefix>[A-Za-z0-9._-]+)-\$\{\{\s*github\.event_name\s*==\s*'(?P<event>[a-z_]+)'\s*" + r"&&\s*github\.ref\s*\|\|\s*github\.run_id\s*\}\}" +) +CANCEL_SHAPE = re.compile(r"\$\{\{\s*github\.event_name\s*==\s*'(?P<event>[a-z_]+)'\s*\}\}") + + +def read_concurrency(text): + """The top-level `concurrency` mapping. A deliberately limited reader: two-space fields.""" + lines = text.splitlines() + starts = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(starts) != 1: + raise AssertionError(f"expected one top-level concurrency block, found {len(starts)}") + header = lines[starts[0]].partition("#")[0].strip() + if header != "concurrency:": + # `concurrency: |` and `concurrency: some-string` are scalars, not a mapping. Reading the + # lines under one as fields would let a workflow that is not this policy pass every check. + raise AssertionError(f"concurrency must be a mapping, not a scalar: {lines[starts[0]]!r}") + fields = {} + for line in lines[starts[0] + 1:]: + stripped = line.strip() + if stripped and not line.startswith(" "): + break # the next top-level key + if not stripped or stripped.startswith("#"): + continue + if not line.startswith(" ") or line.startswith(" "): + raise AssertionError(f"unexpected indentation under concurrency: {line!r}") + key, separator, value = stripped.partition(":") + if not separator: + raise AssertionError(f"not a field of concurrency: {line!r}") + fields[key.strip()] = value.strip() + return fields + + +def pull_request(number, run_id): + # github.ref for a pull request is refs/pull/<n>/merge: the PR number, never the branch name. + return (PULL_REQUEST, f"refs/pull/{number}/merge", run_id) + + +def other_run(event_name, ref, run_id): + return (event_name, ref, run_id) + + +MAIN, TAG = ("refs/heads/main", "refs/tags/v1.2.3") +SAME_GROUP = [ + ("a newer commit on the same pull request", pull_request(1316, 43599251877), pull_request(1316, 43600899878)), + ("a rerun of one main run", other_run(PUSH, MAIN, 7001), other_run(PUSH, MAIN, 7001)), +] +DIFFERENT_GROUPS = [ + ("two pull requests", pull_request(1316, 1), pull_request(1317, 1)), + ("the same branch name in two forks", pull_request(1316, 2), pull_request(1400, 2)), + ("two pushes to main", other_run(PUSH, MAIN, 3), other_run(PUSH, MAIN, 4)), + ("two release tag runs", other_run(PUSH, TAG, 5), other_run(PUSH, TAG, 6)), + ("two manual runs", other_run(DISPATCH, MAIN, 7), other_run(DISPATCH, MAIN, 8)), + ("a main push and a pull request", other_run(PUSH, MAIN, 9), pull_request(1316, 9)), + ("a release tag and a pull request", other_run(PUSH, TAG, 10), pull_request(1316, 10)), +] +CANCELLATION = [ + ("a push supersedes the previous run of its pull request", pull_request(1316, 11), True), + ("a push to main is never cancelled", other_run(PUSH, MAIN, 12), False), + ("a release tag run is never cancelled", other_run(PUSH, TAG, 13), False), + ("a manual run is never cancelled", other_run(DISPATCH, MAIN, 14), False), +] + + +class ConcurrencyTests(unittest.TestCase): + workflow = DEFAULT_WORKFLOW + + @classmethod + def setUpClass(cls): + cls.text = cls.workflow.read_text() + cls.fields = read_concurrency(cls.text) + cls.group_shape = GROUP_SHAPE.fullmatch(cls.fields.get("group", "")) + cls.cancel_shape = CANCEL_SHAPE.fullmatch(cls.fields.get("cancel-in-progress", "")) + if not cls.group_shape or not cls.cancel_shape: + raise AssertionError(f"the concurrency fields are not the documented shapes: {cls.fields}") + + def cancels(self, event_name): + return event_name == self.cancel_shape["event"] + + def group(self, event_name, ref, run_id): + return self.group_shape["prefix"] + "-" + (ref if event_name == self.group_shape["event"] else str(run_id)) + + def test_policy_is_the_two_documented_fields(self): + self.assertEqual(sorted(self.fields), ["cancel-in-progress", "group"]) + self.assertEqual(self.group_shape["prefix"], "workspace") + self.assertEqual(self.group_shape["event"], PULL_REQUEST) + self.assertEqual(self.cancel_shape["event"], PULL_REQUEST) + + def test_a_scalar_concurrency_value_is_not_read_as_a_mapping(self): + cases = { + "a block scalar": "concurrency: |\n group: workspace-x\n cancel-in-progress: true\n", + "a plain scalar": "concurrency: workspace-x\njobs: {}\n", + } + for description, text in cases.items(): + with self.subTest(description): + with self.assertRaises(AssertionError): + read_concurrency(text) + + def test_one_group_per_pull_request_and_run(self): + for description, first, second in SAME_GROUP: + with self.subTest(description): + self.assertEqual(self.group(*first), self.group(*second), description) + for description, first, second in DIFFERENT_GROUPS: + with self.subTest(description): + self.assertNotEqual(self.group(*first), self.group(*second), description) + + def test_only_a_pull_request_cancels(self): + for description, context, expected in CANCELLATION: + with self.subTest(description): + self.assertEqual(self.cancels(context[0]), expected, description) + + def test_pyyaml_reads_the_same_fields(self): + if yaml is None: + self.skipTest("PyYAML is not installed; the limited reader above ran alone") + document = yaml.load(self.text, Loader=yaml.BaseLoader) # BaseLoader keeps `on:` a string + self.assertEqual(document["concurrency"], self.fields) + + def test_no_per_job_concurrency_is_added(self): + indented = [line for line in self.text.splitlines() + if line.strip().startswith("concurrency:") and not line.startswith("concurrency:")] + self.assertEqual(indented, [], "the policy belongs to the workflow, not to one job") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--workflow", type=Path, default=DEFAULT_WORKFLOW, help="workflow to read (default: %(default)s)") + arguments, remaining = parser.parse_known_args() + ConcurrencyTests.workflow = arguments.workflow + unittest.main(argv=[sys.argv[0], *remaining]) + + +if __name__ == "__main__": + main() diff --git a/sonar-project.properties b/sonar-project.properties index d08c71698..c2be7b192 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -7,7 +7,11 @@ sonar.organization=storytold # *_tests.rs), which includes the browser fault-injection fixtures in crates/platform/tests. sonar.sources=. sonar.tests=. -sonar.test.inclusions=**/tests/**,**/tests.rs,**/*_tests.rs +# scripts/test-workspace-concurrency.py is a unit-test module for the Workspace workflow's +# cancellation policy: its unittest cases read a workflow and assert on it, so it is test +# code, analysed as a test and still linted, indexed and reported, not counted as production +# code that needs coverage. Its name is listed exactly, so no other script is classified. +sonar.test.inclusions=**/tests/**,**/tests.rs,**/*_tests.rs,scripts/test-workspace-concurrency.py # Codec constant tables are transcribed from the format specifications; their repeated rows are # data, not copy-pasted logic. @@ -15,6 +19,29 @@ sonar.cpd.exclusions=**/*tables.rs # S4790 (weak hash): the ICC specification defines the profile ID as the MD5 of the profile, so # no other algorithm produces an ID other software accepts. It identifies, it does not protect. -sonar.issue.ignore.multicriteria=icc_profile_id +# +# The encrypted packages below are the same case: each format derives its keys from MD5 or SHA-1, +# so substituting a stronger hash stops the files the module reads and writes from opening. +sonar.issue.ignore.multicriteria=icc_profile_id,xls_filepass_hash,pdf_standard_security_hash,odf_package_hash,gha-lockfile sonar.issue.ignore.multicriteria.icc_profile_id.ruleKey=rust:S4790 sonar.issue.ignore.multicriteria.icc_profile_id.resourceKey=crates/cms/src/write.rs +# xls: [MS-OFFCRYPTO] 2.3.6.1-2.3.6.2, where RC4 1.1 takes its key and verifier from MD5, and +# 2.3.5.1-2.3.5.2, where RC4 CryptoAPI takes them from SHA-1. +sonar.issue.ignore.multicriteria.xls_filepass_hash.ruleKey=rust:S4790 +sonar.issue.ignore.multicriteria.xls_filepass_hash.resourceKey=crates/xls/src/crypt.rs +# pdf: ISO 32000-1 7.6.3.3, Algorithms 2-7. Revisions 2-4 derive the file key and the /O and /U +# values from MD5; revisions 5 and 6 use SHA-256 and SHA-512 (Algorithm 2.B). +sonar.issue.ignore.multicriteria.pdf_standard_security_hash.ruleKey=rust:S4790 +sonar.issue.ignore.multicriteria.pdf_standard_security_hash.resourceKey=crates/pdf/src/crypt.rs +# odf: OpenDocument 4.16.6 and 4.16.3, a start key and a file checksum made with SHA-1, each used +# only where the package's manifest names it. +sonar.issue.ignore.multicriteria.odf_package_hash.ruleKey=rust:S4790 +sonar.issue.ignore.multicriteria.odf_package_hash.resourceKey=crates/odf/src/crypt.rs + +# githubactions:S7637 asks for every action to be pinned to a commit SHA. A workflow covered by +# .github/workflows/actions.lock runs the commit the lockfile records, so its tag refs are pinned +# and the lockfile covers the actions those actions use too. Sonar does not read lockfiles yet, so +# the rule flags the tag refs anyway: +# https://community.sonarsource.com/t/githubactions-s7637-false-positives-for-actions-pinned-through-native-actions-lock/190814 +sonar.issue.ignore.multicriteria.gha-lockfile.ruleKey=githubactions:S7637 +sonar.issue.ignore.multicriteria.gha-lockfile.resourceKey=.github/workflows/** diff --git a/vendor/README.craft-reader.md b/vendor/README.craft-reader.md index 3439657b5..8fc625fb9 100644 --- a/vendor/README.craft-reader.md +++ b/vendor/README.craft-reader.md @@ -444,3 +444,18 @@ a decoder's limit from damage). Not ported from those commits: the page-wide all refused-mask handling in `hayro-syntax` and `hayro-interpret` (0ed33990, 4aa732ea, e2464e14), which rest on the decoded-image cache of 558ffd7f (a performance change). Tests: those that came with the patches in `hayro-jbig2`, and PdfCraft's raster tests adapted in `hayro-jbig2/src/pdfcraft_tests.rs`. + +## Craft review note: the one direct `unsafe` + +`hayro-syntax/src/page.rs` holds the snapshot's only direct `unsafe` block: a +`core::mem::transmute` of `&XRef` to `&'static XRef` in the page cache. The vendored crates are +outside the workspace's `forbid(unsafe_code)`, so it compiles. Its safety argument is the field +order of the owning struct together with the `Arc<XRef>` outliving the borrow. Treat it as an +audited exception, not a pattern to copy: if the caching code is re-synced, re-read that +invariant and re-run the PDF tests that drop pages while a cache entry is live. + +`hayro-syntax` also has an `unsafe` cargo feature that pulls in `flate2`, `memchr` and +SIMD-capable decoders. `craft-pdf/read` depends on it with `default-features = false, +features = ["std"]`, so the feature stays off; a review of the resolved graph should keep it +that way. The CI check for that resolved feature set is a CI change under AGENTS.md rule 11 and +is proposed separately rather than in a fix pull request. diff --git a/vendor/hayro-syntax/src/pdf.rs b/vendor/hayro-syntax/src/pdf.rs index a13e3f669..88b881b7f 100644 --- a/vendor/hayro-syntax/src/pdf.rs +++ b/vendor/hayro-syntax/src/pdf.rs @@ -186,6 +186,16 @@ impl Pdf { pub fn metadata(&self) -> &Metadata { self.xref.metadata() } + + /// Return the document information dictionary resolved through the final trailer and xref. + pub fn info(&self) -> Option<crate::object::Dict<'_>> { + self.xref.info_id().and_then(|id| self.xref.get(id)) + } + + /// Whether the resolved trailer declares the document encrypted. + pub fn is_encrypted(&self) -> bool { + self.xref.is_encrypted() + } } fn find_version(data: &[u8]) -> Option<PdfVersion> { diff --git a/vendor/hayro-syntax/src/xref.rs b/vendor/hayro-syntax/src/xref.rs index 5fced8a88..0d2dadb64 100644 --- a/vendor/hayro-syntax/src/xref.rs +++ b/vendor/hayro-syntax/src/xref.rs @@ -449,6 +449,8 @@ impl XRef { let td = TrailerData { pages_ref: pages_ref.into(), root_ref: root_ref.into(), + info_ref: trailer_dict.get_ref(INFO).map(Into::into), + encrypted: trailer_dict.contains_key(ENCRYPT), version, }; @@ -461,6 +463,8 @@ impl XRef { let td = TrailerData { pages_ref: pages_ref.into(), root_ref, + info_ref: None, + encrypted: false, version: None, }; @@ -526,6 +530,16 @@ impl XRef { self.trailer_data().root_ref } + /// Return the document information dictionary reference from the resolved trailer, if any. + pub fn info_id(&self) -> Option<ObjectIdentifier> { + self.trailer_data().info_ref + } + + /// Whether the resolved trailer has an `/Encrypt` entry. + pub fn is_encrypted(&self) -> bool { + self.trailer_data().encrypted + } + /// Whether the PDF has optional content groups. pub fn has_optional_content_groups(&self) -> bool { match &self.0 { @@ -885,6 +899,8 @@ struct MapRepr { pub(crate) struct TrailerData { pub(crate) pages_ref: ObjectIdentifier, pub(crate) root_ref: ObjectIdentifier, + pub(crate) info_ref: Option<ObjectIdentifier>, + pub(crate) encrypted: bool, pub(crate) version: Option<PdfVersion>, } @@ -893,6 +909,8 @@ impl TrailerData { Self { pages_ref: ObjectIdentifier::new(0, 0), root_ref: ObjectIdentifier::new(0, 0), + info_ref: None, + encrypted: false, version: None, } } diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index 3226a38e0..3d61277ad 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -1,21 +1,25 @@ # Local linesweeper 0.5.0 copy This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and the -local patch listed below. `.cargo_vcs_info.json` names the commit it was packaged from, -`824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest -names, which is archived; its README says development moved off GitHub. +local patches listed below, to `src/sweep/sweep_line.rs` and `docs/sweep.typ`. `.cargo_vcs_info.json` +names the commit it was packaged from, `824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not +in the GitHub repository the manifest names, which is archived; its README says development moved off +GitHub. -Every file here except this one, `SOURCE.json` and the patched file below is byte for byte the file -in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download +Every file here except this one, `SOURCE.json` and the two patched files below is byte for byte the +file in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `upstream_repository` is null because no public repository this copy can name -holds `upstream_revision`. `local_patches` describes the local patch. +holds `upstream_revision`. `local_patches` describes each local patch. ## Local patches | File | Change | |---|---| | `src/sweep/sweep_line.rs` | The doc comment of `SweepLine::line_segment` says it can return a segment that has exited, which `segment_range` leaves out. Code comments label the change `Craft patch (exited slots)`. | +| `docs/sweep.typ` | The intersection scan to the left compares each segment with `alpha^(i+1)` instead of `alpha^i`. With `alpha^i`, its first pass compared `alpha^i` with itself, and the lemma after it is stated for `alpha^(i+1)`. | +| `docs/sweep.typ` | Two typos are corrected. "condi0.2tions" reads "conditions", and `q(i+i)` reads `q(i+1)`, the first index for which `q` is false. | +| `docs/sweep.typ` | The lemma for the intersection scan to the left asks for the ordering invariant on `(alpha^1, ..., alpha^(i+1))` and the crossing invariant on `(alpha^1, ..., alpha^i)`, which is how the bidirectional lemma uses it. The argument for the order invariant cites the crossing invariant instead of a "third invariant"; the document defines two. | `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 0536117b0..5525d0279 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -8,7 +8,10 @@ "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", "local_patches": [ - "In `src/sweep/sweep_line.rs`, the doc comment of `SweepLine::line_segment` says it can return a segment that has exited, which `segment_range` leaves out." + "In `src/sweep/sweep_line.rs`, the doc comment of `SweepLine::line_segment` says it can return a segment that has exited, which `segment_range` leaves out.", + "In `docs/sweep.typ`, the intersection scan to the left compares each segment with `alpha^(i+1)`, the segment the lemma after it is stated for, instead of `alpha^i`.", + "In `docs/sweep.typ`, the typo \"condi0.2tions\" reads \"conditions\", and `q(i+i)` reads `q(i+1)`, the first index for which `q` is false.", + "In `docs/sweep.typ`, the lemma for the intersection scan to the left asks for the ordering invariant on `(alpha^1, ..., alpha^(i+1))` and the crossing invariant on `(alpha^1, ..., alpha^i)`, as the bidirectional lemma uses it, and the argument for the order invariant cites the crossing invariant instead of a \"third invariant\"." ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, @@ -23,7 +26,7 @@ { "path": "benches/linebender_logo.rs", "source_sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3", "source_git_blob": null, "sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3" }, { "path": "benches/painted_dreams.rs", "source_sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf", "source_git_blob": null, "sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf" }, { "path": "benches/synthetic.rs", "source_sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810", "source_git_blob": null, "sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810" }, - { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3" }, + { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "c151c2c47032eca41914139b105177d10996b6ece9c93622aaeb31a371cfe17b" }, { "path": "examples/boolean_op.rs", "source_sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f", "source_git_blob": null, "sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f" }, { "path": "examples/bus.rs", "source_sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33", "source_git_blob": null, "sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33" }, { "path": "examples/curve_metrics.rs", "source_sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2", "source_git_blob": null, "sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2" }, diff --git a/vendor/linesweeper/docs/sweep.typ b/vendor/linesweeper/docs/sweep.typ index 0f83ac1c6..c77f6cdc6 100644 --- a/vendor/linesweeper/docs/sweep.typ +++ b/vendor/linesweeper/docs/sweep.typ @@ -221,7 +221,7 @@ The first observation is that the sweep line invariants are maintained as we inc to the next event: + For the order invariant, first note that there is an event whenever $y$ leaves the domain of a segment, so $y$ remains in all domains until the next event. Moreover, if at any $y' > y$ the ordering breaks, two line segments must have $epsilon$-crossed one another by $y'$. - The third invariant guarantees that there's an event before this happens, so by the contra-positive until an event happens the ordering + The crossing invariant guarantees that there's an event before this happens, so by the contra-positive until an event happens the ordering constraint is maintained. + The crossing invariant is maintained because the set of things to check (i.e. the set of line segments that $epsilon$-cross one another after $y$) only shrinks as $y$ increases. @@ -368,13 +368,13 @@ of the other one. #figure( pseudocode-list([ + *for* $j = i$ down to $1$ - + let $w^j$ be the smallest height of any event between $j$ and $i$ + + let $w^j$ be the smallest height of any event between $j$ and $i+1$ - + *if* $(alpha^j_(-,epsilon), alpha^i)$ cross by $w^j$ - + choose $z$ before the crossing, such that $alpha^j approx_(z,epsilon) alpha^i$ - + insert an intersection event for $(alpha^j, alpha^i)$ at $z$ + + *if* $(alpha^j_(-,epsilon), alpha^(i+1))$ cross by $w^j$ + + choose $z$ before the crossing, such that $alpha^j approx_(z,epsilon) alpha^(i+1)$ + + insert an intersection event for $(alpha^j, alpha^(i+1))$ at $z$ - + *if* $alpha^j_+ (z) <= alpha^i (z)$ for all $z in [y, w^j]$ + + *if* $alpha^j_+ (z) <= alpha^(i+1) (z)$ for all $z in [y, w^j]$ + *break* ]), caption: "Intersection scan to the left" @@ -383,8 +383,8 @@ of the other one. We'll skip the proof of the following lemma, because it's basically the same as the last one. #lemma[ -Suppose that $(alpha^1, ..., alpha^i)$ satisfy the ordering invariant -at $y$, and suppose also that $(alpha^1, ..., alpha^(i+1))$ +Suppose that $(alpha^1, ..., alpha^(i+1))$ satisfy the ordering invariant +at $y$, and suppose also that $(alpha^1, ..., alpha^i)$ satisfy the crossing invariant at $y$. After running an intersection scan to the left, $(alpha^1, ..., alpha^(i+1))$ satisfy a slightly stronger crossing invariant at $y$: for every $j <= i$, @@ -555,7 +555,7 @@ height. Note that because the sweep line changes at a discrete set of heights, at every important height $y$ we actually have two weakly-ordered sweep line: the "old" one from infinitesmally before $y$ height and the "new" one from $y$ onwards. Because everything is continuous and the weak ordering conditions are -closed, both the old and new sweep lines satisfy the weak ordering condi0.2tions +closed, both the old and new sweep lines satisfy the weak ordering conditions at $y$. The algorithm goes like this: at every important height we use @@ -623,7 +623,7 @@ Let's check that this insertion position is valid: for every $j <= i$ we have either $j <= i_-$ or $i_- < j <= i$. In the first case, we already observed that $alpha^j_-(y) <= beta(y)$; in the second case, $q(j)$ returned `true` and so $alpha^j_-(y) <= beta^j^+ (y)$. In either case, $alpha^j prec.tilde beta$. -On the other hand, $q(i+i)$ being `false` implies that $alpha^(i+1)_- (y) >= +On the other hand, $q(i+1)$ being `false` implies that $alpha^(i+1)_- (y) >= beta(y)$. This implies that for all $j >= i+1$, $alpha^j_+ (y) >= beta(y)$ and so $alpha^j succ.tilde_y beta$.