diff --git a/.cargo/config.toml b/.cargo/config.toml deleted file mode 100644 index 873f4f7aa..000000000 --- a/.cargo/config.toml +++ /dev/null @@ -1,2 +0,0 @@ -[lints] -cargo.unused_workspace_dependencies = "allow" diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 000000000..0bc679e47 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,61 @@ +# cargo-nextest (https://nexte.st) runs every test in its own process, in parallel across test +# binaries. Every leg of the Workspace gate uses it (.github/workflows/workspace.yml); local runs may +# keep `cargo test`. Nextest does not run doctests, so the gate also runs `cargo test --doc`. +# +# cargo nextest run --workspace --profile ci +# cargo test --workspace --doc +# +# Refuse an older nextest: CI installs exactly this version (GHSA-vc25-qg58-w57c is fixed in it). +nextest-version = "0.9.150" + +# Some tests share a resource that an in-process mutex keeps to one test at a time. With one +# process per test those mutexes no longer serialize anything, so these groups do it instead, one +# test at a time, as under `cargo test`. +[test-groups] +# craft-ui: `gpu_test_lock()` / `gpu_lock()`. Each renderer creates its own wgpu instance and +# device, and creating or destroying one while another test uses its device can crash. +gpu = { max-threads = 1 } +# craft-video h264_decode: `FIXTURE_GENERATION` keeps a second producer from replacing a fixture +# file another test is reading. +video-fixtures = { max-threads = 1 } +# craft-print: `PRINT_TICKET_PROVIDER` serializes the Windows PrintTicket provider, and the tests +# share the one test print queue the gate installs. +print = { max-threads = 1 } +# craft-video integration tests on Linux and macOS: the binaries generate and read the same fixture +# directories (see the `ci` overrides below). +video-integration = { max-threads = 1 } + +[[profile.default.overrides]] +filter = 'package(craft-ui) & (binary(visual_regression) | test(/^combo::tests::|selected_tab_erases_a_baseline_centered_on_its_bottom_edge/))' +test-group = 'gpu' + +[[profile.default.overrides]] +filter = 'package(craft-video) & binary(h264_decode)' +test-group = 'video-fixtures' + +[[profile.default.overrides]] +filter = 'package(craft-print)' +test-group = 'print' + +# The gate (`--profile ci`). Run every test and list all failures at the end, as `cargo test` +# reports a whole binary. Slow tests are named every 60 seconds; none is stopped for being slow, +# so a hang is still ended by the gate's own timeout, as before. +[profile.ci] +fail-fast = false +slow-timeout = { period = "60s" } +failure-output = "immediate-final" + + +# Linux and macOS (the resource audit in craft-libs#2058): every GPU consumer shares the one `gpu` +# slot, and the craft-video integration binaries share their fixture directories. Conservative on +# purpose: the in-process mutexes these tests rely on do not reach across nextest's processes. +# Windows keeps the default groups above, which its leg has passed with since it moved to nextest. +[[profile.ci.overrides]] +platform = 'cfg(unix)' +filter = 'package(craft-ui) | package(craft-keymap) | package(craft-update)' +test-group = 'gpu' + +[[profile.ci.overrides]] +platform = 'cfg(unix)' +filter = 'package(craft-video) & kind(test)' +test-group = 'video-integration' diff --git a/.gitattributes b/.gitattributes index a854bbdb9..0c35cf7c5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -14,3 +14,6 @@ crates/font-store/index/sources.json -text # The build fixture verifies these license files are copied byte-for-byte. crates/fonts-build/tests/fixture/craft-fonts/fonts/**/OFL.txt -text + +# DXF drawing goldens assert exact writer bytes, including LF on every platform. +crates/dxf/tests/data/drawing_*.dxf -text diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 000000000..5996d0d2f --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,160 @@ +# 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' + '.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' + '.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/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' + '.github/workflows/full-validation.yml': [] + '.github/workflows/house-rules.yml': [] + '.github/workflows/jpeg.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/keymap.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.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' + '.github/workflows/menu.yml': + - 'actions/checkout@v7.0.1' + - 'dtolnay/rust-toolchain@stable' + '.github/workflows/nightly.yml': [] + '.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/taiki-e-install-action@v2.87.32' + '.github/workflows/proof.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/sonarcloud.yml': [] + '.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' + '.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/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': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + - 'storytold/craft-common-actions@d65d611f0ef67eaa94039351be5afce61102dbb0' +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/taiki-e-install-action@v2.87.32': + ref: 'v2.87.32' + commit: 'sha1-76747d22a7567cc4438546a84f11bdf18e670ab8' + owner_id: 88700172 + repo_id: 1382753260 + 'storytold/craft-common-actions@d65d611f0ef67eaa94039351be5afce61102dbb0': + ref: 'main' + commit: 'sha1-d65d611f0ef67eaa94039351be5afce61102dbb0' + owner_id: 76897702 + repo_id: 1414429108 diff --git a/.github/workflows/ai-core.yml b/.github/workflows/ai-core.yml index cc8d738ac..2be123b23 100644 --- a/.github/workflows/ai-core.yml +++ b/.github/workflows/ai-core.yml @@ -12,33 +12,26 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: ai-core-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: ai-core-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not. jobs: ai-core: + name: AI model WASM timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + 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: rustfmt, clippy targets: wasm32-unknown-unknown - - run: cargo fmt --check - - run: cargo clippy -p craft-ai-core --all-targets --locked -- -D warnings - - run: cargo test -p craft-ai-core --locked # The model promises to compile for the web. - run: cargo check -p craft-ai-core --target wasm32-unknown-unknown --locked diff --git a/.github/workflows/atomic.yml b/.github/workflows/atomic.yml index 1a20fa679..23de7f9f4 100644 --- a/.github/workflows/atomic.yml +++ b/.github/workflows/atomic.yml @@ -12,45 +12,36 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: atomic-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: atomic-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this runs what it does not. jobs: atomic: + name: Atomic inherited Linux ACLs timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + 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: rustfmt, clippy - name: Install ACL tools - if: runner.os == 'Linux' run: sudo apt-get update && sudo apt-get install -y acl - - run: cargo fmt --check - - run: cargo clippy -p craft-atomic -p craft-settings --all-targets --locked -- -D warnings - - run: cargo test -p craft-atomic -p craft-settings --locked -- --nocapture - name: Check inherited Linux ACLs - if: runner.os == 'Linux' run: cargo test -p craft-atomic --locked -- --ignored --nocapture wasm: 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 0517efe6f..5fd971c62 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -11,36 +11,36 @@ on: permissions: contents: read +# A fraction of the fuzz-style cases, as in the Workspace gate; nightly.yml runs them in full. +env: + CRAFT_HOSTILE_DIVISOR: "8" + PROPTEST_CASES: "64" + concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-audio-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-audio-${{ github.ref }} + cancel-in-progress: true jobs: lint: timeout-minutes: 15 - name: Audio lint, feature sets, docs, WASM + # fmt, clippy with all features and the minimum Rust version run in the Workspace gate. + name: Audio feature sets, docs, WASM 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 + components: clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: craft-audio-lint - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-audio --check # Each feature on its own, so code that needs another feature fails here. - name: Clippy, each feature alone run: | @@ -49,7 +49,6 @@ jobs: cargo clippy -p craft-audio --all-targets --locked --no-default-features ${f:+--features "$f"} -- -D warnings echo "::endgroup::" done - - run: cargo clippy -p craft-audio --all-targets --locked --all-features -- -D warnings # missing_docs is a warning in the crate; -D warnings makes it (and broken links) fail here. - run: cargo doc -p craft-audio --all-features --no-deps --locked env: @@ -63,44 +62,21 @@ jobs: RUSTDOCFLAGS: "-D warnings" - run: cargo check -p craft-audio --all-features --locked --target wasm32-unknown-unknown - run: cargo check -p craft-audio --no-default-features --features lossless-encode --locked --target wasm32-unknown-unknown - msrv: - timeout-minutes: 10 - name: Audio on the minimum Rust version - runs-on: ubuntu-latest - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # 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 - with: - key: craft-audio-msrv - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo +1.95.0 check -p craft-audio -p craft-media --all-features --locked features: timeout-minutes: 10 name: Audio tests without symphonia and lossless-encode only 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 - with: - key: craft-audio-features - save-if: ${{ github.ref == 'refs/heads/main' }} - run: cargo test -p craft-audio --no-default-features --features lossless-encode --locked - run: cargo test -p craft-audio --no-default-features --features pcm-encode --locked --lib - run: cargo test -p craft-audio --no-default-features --features flac-encode --locked --lib @@ -113,20 +89,16 @@ 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 - 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..9220d8e09 100644 --- a/.github/workflows/cms.yml +++ b/.github/workflows/cms.yml @@ -11,16 +11,20 @@ on: permissions: contents: read +concurrency: + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: cms-${{ github.ref }} + cancel-in-progress: true + +# clippy and the debug tests run in the Workspace gate; this runs the release build of the tests. jobs: cms: 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 - - run: cargo clippy -p craft-cms --all-targets --all-features --locked -- -D warnings # Release: the FOGRA39 fit and ink-limit tests take about 35 s in debug and 4 s here. Tests that need # installed system profiles print "skipped:" when none are present. - run: cargo test -p craft-cms --all-features --release --locked -- --nocapture diff --git a/.github/workflows/crw.yml b/.github/workflows/crw.yml index 8fec98661..466b6c05d 100644 --- a/.github/workflows/crw.yml +++ b/.github/workflows/crw.yml @@ -12,61 +12,29 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-crw-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-crw-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not. jobs: - native: - timeout-minutes: 20 - name: CRW lint and tests (${{ matrix.os }}) - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, windows-latest] - runs-on: ${{ matrix.os }} - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7 - with: - persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 - with: - toolchain: stable - components: rustfmt, clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: craft-crw-${{ matrix.os }} - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-crw --check - - run: cargo clippy -p craft-crw --all-targets --locked -- -D warnings - - run: cargo test -p craft-crw --locked - wasm: timeout-minutes: 10 name: CRW WASM 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 - with: - key: craft-crw-wasm - save-if: ${{ github.ref == 'refs/heads/main' }} - run: cargo check -p craft-crw --locked --target wasm32-unknown-unknown samples: @@ -75,21 +43,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 - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # 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..23def9feb 100644 --- a/.github/workflows/dialogs.yml +++ b/.github/workflows/dialogs.yml @@ -12,10 +12,10 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: dialogs-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: dialogs-${{ github.ref }} + cancel-in-progress: true jobs: dialogs: @@ -23,20 +23,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: 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 # The macOS code is linted on Linux: it compiles for the target without the SDK. targets: aarch64-apple-darwin - - run: cargo clippy -p craft-dialogs --all-targets --locked -- -D warnings + # Native clippy and the tests run in the Workspace gate. - run: cargo clippy -p craft-dialogs --target aarch64-apple-darwin --locked -- -D warnings - - run: cargo test -p craft-dialogs --locked diff --git a/.github/workflows/doc.yml b/.github/workflows/doc.yml index a0c619c1e..627543381 100644 --- a/.github/workflows/doc.yml +++ b/.github/workflows/doc.yml @@ -12,36 +12,27 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: doc-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: doc-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not. jobs: doc: + name: Craft documents WASM timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + 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 - - run: cargo fmt --check - - run: cargo clippy -p craft-doc --all-targets --locked -- -D warnings - - run: cargo clippy -p craft-doc --all-targets --all-features --locked -- -D warnings - - run: cargo test -p craft-doc --locked -- --nocapture - - run: cargo test -p craft-doc --all-features --locked -- --nocapture - run: cargo check -p craft-doc --all-features --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/docpath.yml b/.github/workflows/docpath.yml deleted file mode 100644 index 571b65eca..000000000 --- a/.github/workflows/docpath.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Document paths - -on: - workflow_dispatch: - push: - branches: [main] - paths: ['crates/docpath/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docpath.yml'] - pull_request: - paths: ['crates/docpath/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docpath.yml'] - -permissions: - contents: read - -concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: docpath-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - docpath: - timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 - with: - toolchain: stable - components: rustfmt, clippy - - run: cargo fmt --check - - run: cargo clippy -p craft-docpath --all-targets --locked -- -D warnings - - run: cargo test -p craft-docpath --locked -- --nocapture diff --git a/.github/workflows/ecproj-format.yml b/.github/workflows/ecproj-format.yml index 16bab05c7..048c897b3 100644 --- a/.github/workflows/ecproj-format.yml +++ b/.github/workflows/ecproj-format.yml @@ -12,34 +12,27 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: ecproj-format-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: ecproj-format-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not. jobs: ecproj-format: + name: EffectCraft project format WASM timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + 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 - - run: cargo fmt --check - - run: cargo clippy -p craft-ecproj-format --all-targets --locked -- -D warnings - - run: cargo test -p craft-ecproj-format --locked -- --nocapture - run: cargo check -p craft-ecproj-format --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/font-store.yml b/.github/workflows/font-store.yml index f246f621a..e655697b3 100644 --- a/.github/workflows/font-store.yml +++ b/.github/workflows/font-store.yml @@ -12,36 +12,26 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: font-store-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: font-store-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not. jobs: font-store: + name: Font store WASM timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + 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: 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 targets: wasm32-unknown-unknown - - run: cargo fmt --check - - run: cargo clippy -p craft-font-store --all-targets --locked -- -D warnings - - run: cargo test -p craft-font-store --locked - - run: cargo clippy -p craft-font-catalog --all-targets --locked -- -D warnings - - run: cargo test -p craft-font-catalog --locked - name: Check the web build - if: runner.os == 'Linux' run: cargo check -p craft-font-store --target wasm32-unknown-unknown --locked diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index e19902e8c..12478d2c9 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -42,11 +42,10 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-formats-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-formats-${{ github.ref }} + cancel-in-progress: true jobs: check: @@ -68,44 +67,33 @@ jobs: - { crate: craft-tiff, features: "" } - { crate: craft-heif, features: "testdata" } - { crate: craft-cms, features: "" } - name: ${{ matrix.crate }} lint, tests, WASM + # fmt, clippy with default and with all features, and the tests run in the Workspace gate on + # every OS; this lints each feature alone and checks the web build. + name: ${{ matrix.crate }} feature sets, WASM 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 + components: clippy targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - with: - key: ${{ matrix.crate }} - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p "$CRATE" --check - env: - CRATE: ${{ matrix.crate }} - - name: Clippy, default features and each feature alone + - name: Clippy, each feature alone + if: matrix.features != '' env: CRATE: ${{ matrix.crate }} FEATURES: ${{ matrix.features }} run: | - cargo clippy -p "$CRATE" --all-targets --locked -- -D warnings for f in $FEATURES; do echo "::group::feature: $f" cargo clippy -p "$CRATE" --all-targets --locked --no-default-features --features "$f" -- -D warnings echo "::endgroup::" done - - run: cargo clippy -p "$CRATE" --all-targets --locked --all-features -- -D warnings - env: - CRATE: ${{ matrix.crate }} - - run: cargo test -p "$CRATE" --all-features --locked - env: - CRATE: ${{ matrix.crate }} - run: cargo check -p "$CRATE" --all-features --locked --target wasm32-unknown-unknown env: CRATE: ${{ matrix.crate }} diff --git a/.github/workflows/full-validation.yml b/.github/workflows/full-validation.yml new file mode 100644 index 000000000..85ad96f2f --- /dev/null +++ b/.github/workflows/full-validation.yml @@ -0,0 +1,64 @@ +name: Full validation + +# Add full-validation to a PR for uncapped validation of its merge ref. Keep the label across pushes. +# Fast Workspace checks are not substitutes for these six completed native/PDF gate checks. +on: + pull_request: + types: [opened, synchronize, reopened, labeled] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # An unrelated label event must not cancel an active full run. + group: full-validation-${{ github.event.action == 'labeled' && github.event.label.name != 'full-validation' && github.run_id || github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + native: + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-validation') && + (github.event.action != 'labeled' || github.event.label.name == 'full-validation')) + name: Full native + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest","windows-latest","macos-latest"]' + select-os: '[]' + timeout-minutes: 120 + tools: "" + packages: mesa-vulkan-drivers libvulkan1 + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + linux-env: WGPU_BACKEND=vulkan + windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1 + env: CRAFT_PRINT_REQUIRE_QUEUE=0 + setup-command: bash scripts/ci-test-inputs.sh + command: | + python scripts/test-full-validation.py + bash scripts/ci-full-validation.sh + + pdf-contracts: + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-validation') && + (github.event.action != 'labeled' || github.event.label.name == 'full-validation')) + name: Full PDF contracts + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest","windows-latest","macos-latest"]' + select-os: '[]' + timeout-minutes: 120 + tools: "" + craft-fonts-ref: "" + require-craft-fonts: false + env: RUSTFLAGS=--cfg craft_pdf_unicode_fixtures + setup-command: | + python scripts/test-fetch-pdf-test-fonts.py + python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" + echo "CRAFT_PDF_TEST_FONT_DIR=$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" + command: | + unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES + cargo clippy -p craft-pdf --all-targets --all-features --locked -- -D warnings + cargo test -p craft-pdf --all-features --locked + cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml deleted file mode 100644 index 5f717aeff..000000000 --- a/.github/workflows/i18n.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Translations - -on: - workflow_dispatch: - push: - branches: [main] - paths: ['crates/i18n/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/i18n.yml'] - pull_request: - paths: ['crates/i18n/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/i18n.yml'] - -permissions: - contents: read - -concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: i18n-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - i18n: - timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 - with: - toolchain: stable - components: rustfmt, clippy - - run: cargo fmt --check - - run: cargo clippy -p craft-i18n --all-targets --features collate --locked -- -D warnings - - run: cargo test -p craft-i18n --features collate --locked -- --nocapture diff --git a/.github/workflows/jpeg.yml b/.github/workflows/jpeg.yml index 900baf678..495af8b23 100644 --- a/.github/workflows/jpeg.yml +++ b/.github/workflows/jpeg.yml @@ -12,35 +12,28 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-jpeg-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-jpeg-${{ github.ref }} + cancel-in-progress: true jobs: check: - timeout-minutes: 10 - name: JPEG lint, tests, WASM + # Uncached: the wasm check builds its dependencies on every run (about 10 minutes with setup). + timeout-minutes: 20 + # fmt, clippy and the tests run in the Workspace gate on every OS. + name: JPEG WASM 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 - with: - key: craft-jpeg - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-jpeg --check - - run: cargo clippy -p craft-jpeg --all-targets --locked -- -D warnings - - run: cargo test -p craft-jpeg --locked - run: cargo check -p craft-jpeg --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index aba535265..bd4ef280a 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -12,43 +12,39 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: keymap-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: keymap-${{ github.ref }} + cancel-in-progress: true jobs: linux: timeout-minutes: 15 - name: Keymap (Linux) + # fmt, and clippy and the tests with default and with all features, run in the Workspace gate + # on every OS; this runs the feature subsets. + name: Keymap feature sets runs-on: ubuntu-latest env: 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 - with: - key: craft-keymap-linux - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-keymap --check + components: clippy - run: cargo clippy -p craft-keymap --all-targets --no-default-features --locked -- -D warnings # `snapshot` covers `ui` and `egui` and compiles the dialog screenshots, which need a GPU # to run, so the test steps leave them out. @@ -58,58 +54,20 @@ jobs: run: cargo test -p craft-keymap --no-default-features --lib --tests --locked - name: Test egui dispatch and the shortcuts dialog run: cargo test -p craft-keymap --features ui --locked - native: - timeout-minutes: 15 - name: Keymap (${{ matrix.os }}) - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["macos-latest","windows-latest"]') || fromJSON('["windows-latest"]') }} - runs-on: ${{ matrix.os }} - env: - CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7 - with: - persist-credentials: false - - name: Checkout test fonts - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # 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 - with: - toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: craft-keymap-${{ matrix.os }} - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo test -p craft-keymap --features ui --locked wasm: timeout-minutes: 10 name: Keymap WASM 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 - with: - key: craft-keymap-wasm - save-if: ${{ github.ref == 'refs/heads/main' }} - run: cargo check -p craft-keymap --features ui --locked --target wasm32-unknown-unknown 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..1b5afaebd 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -11,43 +11,40 @@ on: permissions: contents: read +# A fraction of the fuzz-style cases, as in the Workspace gate; nightly.yml runs them in full. +env: + CRAFT_HOSTILE_DIVISOR: "8" + PROPTEST_CASES: "64" + concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-media-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-media-${{ github.ref }} + cancel-in-progress: true jobs: lint: timeout-minutes: 10 - name: Media lint, feature sets, WASM + # fmt, and clippy with default and with all features, run in the Workspace gate on every OS. + name: Media feature sets, WASM 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 + components: clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: craft-media-lint - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-media --check - run: cargo clippy -p craft-media --all-targets --locked --no-default-features -- -D warnings - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features bitstream -- -D warnings - - run: cargo clippy -p craft-media --all-targets --locked -- -D warnings - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features matroska -- -D warnings - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features ogg -- -D warnings - - run: cargo clippy -p craft-media --all-targets --locked --all-features -- -D warnings - - run: cargo clippy -p craft-media-testkit --all-targets --locked -- -D warnings - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features serde -- -D warnings - run: cargo check -p craft-media --all-features --locked --target wasm32-unknown-unknown test: @@ -56,19 +53,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: 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 - with: - key: craft-media-test - save-if: ${{ github.ref == 'refs/heads/main' }} - name: Build tests while installing ffmpeg run: | # The man-db index rebuild after dpkg is slow on hosted runners. diff --git a/.github/workflows/menu.yml b/.github/workflows/menu.yml index 6d0e082cb..b12c8bcc6 100644 --- a/.github/workflows/menu.yml +++ b/.github/workflows/menu.yml @@ -18,22 +18,17 @@ concurrency: jobs: linux: timeout-minutes: 15 - name: Menu (Linux) + # fmt, native clippy and the tests run in the Workspace gate on every OS. + name: Menu macOS and WASM lint 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 + components: clippy targets: aarch64-apple-darwin, wasm32-unknown-unknown - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - with: - key: craft-menu-linux - - run: cargo fmt -p craft-menu --check - - run: cargo clippy -p craft-menu --all-targets --locked -- -D warnings # The macOS backend type-checks from Linux; it needs no linker or SDK. - run: cargo clippy -p craft-menu --lib --locked --target aarch64-apple-darwin -- -D warnings - run: cargo clippy -p craft-menu --lib --locked --target wasm32-unknown-unknown -- -D warnings - - run: cargo test -p craft-menu --locked diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 000000000..ed9d36127 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: Nightly full tests + +# The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep +# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The +# rest of the workspace's tests run with them, on Linux, with the gate's setup. +on: + schedule: + - cron: "37 2 * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: nightly-${{ github.ref }} + cancel-in-progress: false + +jobs: + full: + name: Full tests + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest"]' + timeout-minutes: 120 + tools: cargo-nextest@0.9.150 + packages: mesa-vulkan-drivers libvulkan1 + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + linux-env: WGPU_BACKEND=vulkan + env: CRAFT_PRINT_REQUIRE_QUEUE=0 + setup-command: bash scripts/ci-test-inputs.sh + cache-paths: .test-inputs/photocraft/corpus + cache-key: photocraft-corpus + cache-key-files: scripts/ci-test-inputs.sh + command: cargo nextest run --workspace --all-features --locked --profile ci diff --git a/.github/workflows/pcraft-format.yml b/.github/workflows/pcraft-format.yml index 177bb4593..0e4feabc9 100644 --- a/.github/workflows/pcraft-format.yml +++ b/.github/workflows/pcraft-format.yml @@ -12,34 +12,28 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: pcraft-format-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: pcraft-format-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS, and its msrv job checks the +# workspace on 1.95; this checks the web build on 1.95. jobs: pcraft-format: + name: PhotoCraft format WASM timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + 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 - - run: cargo fmt --check - - run: cargo clippy -p craft-pcraft-format --all-targets --locked -- -D warnings - - run: cargo test -p craft-pcraft-format --locked -- --nocapture - run: cargo check -p craft-pcraft-format --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/pdf.yml b/.github/workflows/pdf.yml index a494d085c..7b7397757 100644 --- a/.github/workflows/pdf.yml +++ b/.github/workflows/pdf.yml @@ -11,39 +11,35 @@ on: permissions: contents: read +# A fraction of the proptest cases, as in the Workspace gate; nightly.yml runs them in full. +env: + PROPTEST_CASES: "64" + concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-pdf-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-pdf-${{ github.ref }} + cancel-in-progress: true jobs: native: - name: PDF (${{ matrix.os }}) - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + # fmt, clippy and the tests run in the Workspace gate on every OS, with the licensed fonts and + # the plate tests; this runs the tests behind craft_pdf_unicode_fixtures and the read-only + # contract, which is its own workspace. + name: PDF Unicode fixtures and read-only contract + runs-on: ubuntu-latest env: 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 - 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 @@ -52,26 +48,20 @@ jobs: python scripts/test-fetch-pdf-test-fonts.py python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" echo "CRAFT_PDF_TEST_FONT_DIR=$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" - - run: cargo fmt --check - - run: cargo clippy -p craft-pdf --all-targets --all-features --locked -- -D warnings - - run: cargo test -p craft-pdf --all-features --locked + - run: cargo test -p craft-pdf --all-features --locked --test unicode_writing --test upstream_compatibility --test upstream_reading - run: cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked backends: name: PDF vendored contracts 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 - with: - key: craft-pdf-backends - save-if: ${{ github.ref == 'refs/heads/main' }} - run: bash scripts/test-pdf-backends.sh wasm: name: PDF WASM runtime @@ -81,19 +71,15 @@ 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 - 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,37 +97,9 @@ 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 - run: cargo test -p craft-pdf --all-features --locked --target wasm32-unknown-unknown - run: cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked --target wasm32-unknown-unknown - plate-test: - name: Plate tests and craft-prepress - runs-on: ubuntu-latest - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 - with: - toolchain: stable - components: clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: craft-plate-test - save-if: ${{ github.ref == 'refs/heads/main' }} - - uses: actions/setup-python@v7 - with: - python-version: "3.12" - - name: Provision licensed PDF test fonts - shell: bash - run: | - python scripts/test-fetch-pdf-test-fonts.py - python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" - echo "CRAFT_PDF_TEST_FONT_DIR=$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" - - run: cargo clippy -p craft-plate-test -p craft-prepress --all-targets --all-features --locked -- -D warnings - - run: cargo test -p craft-plate-test -p craft-prepress --all-features --locked diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml deleted file mode 100644 index 3838e6c42..000000000 --- a/.github/workflows/print.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Print spooler -on: - workflow_dispatch: - push: - branches: [main] - paths: ['crates/print/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/print.yml'] - pull_request: - paths: ['crates/print/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/print.yml'] -permissions: - contents: read -concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: print-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} -jobs: - print: - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 - with: - toolchain: stable - components: rustfmt, clippy - - run: cargo fmt --check - - run: cargo clippy -p craft-print --all-targets -- -D warnings - - name: Prepare the Windows test driver - if: runner.os == 'Windows' - shell: powershell - run: | - Start-Service Spooler - Add-PrinterDriver -Name 'Generic / Text Only' - - run: cargo test -p craft-print --locked -- --nocapture - timeout-minutes: 10 - env: - CRAFT_PRINT_REQUIRE_QUEUE: ${{ runner.os == 'Windows' && '1' || '0' }} diff --git a/.github/workflows/proof.yml b/.github/workflows/proof.yml index 0035b1c04..ea5edb8a5 100644 --- a/.github/workflows/proof.yml +++ b/.github/workflows/proof.yml @@ -12,49 +12,41 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: craft-proof-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: craft-proof-${{ github.ref }} + cancel-in-progress: true jobs: check: timeout-minutes: 20 - name: Proofing lint, tests with and without Language data, WASM + # fmt, and clippy and the tests without Language data, run in the Workspace gate on every OS. + name: Proofing with Language data, WASM 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 + components: clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: craft-proof - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-proof --check - - name: Without Language data (a fork, docs.rs, offline) - run: | - cargo clippy -p craft-proof --all-targets --locked -- -D warnings - cargo test -p craft-proof --locked - cargo check -p craft-proof --locked --target wasm32-unknown-unknown + - name: The web build without Language data (a fork, docs.rs, offline) + run: cargo check -p craft-proof --locked --target wasm32-unknown-unknown - name: A release without Language data fails run: | if CRAFT_I18N_REQUIRED=1 cargo check -p craft-proof --locked 2>build.log; then diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 654fe4c02..c03a3a076 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -20,8 +20,11 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main with: pdf-test-fonts: true + # The instrumented build runs without a dependency cache: its 1.2 GB entry does not fit the + # repository's 10 GB cache budget beside the Workspace gate's. It runs on main only. + build-cache: false # The codec and format code behind features that are off by default. Without these the # coverage build never compiles it, and new code there reads as untested. cargo-features: >- - craft-video/dnx,craft-video/vp8,craft-video/prores,craft-video/h264,craft-video/hevc,craft-video/vp9,craft-video/av1,craft-video/threads,craft-audio/decode,craft-audio/encode,craft-audio/peaks,craft-audio/rayon,craft-audio/serde,craft-media/matroska,craft-media/ogg,craft-media/bitstream,craft-media/serde,craft-mesh/stl,craft-mesh/obj,craft-mesh/ply,craft-mesh/gltf,craft-metafile/write + craft-image-codecs/avif,craft-image-codecs/avif-decode,craft-video/dnx,craft-video/vp8,craft-video/prores,craft-video/h264,craft-video/hevc,craft-video/vp9,craft-video/av1,craft-video/threads,craft-audio/decode,craft-audio/encode,craft-audio/peaks,craft-audio/rayon,craft-audio/serde,craft-media/matroska,craft-media/ogg,craft-media/bitstream,craft-media/serde,craft-mesh/stl,craft-mesh/obj,craft-mesh/ply,craft-mesh/gltf,craft-metafile/write,craft-image-codecs/sgi,craft-image-codecs/sunraster,craft-jsonrpc/async-lines secrets: inherit diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml deleted file mode 100644 index 0892f5a2c..000000000 --- a/.github/workflows/ui.yml +++ /dev/null @@ -1,74 +0,0 @@ -name: Shared UI - -on: - push: - branches: [main] - paths: ["crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/ui.yml"] - pull_request: - paths: ["crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/ui.yml"] - workflow_dispatch: - -permissions: - contents: read - -concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-ui-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - native: - timeout-minutes: 30 - name: UI (${{ matrix.os }}) - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7 - - 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 - with: - toolchain: stable - components: rustfmt, clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: craft-ui - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt --check - - run: cargo clippy -p craft-ui --all-targets --locked -- -D warnings - - run: cargo clippy -p craft-ui --all-targets --all-features --locked -- -D warnings - - run: cargo test -p craft-ui --locked - - run: cargo test -p craft-ui --all-features --locked - wasm: - timeout-minutes: 15 - name: UI WASM - runs-on: ubuntu-latest - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 - with: - toolchain: stable - targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: craft-ui-wasm - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo check -p craft-ui --all-features --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index f9c8e1498..96ab4d6ad 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -12,37 +12,31 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: update-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: update-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests with default and with all features run in the Workspace gate on every +# OS; this runs the egui feature alone. jobs: update: + name: Update with egui alone timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + 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: # 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 - - run: cargo fmt --check - # Default (no egui) and the egui feature both build and lint cleanly. - - run: cargo clippy -p craft-update --all-targets --locked -- -D warnings + components: clippy - run: cargo clippy -p craft-update --all-targets --locked --features egui -- -D warnings - - run: cargo test -p craft-update --locked -- --nocapture - run: cargo test -p craft-update --locked --features egui -- --nocapture diff --git a/.github/workflows/vectorcraft-format.yml b/.github/workflows/vectorcraft-format.yml index b2b20463a..cd66615a5 100644 --- a/.github/workflows/vectorcraft-format.yml +++ b/.github/workflows/vectorcraft-format.yml @@ -12,34 +12,28 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: vectorcraft-format-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: vectorcraft-format-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS, and its msrv job checks the +# workspace on 1.95; this checks the web build on 1.95. jobs: vectorcraft-format: + name: VectorCraft format WASM timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + 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 - - run: cargo fmt --check - - run: cargo clippy -p craft-vectorcraft-format --all-targets --locked -- -D warnings - - run: cargo test -p craft-vectorcraft-format --locked -- --nocapture - run: cargo check -p craft-vectorcraft-format --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index ec1c16eda..20afe0d70 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -11,6 +11,11 @@ on: permissions: contents: read +# A fraction of the fuzz-style cases, as in the Workspace gate; nightly.yml runs them in full. +env: + CRAFT_HOSTILE_DIVISOR: "8" + PROPTEST_CASES: "64" + concurrency: group: shared-video-${{ github.ref }} cancel-in-progress: true @@ -18,25 +23,22 @@ concurrency: jobs: lint: timeout-minutes: 20 - name: Video lint, feature sets, docs, WASM + # fmt and clippy with all features run in the Workspace gate on every OS. + name: Video feature sets, docs, WASM 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 + components: clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: craft-video-lint - - run: cargo fmt -p craft-video --check # Each feature on its own, so code that needs another feature fails here. - name: Clippy, each feature alone run: | @@ -45,35 +47,27 @@ jobs: cargo clippy -p craft-video --all-targets --locked --no-default-features ${f:+--features "$f"} -- -D warnings echo "::endgroup::" done - - run: cargo clippy -p craft-video --all-targets --locked --all-features -- -D warnings - run: cargo doc -p craft-video --all-features --no-deps --locked env: RUSTDOCFLAGS: "-D warnings" - run: cargo check -p craft-video --all-features --locked --target wasm32-unknown-unknown test: timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, windows-latest] - runs-on: ${{ matrix.os }} - name: Video tests (${{ matrix.os }}) + # The Workspace gate runs these tests on every OS without ffmpeg; this runs them with it. + runs-on: ubuntu-latest + name: Video tests with ffmpeg 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 - with: - key: craft-video-${{ matrix.os }} - - name: Install ffmpeg (Linux) - if: runner.os == 'Linux' + - name: Install ffmpeg run: | sudo rm -f /var/lib/man-db/auto-update sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends ffmpeg diff --git a/.github/workflows/web-api.yml b/.github/workflows/web-api.yml index 2460fb569..f0f8e22da 100644 --- a/.github/workflows/web-api.yml +++ b/.github/workflows/web-api.yml @@ -12,10 +12,10 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: web-api-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: web-api-${{ github.ref }} + cancel-in-progress: true jobs: web-api: @@ -26,16 +26,16 @@ 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 + components: clippy targets: wasm32-unknown-unknown - name: Read the wasm-bindgen version from Cargo.lock id: wasm-bindgen @@ -46,12 +46,10 @@ 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 - - run: cargo fmt --check - - run: cargo clippy -p craft-web-api --all-targets --locked -- -D warnings + # fmt, native clippy and the native tests run in the Workspace gate. - run: cargo clippy -p craft-web-api --all-targets --locked --target wasm32-unknown-unknown -- -D warnings - - run: cargo test -p craft-web-api --locked - run: cargo test -p craft-web-api --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/web-host.yml b/.github/workflows/web-host.yml index b780ee76b..dc0254850 100644 --- a/.github/workflows/web-host.yml +++ b/.github/workflows/web-host.yml @@ -12,40 +12,33 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-web-host-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-web-host-${{ github.ref }} + cancel-in-progress: true jobs: check: timeout-minutes: 20 - name: Web host lint, tests, WASM tests + # fmt, native clippy and the native tests run in the Workspace gate. + name: Web host WASM lint and tests runs-on: ubuntu-latest env: 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 + components: clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: craft-web-host - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-web-host --check - - run: cargo clippy -p craft-web-host --all-targets --locked -- -D warnings - run: cargo clippy -p craft-web-host --all-targets --locked --target wasm32-unknown-unknown -- -D warnings - - run: cargo test -p craft-web-host --locked - name: Read the wasm-bindgen version from Cargo.lock id: wasm-bindgen shell: bash @@ -55,7 +48,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..c13b1ac3f 100644 --- a/.github/workflows/window.yml +++ b/.github/workflows/window.yml @@ -12,39 +12,33 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: window-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: window-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests with default and with all features (egui and restore together) run in +# the Workspace gate on every OS; this runs each feature alone. jobs: window: + name: Window with each feature alone timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + 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: rustfmt, clippy - - run: cargo fmt --check - # Default (no egui) and the egui feature both build and lint cleanly. - - run: cargo clippy -p craft-window --all-targets --locked -- -D warnings + components: clippy - run: cargo clippy -p craft-window --all-targets --locked --features egui -- -D warnings - - run: cargo test -p craft-window --locked -- --nocapture - run: cargo test -p craft-window --locked --features egui -- --nocapture - run: cargo clippy -p craft-window --all-targets --locked --features restore -- -D warnings - - run: cargo test -p craft-window --locked --features restore,egui -- --nocapture + - run: cargo test -p craft-window --locked --features restore -- --nocapture diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index a7a3bb587..e13d290a6 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -6,56 +6,194 @@ on: tags: ["v*"] pull_request: workflow_dispatch: + # A full run on main every 6 hours that is never cancelled, so the caches are saved while pushes + # to main cancel each other. The midnight run builds the Linux leg from source (`native`). + schedule: + - cron: "17 0 * * *" + - cron: "17 6,12,18 * * *" permissions: contents: read +concurrency: + # A pull request, and main, each have one group, so a newer push cancels the run it supersedes; + # the newest push's run still tests everything before it. Every other run (a release tag, a + # manual run, the scheduled run) gets a group of its own and is neither cancelled nor replaced + # while queued: a release run always finishes, and the scheduled run saves the caches. + group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }} + jobs: + # Whether this run needs the macOS and Windows legs. On a pull request they run only when it can + # change platform behaviour: a crate with platform cfg code or one that depends on it, the build + # setup, or a file outside the crates (craft-common-actions' select-platforms). The full-ci label + # runs them anyway from the next push or manual run; every other event runs them. + platforms: + name: select platforms + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + platform: ${{ steps.select.outputs.platform }} + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + # The merge commit and its first parent. + - uses: actions/checkout@v7.0.1 + if: github.event_name == 'pull_request' + with: + persist-credentials: false + fetch-depth: 2 + - id: select + uses: storytold/craft-common-actions/actions/select-platforms@d65d611f0ef67eaa94039351be5afce61102dbb0 + with: + os: '["ubuntu-latest","windows-latest","macos-latest"]' + select-os: '["windows-latest","macos-latest"]' + label: full-ci + + # The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each + # main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo + # rebuilds only the crates a change reaches. `cache-prune` keeps the newest entry. The midnight + # scheduled run builds from source (`cold-build`) and starts the entry afresh. The macOS and + # Windows legs keep a dependency-only entry: their workspace crates would not fit the 10 GB cache + # budget beside Linux's. The lint legs keep no cache (`lint-cache: false`) for the same reason; a + # cold lint leg is still shorter than its gate leg. native: name: Workspace uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: - os: '["ubuntu-latest","windows-latest","macos-latest"]' - timeout-minutes: 120 - tools: "" + os: '["ubuntu-latest"]' + cache-workspace-crates: true + cold-build: ${{ github.event.schedule == '17 0 * * *' }} + lint-cache: false + timeout-minutes: &timeout 120 + # Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml). + tools: &tools cargo-nextest@0.9.150 packages: mesa-vulkan-drivers libvulkan1 - craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + craft-fonts-ref: &craft-fonts b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan - windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1 - env: CRAFT_PRINT_REQUIRE_QUEUE=0 - setup-command: | - set -euo pipefail - corpus_fetcher=.test-inputs/photocraft - mkdir -p "$corpus_fetcher" - git -C "$corpus_fetcher" init - git -C "$corpus_fetcher" remote add origin https://github.com/storytold/PhotoCraft.git - git -C "$corpus_fetcher" fetch --quiet --depth=1 origin 74330157cb601573ae4523a95bb9132822fc3918 - git -C "$corpus_fetcher" checkout --quiet --detach FETCH_HEAD - (cd "$corpus_fetcher" && cargo xtask corpus --psd --psd-tools --atn --exr --heif --pngsuite) - mkdir -p corpus - cp -a "$corpus_fetcher/corpus/." corpus/ - python scripts/test-fetch-pdf-test-fonts.py - python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" - 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: | - cargo fmt --check + # Test binaries without debug info or symbols: about a third of the size, and a panic still + # names its file and line. + dev-strip: true + # The fuzz-style tests run a fraction of their cases here: every hostile-input hammer and + # sweep 1/8 (craft-testkit's CRAFT_HOSTILE_DIVISOR), every proptest without its own case + # count 64 cases instead of 256. nightly.yml runs them all in full. + env: &env | + CRAFT_PRINT_REQUIRE_QUEUE=0 + CRAFT_HOSTILE_DIVISOR=8 + PROPTEST_CASES=64 + setup-command: &setup bash scripts/ci-test-inputs.sh + # The PhotoCraft corpora, keyed on the script that pins them: a hit skips the PhotoCraft + # checkout and its xtask build (1:51 on Windows). + cache-paths: &cache-paths .test-inputs/photocraft/corpus + cache-key: &cache-key photocraft-corpus + cache-key-files: &cache-key-files scripts/ci-test-inputs.sh + # A `lint ()` leg beside each `gate ()` leg, so clippy is off the tests' critical path. + lint-command: &lint | + if [ "$RUNNER_OS" = Linux ]; then + python3 scripts/test-workspace-concurrency.py + python3 scripts/test-workspace-tests.py + fi + # One rustfmt call gets every source root of the workspace, which is longer than + # Windows allows for a command line (os error 206). rustfmt's result is the same on + # every system, so the Linux and macOS legs check it. + if [ "$RUNNER_OS" != Windows ]; then + cargo fmt --check + fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - cargo test --workspace --locked - cargo test --workspace --all-features --locked + command: &command | + # The tests run once, with every feature, in parallel across test binaries; nextest skips + # doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose + # tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's + # first clippy run; the last command runs the crates whose tests check behaviour with a + # feature off, which an all-features build cannot reach. + cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests + cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench + cargo test --workspace --doc --all-features --locked + cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests + + # The macOS and Windows legs, when `platforms` says this run needs them, with the Linux leg's + # inputs. + native-platforms: + name: Workspace + needs: platforms + if: needs.platforms.outputs.platform == 'true' + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["windows-latest","macos-latest"]' + lint-cache: false + timeout-minutes: *timeout + tools: *tools + craft-fonts-ref: *craft-fonts + dev-strip: true + # No debuginfo on Windows: writing PDBs for every test binary is a large part of its link + # time. A panic still names its file and line; only backtrace frames lose theirs, and the + # Linux and macOS legs keep line tables. + windows-env: | + CRAFT_PRINT_REQUIRE_QUEUE=1 + CARGO_PROFILE_DEV_DEBUG=0 + env: *env + setup-command: *setup + cache-paths: *cache-paths + cache-key: *cache-key + cache-key-files: *cache-key-files + lint-command: *lint + command: *command windows-command: | powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' - cargo fmt --check - cargo clippy --workspace --all-targets --locked -- -D warnings - cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - cargo test --workspace --locked - cargo test --workspace --all-features --locked + cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests + cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench + cargo test --workspace --doc --all-features --locked + cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests + + # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), and + # every run restores only the newest. This deletes the older ones as soon as the Linux leg is + # done, instead of leaving them to the 10 GB budget's eviction, which would evict other entries + # too. The only job with `actions: write`; it checks out and runs nothing from the repository. + cache-prune: + name: cache prune + needs: native + if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - name: Delete all but the newest rolling entry of each job and runner + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + # `-rust---crates-----...`, newest first. + gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \ + --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" + declare -A kept + while read -r id key; do + [[ "$key" =~ ^.+-rust-[0-9a-f]{64}-(.+-crates-[A-Za-z_]+-[a-z0-9]+)-[0-9]+-[0-9]+- ]] || continue + entry=${BASH_REMATCH[1]} + if [ -n "${kept[$entry]:-}" ]; then + echo "delete $key" + gh cache delete "$id" --repo "$REPO" + else + kept[$entry]=1 + echo "keep $key" + fi + done < "$RUNNER_TEMP/caches" msrv: name: Rust 1.95 uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: + # Its own dependency-cache entry: the calls in this file share one job id, so without a name + # they would write the same key. + cache-name: msrv os: '["ubuntu-latest"]' toolchain: 1.95.0 targets: "" @@ -70,6 +208,7 @@ jobs: name: UI and settings WASM uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: + cache-name: wasm os: '["ubuntu-latest"]' targets: wasm32-unknown-unknown tools: "" diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 32bae195d..5805271e0 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -6,9 +6,12 @@ author, source and license. Library code and original assets are under the repos | File | Author | Source | License | |---|---|---|---| +| `licenses/jpeg-encoder-0.6.1/`, `crates/image-codecs/NOTICE` | jpeg-encoder contributors and the IJG, libjpeg-turbo and SIMD authors named in the retained notices | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1), used unmodified; source checksums in `SOURCE.json` | (MIT OR Apache-2.0) AND IJG | +| `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/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 | | `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | | `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | | `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | @@ -88,9 +91,88 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso | `crates/psd/tests/fixtures/atn/*.atn` (seven synthetic action sets, encoded field by field; `crates/psd/tests/fixtures/atn/README.md`) | PhotoCraft contributors | [PhotoCraft `crates/psd/tests/fixtures/atn`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/psd/tests/fixtures/atn) | MIT OR Apache-2.0 | | `crates/lottie/tests/fixtures/` | EffectCraft contributors (original work: four hand-written Lottie JSON documents, written from the public Lottie format description; not exported from any Adobe product or third-party file) | [EffectCraft `crates/lottie/tests/fixtures`](https://github.com/storytold/effectcraft/tree/e18f48fb/crates/lottie/tests/fixtures) | MIT OR Apache-2.0 | | `crates/pkcs7/tests/data/` | PdfCraft contributors (original work: throw-away test keys and certificates made with OpenSSL 3 for these tests, as seven PKCS #12 files with the password `test` and two PEM certificates; they protect nothing; commands in `crates/pkcs7/tests/data/README.md`) | [PdfCraft `crates/sign/tests/data`](https://github.com/storytold/pdfcraft/tree/1d7a9f9f/crates/sign/tests/data) | MIT OR Apache-2.0 | -| `crates/affinity/tests/support/corpus.tsv`, `crates/affinity/tests/support/affinity3-signatures.txt` (manifest and measured signatures only; the 51 documents are not bundled, `scripts/fetch-affinity-corpus.sh` downloads them outside the checkout) | The authors of each document: samuel-etver (vector-art), Seth A. Robinson (Patchy fixtures), Nick Beeuwsaert (AFDesignLoad), Jeremy Cantu (Branding), eviltwo (AssetStoreTemplate), Square (leakcanary) | each file's pinned upstream URL and SHA-256 in the manifest; list carried over from [VectorCraft `xtask/src/affinity_corpus.rs`](https://github.com/storytold/vectorcraft/blob/6e873b806c9d5b3f2b55f651df57bd97933b579a/xtask/src/affinity_corpus.rs) | CC0-1.0, MIT or Apache-2.0 (per file, in the manifest) | +| `crates/affinity/tests/support/corpus.tsv`, `crates/affinity/tests/support/affinity3-signatures.txt` (manifest and measured signatures only; the 113 files, 90 of them documents, are not bundled, `scripts/fetch-affinity-corpus.sh` downloads them outside the checkout) | The authors of each document: samuel-etver (vector-art), satoshoe-dev (affinity-samples), Seth A. Robinson (Patchy fixtures), Nick Beeuwsaert (AFDesignLoad), Jeremy Cantu (Branding), eviltwo (AssetStoreTemplate), Square (leakcanary) | each file's pinned upstream URL and SHA-256 in the manifest; every name from [VectorCraft `xtask/src/affinity_corpus.rs`](https://github.com/storytold/vectorcraft/blob/bada8e17103db9917de44e40a1cead5a7fc71c3c/xtask/src/affinity_corpus.rs) and [PhotoCraft `xtask/affinity-corpus.sha256`](https://github.com/storytold/photocraft/blob/629751503165118d5fec5f70e64fe2d6592f7b53/xtask/affinity-corpus.sha256) | CC0-1.0, MIT or Apache-2.0 (per file, in the manifest) | | `crates/raw/docs/coverage/adobe-cameras.tsv` | Facts (maker, model, extension, profile, minimum Camera Raw version) parsed by LightCraft contributors from Adobe's published list | [Adobe Camera Raw supported cameras](https://helpx.adobe.com/camera-raw/desktop/dng-and-file-formats/camera-raw-plug-supported-cameras.html), Wayback capture 20261003133011; moved from [LightCraft `docs/raw`](https://github.com/storytold/lightcraft/tree/5ff567a4a2e067bef1b6bce152c11e7f727ccbaf/docs/raw) | Facts, not copyrightable expression; the file is MIT OR Apache-2.0 | | `crates/raw/docs/coverage/{coverage,coverage-sweep,evidence,usage-weights}.tsv`, `coverage.py` | LightCraft contributors | [LightCraft `docs/raw`](https://github.com/storytold/lightcraft/tree/5ff567a4a2e067bef1b6bce152c11e7f727ccbaf/docs/raw) | MIT OR Apache-2.0 | | `crates/raw/docs/raf-corpus.sha256` (hashes only; the files are not bundled) | The photographers who contributed each file to raw.pixls.us | [raw.pixls.us](https://raw.pixls.us/) | CC0-1.0 | | `crates/drawingml/src/preset_text.txt` | DeckCraft contributors (Nikita Rakitin); generated by `crates/drawingml/tests/fixtures/make_preset_guides.py` from the guide formulas of ECMA-376 Part 1 `presetShapeDefinitions.xml` | [storytold/deckcraft#650](https://github.com/storytold/deckcraft/pull/650) | MIT OR Apache-2.0 (the formulas are the format's definition in ECMA-376) | | `crates/drawingml/tests/fixtures/preset_table.txt` | DeckCraft contributors (Nikita Rakitin); generated by `crates/drawingml/tests/fixtures/make_preset_table.py` from ECMA-376 Part 1 `presetShapeDefinitions.xml` | [storytold/deckcraft#650](https://github.com/storytold/deckcraft/pull/650) | MIT OR Apache-2.0 (the formulas are the format's definition in ECMA-376) | + +## Binary Apple property lists + +`crates/plist` is extracted from `storytold/craft-anything` (`crates/formats/src/plist.rs` and checked byte reads), at source main `88d1d9cac852aec1c7fd97886db451e005e49d2a`. MIT OR Apache-2.0; source license texts are retained in the crate. Primary import Git authors preserve Brandon Thomas, BFlat, RRFZ and Afloat. Regression imports preserve BFlat. XML, JSON projection, calendar formatting and app policy were not imported into the public API. + +`crates/tga/src/metadata_tests.rs` and metadata-boundary helpers in `crates/tga/src/lib.rs` are adapted from nuclearspike's FilmCraft #1932 at `e7842f76f887005c460c64a8ab51d59d086e6f27` (MIT OR Apache-2.0). Synthetic fixtures are original contributor test data; primary Git author retained. +The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper are ported from Craft Anything `8f3b775157d331dd31cfa4da911e26d8856b8c77` (same MIT OR Apache-2.0 source licenses). Brandon Thomas is the primary import author; retained hardening credits include Afloat, BFlat, Rahul, RRFZ and NetterSilver. The finite-real fix preserves gmrmad1 as author from Craft Anything #1905 (`d85e104f`); quoted-attribute/line-ending regressions preserve RRFZ. Bounds/adaptation and bounded entity scanning are subsequent Dylan M. Taylor changes. App-specific JSON projections and keyed-archive interpretation remain outside this crate. + +## Score serializers + +`crates/score` extracts SoundCraft MusicXML and SVG score writing from `crates/engine/src/score.rs` at main `648ed9db9a0e98cc55643babffac381521a556c8`, with per-pitch ties adapted from [SoundCraft #182](https://github.com/storytold/soundcraft/pull/182) at `21cb618d93ec0e8d4771ac534994de8d5996ff10`. Source is MIT OR Apache-2.0. Import commits preserve Brandon Thomas, NetterSilver, Samuel Bacaro and Vikram Bhaskaran as primary authors of their respective changes. The consumer retains session mapping and layout. Shared API wiring, validation and focused tests are subsequent Dylan M. Taylor changes. + +## Source-timed MIDI compatibility + +`crates/midi/src/source_timed.rs` is extracted from LoopCraft `crates/midi/src/lib.rs` at `884e67c24b9b68badf6a4a4f7d62492f3673d354` (MIT OR Apache-2.0). The recorded source history for the extracted file is Dylan M. Taylor (`0d150c1f`, `440bc7ed`, `9e50523d`); Git authorship is preserved. It includes the original hostile-file, SMPTE, timing and round-trip tests. UTF-8 truncation and event-budget suffix repairs are subsequent changes. The module is an application-independent source-timed model; it does not depend on LoopCraft. +## Non-seeking WAV primitives + +`crates/audio/src/wav_stream.rs` is extracted from AniCraft `crates/audio/src/wav.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0). Tanish Manku is retained as the primary import author, from original commit `30c121d269a49d9abe54a3834ed4aa0201542535`. Odd-data padding accounting, shared API documentation and regression tests are subsequent Dylan M. Taylor changes. + +## GIMP palette reader + +`crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. + +The legacy ZIP Zstandard method-20 mapping and bounded-read regression in `crates/zip/src/lenient` are ported from RRFZ's Craft Anything commit `29badae7c9280fdf4c24795927bf3a91f51694c6` (MIT OR Apache-2.0). RRFZ remains the primary Git author. Firmware scanner detection remains app-owned and is not part of this port. +## TAR/CPIO compatibility updates + +The old GNU sparse-extension traversal, GNU CRC-symlink compatibility and PAX-size precedence fixes and their regression tests in `crates/tar` are ported from RRFZ's Craft Anything PRs #1973 (`8ea2ec66a1bc80f0420f3695baac877a0cb9b9a5`), #1984 (`b226a475f7dce9710e3af7a069386fe7a9720df7`) and #2007 (`d29465c20b0d570ea4973be512a0cb4e212bb60f`). Source is MIT OR Apache-2.0; RRFZ remains the primary Git author of each port. The PAX update adapts to the shared parser's existing `PaxOverrides` structure without changing the source policy. + +## Aligned stored ZIP entries + +The USDZ alignment requirement and compatibility fixture for `Writer::add_stored_aligned` come from TextureCraft `crates/formats/src/mesh_export/usd.rs`, introduced by bflatastic in `bdbb52c9` and maintained through `9eb20086` (MIT OR Apache-2.0). The shared API and alignment validation are subsequent Dylan M. Taylor work. Scene/material mapping remains in TextureCraft. + +The raw gradient wire ordering in `craft-lottie::Gradient::flat_values` follows +AniCraft's Lottie exporter by Tanish Manku (`63b39355`, `b9258b7b`), MIT OR Apache-2.0. +Sanitization, animation fitting and numeric output policy remain caller-owned. + +## Screen Video key frames + +`crates/video/src/screen_video.rs` extracts AniCraft `crates/xfl/src/video.rs` codec-3 decoding and its synthetic partial-block fixture, introduced by Tanish Manku in `1f3e603b7ff53a3da364e41ec4da8d43dc83aab0` with pixel-loop cleanup `2b7571363b4b647266df758f95b6e397021cfd4d` (MIT OR Apache-2.0). Import commits preserve Tanish as primary author. Caller-owned bounds and neutral RGBA output separate codec work from the consuming app's FLV first-frame/report policy. Boundary tests and integration are subsequent Dylan M. Taylor changes. + +## Source Map v3 parser and lookup + +`crates/sourcemap` extracts the bounded parser, source inventory and generated-position lookup from Craft Anything `crates/formats/src/sourcemap.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). Core-history ports preserve Brandon Thomas, BFlat, Afloat, RRFZ, Nicolas Bohn and Alex Joaquim Pereira as primary authors, with exact source revisions in each commit. Six regression files preserve their source authors; nine core unit tests retain the original tests. App annotation scanning, data URLs, base64 and file I/O are intentionally not imported. Workspace wiring is a subsequent change; existing limits and errors are unchanged. +## JSONC span-preserving editing + +`crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported. + +## XFA XML DOM + +`crates/xfa/src/xml.rs` is extracted from PDFCraft at `271e479c53723b1b294c866d5cb2f27604601b29`, originally by Dylan M. Taylor (`eead4541`, `7d44e654`), MIT OR Apache-2.0. The initial extraction changes visibility and module boundaries; subsequent namespace-retention budget hardening intentionally tightens resource admission. PDF/layout/form policy remains in the app. + +## Java class inspection + +`crates/java-class` extracts Craft Anything `java_class.rs` and `java_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0), preserving separate primary-author source-history ports by Brandon Thomas, BFlat, Afloat and RRFZ. The checked byte-reader, modified UTF-8 unit decoder, descriptor display helper and synthetic class fixtures come from the same source snapshot. Seven regression files retain their source authors. Neutral error wiring and shared crate integration are subsequent changes. No JAR archive, application I/O or bytecode execution is imported. + +## WebAssembly inspection + +`crates/wasm` extracts Craft Anything `crates/formats/src/wasm.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2`, with its checked byte-reader subset and original synthetic WASM/testkit fixtures (MIT OR Apache-2.0). Eight core-history ports preserve Brandon Thomas, Afloat and RRFZ as primary authors; component, repeated-custom-section and referenced-string regression imports retain source authors and commit references. Fixtures come from `crates/testkit/src/formats.rs` and deterministic mutation helpers from `crates/testkit/src/lib.rs`; no third-party binaries. Shared error naming and workspace wiring are subsequent changes. Existing inspection limits and report behavior are unchanged; this crate validates/inspects/renders, never executes modules. + +## Packet capture and protocol inspection + +`crates/pcap` extracts Craft Anything `crates/formats/src/pcap.rs`, its checked byte reader primitives and synthetic packet fixtures/regressions at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the implementation, byte reader and fixtures in `f64ae3bf3c8863a982af1304e06de20653803968`. Subsequent fixes by phatloi0010, GGWA, BFlat, Afloat, NetterSilver, Max Mittelstädt and RRFZ retain separate primary-author source-history commits with immutable source revisions. Shared error/API wiring and chrono-based timestamp formatting with exhaustive day-boundary parity tests are subsequent Dylan M. Taylor changes. No packet reassembly, decryption, live capture or app analysis policy is imported. +## HTTP Archive reader + +`crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. + +## Dalvik DEX inspection + +`crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained. + +## EVM bytecode inspection + +`crates/evm` extracts Craft Anything `crates/formats/src/evm.rs` at `a31e995858f4312e0f1d59a007112da191ef2d26` (MIT OR Apache-2.0). Eight separate source-history ports preserve Brandon Thomas, Afloat, RRFZ and NetterSilver as primary authors with immutable source references. Synthetic EVM fixtures and deterministic mutation helpers come from the same app source; regression files retain their source provenance. Neutral errors and workspace integration are subsequent changes. No code execution or transaction behavior is imported. + +## XFDF field reader + +`crates/xfdf` extracts PDFCraft field reading from #5937 refresh `cb564fd827f572818e9ddb0ea5989a432b1f39fd` (MIT OR Apache-2.0). App-side annotation and form policy remains local; source history is retained in the original repository. + +Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnulfo, pkibiego and storybored379; module split by aiongg. Subsequent budget/integration work by Dylan M. Taylor. diff --git a/Cargo.lock b/Cargo.lock index ddf27cf3b..42c84b806 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -116,12 +116,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" dependencies = [ "cfg-if", + "getrandom 0.3.4", "once_cell", "serde", "version_check", "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "aligned" version = "0.4.3" @@ -222,6 +232,17 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "apple-native-keyring-store" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a" +dependencies = [ + "keyring-core", + "log", + "security-framework", +] + [[package]] name = "arbitrary" version = "1.5.0" @@ -291,6 +312,51 @@ 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 = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "async-broadcast" version = "0.7.2" @@ -447,7 +513,7 @@ dependencies = [ "log", "num-rational", "num-traits", - "pastey", + "pastey 0.1.1", "rayon", "thiserror 2.0.21", "v_frame", @@ -513,6 +579,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + [[package]] name = "base64" version = "0.22.1" @@ -531,6 +603,15 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -549,11 +630,20 @@ dependencies = [ "bit-vec 0.10.1", ] +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] 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" @@ -724,6 +814,12 @@ dependencies = [ "cipher 0.4.4", ] +[[package]] +name = "borrow-or-share" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" + [[package]] name = "borsh" version = "1.8.1" @@ -835,6 +931,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + [[package]] name = "bytemuck" version = "1.25.2" @@ -873,6 +975,16 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "bzip2-rs" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "beeb59e7e4c811ab37cc73680c798c7a5da77fc9989c62b09138e31ee740f735" +dependencies = [ + "crc32fast", + "tinyvec", +] + [[package]] name = "calloop" version = "0.13.0" @@ -897,6 +1009,64 @@ dependencies = [ "cipher 0.4.4", ] +[[package]] +name = "candle-core" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c15b675b80d994b2eadb20a4bbe434eabeb454eac3ee5e2b4cf6f147ee9be091" +dependencies = [ + "byteorder", + "float8", + "gemm", + "half", + "libm", + "memmap2", + "num-traits", + "num_cpus", + "rand 0.9.5", + "rand_distr", + "rayon", + "safetensors", + "thiserror 2.0.21", + "yoke", + "zip 7.4.0", +] + +[[package]] +name = "candle-nn" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3045fa9e7aef8567d209a27d56b692f60b96f4d0569f4c3011f8ca6715c65e03" +dependencies = [ + "candle-core", + "half", + "libc", + "num-traits", + "rayon", + "safetensors", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "candle-transformers" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b538ec4aa807c416a2ddd3621044888f188827862e2a6fcacba4738e89795d01" +dependencies = [ + "byteorder", + "candle-core", + "candle-nn", + "fancy-regex 0.17.0", + "num-traits", + "rand 0.9.5", + "rayon", + "serde", + "serde_json", + "serde_plain", + "tracing", +] + [[package]] name = "cap-primitives" version = "4.0.3" @@ -915,6 +1085,18 @@ dependencies = [ "winx", ] +[[package]] +name = "cap-std" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8" +dependencies = [ + "cap-primitives", + "io-extras", + "io-lifetimes 3.0.1", + "rustix 1.1.5", +] + [[package]] name = "cast" version = "0.3.0" @@ -930,6 +1112,15 @@ dependencies = [ "cipher 0.4.4", ] +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cbc" version = "0.2.1" @@ -1083,7 +1274,7 @@ dependencies = [ "crmf", "der 0.7.10", "spki 0.7.3", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -1095,7 +1286,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]] @@ -1153,6 +1356,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "serde", + "static_assertions", +] + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -1189,6 +1407,35 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -1304,6 +1551,33 @@ dependencies = [ "sha2 0.10.9", ] +[[package]] +name = "craft-ai" +version = "0.1.0" +dependencies = [ + "candle-core", + "candle-nn", + "candle-transformers", + "dirs", + "serde", + "serde_json", + "sha2 0.11.1", + "sysinfo", + "tempfile", + "tokenizers", + "ureq", +] + +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + [[package]] name = "craft-ai-core" version = "0.1.0" @@ -1342,6 +1616,7 @@ version = "0.1.0" dependencies = [ "craft-media", "craft-media-testkit", + "craft-xml", "log", "proptest", "rayon", @@ -1351,10 +1626,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-ber" +version = "0.1.0" + [[package]] name = "craft-captions" version = "0.1.0" dependencies = [ + "craft-media", + "craft-media-testkit", "craft-timeline", "craft-xml", "proptest", @@ -1369,6 +1650,25 @@ dependencies = [ "craft-media-testkit", ] +[[package]] +name = "craft-cloud" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-cloud-local" +version = "0.1.0" +dependencies = [ + "cap-std", + "craft-cloud", + "craft-ui", + "egui", + "tempfile", +] + [[package]] name = "craft-cms" version = "0.1.0" @@ -1385,6 +1685,47 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-color" +version = "0.1.0" +dependencies = [ + "proptest", + "serde", +] + +[[package]] +name = "craft-color-transform" +version = "0.1.0" +dependencies = [ + "craft-cms", + "craft-color", + "serde", + "serde_json", +] + +[[package]] +name = "craft-control" +version = "0.1.0" +dependencies = [ + "craft-ai-agents", + "craft-atomic", + "craft-flags", + "getrandom 0.3.4", + "log", + "proptest", + "serde", + "serde_json", + "tempfile", +] + +[[package]] +name = "craft-control-protocol" +version = "0.1.0" +dependencies = [ + "serde_json", + "subtle", +] + [[package]] name = "craft-crs" version = "0.1.0" @@ -1420,6 +1761,24 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-dds" +version = "0.1.0" +dependencies = [ + "rayon", +] + +[[package]] +name = "craft-deckcraft-format" +version = "0.1.0" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", + "zip 9.1.3", +] + [[package]] name = "craft-designcraft-format" version = "0.1.0" @@ -1431,6 +1790,38 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-develop" +version = "0.1.0" +dependencies = [ + "craft-develop-model", + "craft-render-parity", + "proptest", + "rayon", + "serde", +] + +[[package]] +name = "craft-develop-model" +version = "0.1.0" +dependencies = [ + "craft-geom", + "craft-metadata", + "miniz_oxide 0.9.1", + "proptest", + "serde", + "serde_json", +] + +[[package]] +name = "craft-dex" +version = "0.1.0" +dependencies = [ + "craft-testkit", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-dialogs" version = "0.1.0" @@ -1470,6 +1861,7 @@ dependencies = [ "craft-wordmodel", "image", "log", + "md4", "miniz_oxide 0.9.1", "proptest", "serde_json", @@ -1488,7 +1880,7 @@ dependencies = [ "craft-zip", "serde_json", "thiserror 2.0.21", - "zip", + "zip 9.1.3", ] [[package]] @@ -1512,7 +1904,7 @@ dependencies = [ "thiserror 2.0.21", "unicode-bidi", "zeroize", - "zip", + "zip 9.1.3", ] [[package]] @@ -1561,6 +1953,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-elf" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-eps" version = "0.1.0" @@ -1578,7 +1979,27 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip", + "zip 9.1.3", +] + +[[package]] +name = "craft-esign" +version = "0.1.0" +dependencies = [ + "craft-cloud", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-evm" +version = "0.1.0" +dependencies = [ + "craft-testkit", + "serde", + "serde_json", + "thiserror 2.0.21", ] [[package]] @@ -1600,6 +2021,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-fcproj-format" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-fig" version = "0.1.0" @@ -1612,7 +2042,7 @@ dependencies = [ "ruzstd", "serde_json", "thiserror 2.0.21", - "zip", + "zip 9.1.3", ] [[package]] @@ -1623,7 +2053,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip", + "zip 9.1.3", ] [[package]] @@ -1659,6 +2089,7 @@ dependencies = [ "craft-dxf", "craft-eps", "craft-file-formats", + "craft-image-codecs", "craft-pdf 0.1.0", "craft-raster-codecs", "craft-svg", @@ -1691,8 +2122,12 @@ name = "craft-font-catalog" version = "0.1.0" dependencies = [ "fontique", + "harfrust 0.13.3", + "kurbo 0.13.1", "skrifa 0.47.0", "thiserror 2.0.21", + "unicode-bidi", + "unicode-segmentation", "windows-registry", "write-fonts 0.54.1", ] @@ -1751,6 +2186,26 @@ dependencies = [ "craft-fonts-build", ] +[[package]] +name = "craft-format" +version = "0.1.0" +dependencies = [ + "craft-zip", + "proptest", + "serde_json", + "sha2 0.10.9", +] + +[[package]] +name = "craft-frame" +version = "0.1.0" +dependencies = [ + "craft-color", + "craft-time", + "rayon", + "serde", +] + [[package]] name = "craft-gainmap" version = "0.1.0" @@ -1765,6 +2220,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-geom" +version = "0.1.0" +dependencies = [ + "proptest", + "serde", +] + [[package]] name = "craft-gif" version = "0.1.0" @@ -1773,6 +2236,64 @@ dependencies = [ "image", ] +[[package]] +name = "craft-gpu" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-gpu-null" +version = "0.1.0" +dependencies = [ + "craft-gpu", +] + +[[package]] +name = "craft-gpu-providers" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-null", +] + +[[package]] +name = "craft-gpu-wgpu" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-providers", + "pollster 0.4.0", + "wgpu", +] + +[[package]] +name = "craft-gridcraft-format" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-gzip" +version = "0.1.0" +dependencies = [ + "flate2", +] + +[[package]] +name = "craft-har" +version = "0.1.0" +dependencies = [ + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-hdr" version = "0.1.0" @@ -1785,6 +2306,7 @@ name = "craft-heif" version = "0.1.0" dependencies = [ "heic-rs", + "proptest", "rayon", ] @@ -1801,6 +2323,10 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-http-url" +version = "0.1.0" + [[package]] name = "craft-i18n" version = "0.1.0" @@ -1839,27 +2365,38 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip", + "zip 9.1.3", ] [[package]] name = "craft-image-codecs" version = "0.1.0" dependencies = [ + "avif-serialize", + "craft-dds", "craft-heif", "craft-jpeg", + "craft-jxl", + "craft-media-testkit", "craft-metadata", + "craft-tiff", + "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", @@ -1874,6 +2411,34 @@ dependencies = [ "indd", ] +[[package]] +name = "craft-ipc" +version = "0.1.0" +dependencies = [ + "chrono", + "getrandom 0.2.17", + "interprocess", + "jsonschema", + "libc", + "serde", + "serde_json", + "sha2 0.10.9", + "widestring", +] + +[[package]] +name = "craft-ipp" +version = "0.1.0" + +[[package]] +name = "craft-java-class" +version = "0.1.0" +dependencies = [ + "craft-testkit", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-jmap" version = "0.1.0" @@ -1893,10 +2458,26 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "craft-jsonc" +version = "0.1.0" +dependencies = [ + "serde_json", +] + +[[package]] +name = "craft-jsonrpc" +version = "0.1.0" +dependencies = [ + "serde_json", + "tokio", +] + [[package]] name = "craft-jxl" version = "0.1.0" dependencies = [ + "brotli-decompressor 5.0.3", "craft-cms", "jixel", "jxl-oxide", @@ -1930,7 +2511,7 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip", + "zip 9.1.3", ] [[package]] @@ -1954,6 +2535,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-macho" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-markdown" version = "0.1.0" @@ -1982,6 +2572,32 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-mcmat" +version = "0.1.0" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-mcp" +version = "0.1.0" +dependencies = [ + "craft-jsonrpc", + "serde_json", +] + +[[package]] +name = "craft-mcp-server" +version = "0.1.0" +dependencies = [ + "proptest", + "serde_json", +] + [[package]] name = "craft-media" version = "0.1.0" @@ -1994,9 +2610,26 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-media-source" +version = "0.1.0" +dependencies = [ + "craft-audio", + "craft-color", + "craft-frame", + "craft-media", + "craft-time", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-media-testkit" version = "0.1.0" +dependencies = [ + "craft-testkit", +] [[package]] name = "craft-menu" @@ -2016,6 +2649,7 @@ version = "0.1.0" dependencies = [ "craft-opc", "craft-xml", + "craft-zip", "miniz_oxide 0.9.1", "serde_json", ] @@ -2088,7 +2722,7 @@ dependencies = [ "sha2 0.11.1", "thiserror 2.0.21", "zeroize", - "zip", + "zip 9.1.3", ] [[package]] @@ -2125,7 +2759,7 @@ dependencies = [ "craft-zip", "log", "thiserror 2.0.21", - "zip", + "zip 9.1.3", ] [[package]] @@ -2150,7 +2784,21 @@ dependencies = [ "craft-xml", "craft-zip", "thiserror 2.0.21", - "zip", + "zip 9.1.3", +] + +[[package]] +name = "craft-palette" +version = "0.1.0" + +[[package]] +name = "craft-pcap" +version = "0.1.0" +dependencies = [ + "chrono", + "serde", + "serde_json", + "thiserror 2.0.21", ] [[package]] @@ -2169,6 +2817,7 @@ dependencies = [ name = "craft-pcraft-format" version = "0.1.0" dependencies = [ + "flate2", "serde", "serde_json", "thiserror 2.0.21", @@ -2226,6 +2875,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pe" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-penpot" version = "0.1.0" @@ -2234,7 +2892,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip", + "zip 9.1.3", ] [[package]] @@ -2298,14 +2956,35 @@ dependencies = [ "zbus", ] +[[package]] +name = "craft-plist" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-plotter" version = "0.1.0" dependencies = [ + "kurbo 0.13.1", "serde", "thiserror 2.0.21", ] +[[package]] +name = "craft-ppt-binary" +version = "0.1.0" +dependencies = [ + "craft-cfb", + "craft-drawingml", + "craft-pptx", + "image", + "log", + "miniz_oxide 0.8.9", + "thiserror 2.0.21", +] + [[package]] name = "craft-pptx" version = "0.1.0" @@ -2342,6 +3021,16 @@ dependencies = [ "ttf-parser", ] +[[package]] +name = "craft-press-print" +version = "0.1.0" +dependencies = [ + "craft-cms", + "craft-prepress", + "craft-print", + "thiserror 2.0.21", +] + [[package]] name = "craft-print" version = "0.1.0" @@ -2366,11 +3055,22 @@ 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", + "flate2", "kurbo 0.13.1", "miniz_oxide 0.8.9", "pdf-writer", @@ -2395,6 +3095,7 @@ dependencies = [ name = "craft-pst" version = "0.1.0" dependencies = [ + "craft-pst", "proptest", ] @@ -2414,9 +3115,9 @@ name = "craft-raster-codecs" version = "0.1.0" dependencies = [ "base64 0.23.1", + "craft-dds", "craft-image-codecs", "image", - "rayon", "thiserror 2.0.21", ] @@ -2441,6 +3142,13 @@ dependencies = [ "zune-jpegxl", ] +[[package]] +name = "craft-render-parity" +version = "0.1.0" +dependencies = [ + "craft-cms", +] + [[package]] name = "craft-rtf" version = "0.1.0" @@ -2455,6 +3163,13 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-score" +version = "0.1.0" +dependencies = [ + "craft-xml", +] + [[package]] name = "craft-scraft-format" version = "0.1.0" @@ -2492,6 +3207,10 @@ dependencies = [ name = "craft-sheet" version = "0.1.0" +[[package]] +name = "craft-shx" +version = "0.1.0" + [[package]] name = "craft-silhouette-studio" version = "0.1.0" @@ -2509,9 +3228,61 @@ dependencies = [ "kurbo 0.13.1", "serde_json", "thiserror 2.0.21", - "zip", + "zip 9.1.3", ] +[[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-sniff" +version = "0.1.0" + +[[package]] +name = "craft-sourcemap" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-sqlite" +version = "0.1.0" + +[[package]] +name = "craft-ssip" +version = "0.1.0" + [[package]] name = "craft-stencilcraft-document" version = "0.1.0" @@ -2546,17 +3317,37 @@ dependencies = [ "weezl 0.2.1", ] +[[package]] +name = "craft-suite-account" +version = "0.1.0" +dependencies = [ + "dirs", + "keyring", + "keyring-core", + "log", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", + "zeroize", +] + [[package]] name = "craft-svg" version = "0.1.0" dependencies = [ "craft-image-codecs", "craft-xml", + "data-url", "flate2", + "gif", + "image-webp", "kurbo 0.13.1", + "quick-xml 0.41.0", "resvg 0.48.1", "roxmltree 0.21.2", "thiserror 2.0.21", + "toml", "usvg 0.48.1", "vectorcraft-geom", "vectorcraft-pathops", @@ -2570,12 +3361,35 @@ dependencies = [ "kurbo 0.13.1", ] +[[package]] +name = "craft-tar" +version = "0.1.0" +dependencies = [ + "craft-testkit", + "serde", +] + +[[package]] +name = "craft-tcraft" +version = "0.1.0" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-testkit" +version = "0.1.0" + [[package]] name = "craft-text" version = "0.1.0" dependencies = [ "hypher", "icu_segmenter", + "kurbo 0.13.1", "miniz_oxide 0.8.9", "unicode-bidi", "unicode-bidi-mirroring", @@ -2588,6 +3402,9 @@ dependencies = [ name = "craft-texture" version = "0.1.0" dependencies = [ + "bytemuck", + "dds", + "half", "rayon", "thiserror 2.0.21", ] @@ -2633,6 +3450,8 @@ dependencies = [ name = "craft-ui" version = "0.1.0" dependencies = [ + "craft-cloud", + "craft-esign", "craft-fonts-build", "craft-i18n", "eframe", @@ -2682,7 +3501,15 @@ dependencies = [ "verifysign", "winreg", "winsafe", - "zip", + "zip 9.1.3", +] + +[[package]] +name = "craft-usd" +version = "0.1.0" +dependencies = [ + "lz4_flex", + "thiserror 2.0.21", ] [[package]] @@ -2699,6 +3526,7 @@ name = "craft-vectorcraft-format" version = "0.1.0" dependencies = [ "flate2", + "proptest", "serde", "serde_json", "thiserror 2.0.21", @@ -2716,12 +3544,26 @@ dependencies = [ name = "craft-video" version = "0.1.0" dependencies = [ + "craft-jpeg", "craft-media", "craft-media-testkit", + "miniz_oxide 0.8.9", + "rav1e", "rayon", "thiserror 2.0.21", ] +[[package]] +name = "craft-wasm" +version = "0.1.0" +dependencies = [ + "craft-testkit", + "serde", + "thiserror 2.0.21", + "wasmparser 0.261.0", + "wasmprinter", +] + [[package]] name = "craft-web-api" version = "0.1.0" @@ -2796,10 +3638,26 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xfa" +version = "0.1.0" +dependencies = [ + "craft-xml", +] + +[[package]] +name = "craft-xfdf" +version = "0.1.0" +dependencies = [ + "craft-xml", + "thiserror 2.0.21", +] + [[package]] name = "craft-xfl" version = "0.1.0" dependencies = [ + "craft-xml", "miniz_oxide 0.8.9", "thiserror 2.0.21", ] @@ -2810,6 +3668,7 @@ version = "0.1.0" dependencies = [ "craft-cfb", "craft-sheet", + "craft-xls", "md-5 0.10.6", "miniz_oxide 0.9.1", "sha1 0.10.7", @@ -2823,6 +3682,7 @@ dependencies = [ "craft-drawingml", "craft-opc", "craft-sheet", + "craft-xlsx", "craft-xml", "thiserror 2.0.21", ] @@ -2836,6 +3696,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xtask" +version = "0.1.0" +dependencies = [ + "craft-atomic", + "serde_json", + "tempfile", +] + [[package]] name = "craft-y4m" version = "0.1.0" @@ -2847,12 +3716,33 @@ dependencies = [ name = "craft-zip" version = "0.1.0" dependencies = [ + "bzip2-rs", "craft-zip", "flate2", + "lzma-rs", + "miniz_oxide 0.8.9", + "ruzstd", + "serde", + "serde_json", "thiserror 2.0.21", - "zip", + "zip 9.1.3", ] +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + [[package]] name = "crc24" version = "0.1.6" @@ -2874,10 +3764,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]] @@ -3101,6 +3991,21 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "dary_heap" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe" +dependencies = [ + "serde", +] + +[[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" @@ -3116,6 +4021,19 @@ dependencies = [ "generic-array", ] +[[package]] +name = "dds" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e917a58e17b27d2f15626c490754ccced7f46592dc5b5f39a3013b89cba5f068" +dependencies = [ + "astc-decode", + "bitflags 2.13.2", + "glam", + "resize", + "zerocopy", +] + [[package]] name = "der" version = "0.7.10" @@ -3123,7 +4041,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", @@ -3136,10 +4054,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" @@ -3151,6 +4085,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" @@ -3325,6 +4270,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "doctest-file" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2db04e74f0a9a93103b50e90b96024c9b2bdca8bce6a632ec71b88736d3d359" + [[package]] name = "document-features" version = "0.2.12" @@ -3368,6 +4319,22 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "dyn-stack" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c4713e43e2886ba72b8271aa66c93d722116acf7a75555cce11dcde84388fe8" +dependencies = [ + "bytemuck", + "dyn-stack-macros", +] + +[[package]] +name = "dyn-stack-macros" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9" + [[package]] name = "eax" version = "0.5.0" @@ -3641,7 +4608,7 @@ dependencies = [ "ff 0.13.1", "generic-array", "group 0.13.0", - "hkdf", + "hkdf 0.12.4", "pem-rfc7468 0.7.0", "pkcs8 0.10.2", "rand_core 0.6.4", @@ -3673,6 +4640,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" +dependencies = [ + "serde", +] + [[package]] name = "emath" version = "0.37.0" @@ -3714,6 +4690,18 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +[[package]] +name = "enum-as-inner" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "enum-map" version = "3.1.0" @@ -3834,6 +4822,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "esaxx-rs" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6" + [[package]] name = "euclid" version = "0.22.14" @@ -3885,6 +4879,28 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" +[[package]] +name = "fancy-regex" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72cf461f865c862bb7dc573f643dd6a2b6842f7c30b07882b56bd148cc2761b8" +dependencies = [ + "bit-set 0.8.0", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "fancy-regex" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912" +dependencies = [ + "bit-set 0.8.0", + "regex-automata", + "regex-syntax", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -3998,6 +5014,29 @@ dependencies = [ "num-traits", ] +[[package]] +name = "float8" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "719a903cc23e4a89e87962c2a80fdb45cdaad0983a89bd150bb57b4c8571a7d5" +dependencies = [ + "half", + "num-traits", + "rand 0.9.5", + "rand_distr", +] + +[[package]] +name = "fluent-uri" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e" +dependencies = [ + "borrow-or-share", + "ref-cast", + "serde", +] + [[package]] name = "fmt-derive" version = "0.1.2" @@ -4150,6 +5189,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fraction" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e076045bb43dac435333ed5f04caf35c7463631d0dae2deb2638d94dd0a5b872" +dependencies = [ + "lazy_static", + "num", +] + [[package]] name = "fs-set-times" version = "0.20.3" @@ -4208,6 +5257,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "futures-sink" version = "0.3.34" @@ -4228,6 +5288,7 @@ checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", "futures-io", + "futures-macro", "futures-sink", "futures-task", "memchr", @@ -4235,6 +5296,125 @@ dependencies = [ "slab", ] +[[package]] +name = "gemm" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa0673db364b12263d103b68337a68fbecc541d6f6b61ba72fe438654709eacb" +dependencies = [ + "dyn-stack", + "gemm-c32", + "gemm-c64", + "gemm-common", + "gemm-f16", + "gemm-f32", + "gemm-f64", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "seq-macro", +] + +[[package]] +name = "gemm-c32" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "086936dbdcb99e37aad81d320f98f670e53c1e55a98bee70573e83f95beb128c" +dependencies = [ + "dyn-stack", + "gemm-common", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "seq-macro", +] + +[[package]] +name = "gemm-c64" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c8aeeeec425959bda4d9827664029ba1501a90a0d1e6228e48bef741db3a3f" +dependencies = [ + "dyn-stack", + "gemm-common", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "seq-macro", +] + +[[package]] +name = "gemm-common" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88027625910cc9b1085aaaa1c4bc46bb3a36aad323452b33c25b5e4e7c8e2a3e" +dependencies = [ + "bytemuck", + "dyn-stack", + "half", + "libm", + "num-complex", + "num-traits", + "once_cell", + "paste", + "pulp", + "raw-cpuid", + "rayon", + "seq-macro", + "sysctl", +] + +[[package]] +name = "gemm-f16" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3df7a55202e6cd6739d82ae3399c8e0c7e1402859b30e4cb780e61525d9486e" +dependencies = [ + "dyn-stack", + "gemm-common", + "gemm-f32", + "half", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "rayon", + "seq-macro", +] + +[[package]] +name = "gemm-f32" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02e0b8c9da1fbec6e3e3ab2ce6bc259ef18eb5f6f0d3e4edf54b75f9fd41a81c" +dependencies = [ + "dyn-stack", + "gemm-common", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "seq-macro", +] + +[[package]] +name = "gemm-f64" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "056131e8f2a521bfab322f804ccd652520c79700d81209e9d9275bbdecaadc6a" +dependencies = [ + "dyn-stack", + "gemm-common", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "seq-macro", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -4337,6 +5517,12 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glam" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" + [[package]] name = "glifo" version = "0.1.1" @@ -4518,9 +5704,12 @@ version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ + "bytemuck", "cfg-if", "crunchy", "num-traits", + "rand 0.9.5", + "rand_distr", "zerocopy", ] @@ -4567,6 +5756,8 @@ dependencies = [ "allocator-api2", "equivalent", "foldhash 0.2.0", + "serde", + "serde_core", ] [[package]] @@ -4575,6 +5766,8 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ + "allocator-api2", + "equivalent", "foldhash 0.2.0", ] @@ -4705,6 +5898,15 @@ dependencies = [ "hmac 0.12.1", ] +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", +] + [[package]] name = "hmac" version = "0.12.1" @@ -5223,6 +6425,19 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "interprocess" +version = "2.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb02ffbf25e8ef0f4a95bff054eef75f6d1bf16919474cf2caa63b21997478a" +dependencies = [ + "doctest-file", + "libc", + "recvmsg", + "widestring", + "windows-sys 0.61.2", +] + [[package]] name = "io-extras" version = "0.19.0" @@ -5400,6 +6615,58 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonschema" +version = "0.49.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ec8a241beed129f06114aa68007e905ca350e7baeb6e17a7631bb7978d91b2" +dependencies = [ + "ahash", + "bytecount", + "data-encoding", + "email_address", + "fancy-regex 0.19.2", + "fraction", + "getrandom 0.3.4", + "idna", + "itoa", + "jsonschema-regex", + "jsonschema-value", + "num-cmp", + "num-traits", + "percent-encoding", + "referencing", + "regex", + "serde", + "serde_json", + "strum", + "unicode-general-category", + "uuid-simd", +] + +[[package]] +name = "jsonschema-regex" +version = "0.49.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91994f45017ed5e66aa8e59b8415f4cb033a6380d7200387b7cf117595fbdf85" +dependencies = [ + "regex-syntax", +] + +[[package]] +name = "jsonschema-value" +version = "0.49.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ec7637f83e510868ae6ed625f7ebfbbde4554ee8ce49854caa5126a8b9b9ecb" +dependencies = [ + "ahash", + "bytecount", + "fraction", + "num-cmp", + "num-traits", + "serde_json", +] + [[package]] name = "jxl-bitstream" version = "1.1.0" @@ -5621,6 +6888,27 @@ dependencies = [ "serde", ] +[[package]] +name = "keyring" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" +dependencies = [ + "apple-native-keyring-store", + "keyring-core", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", +] + +[[package]] +name = "keyring-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fbf4b551298c67925f38cf341a1ada797a75f1837bdf8ae1fc8e2ebc6efb59" +dependencies = [ + "log", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -5848,6 +7136,38 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "lz4_flex" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" + +[[package]] +name = "lzma-rs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e" +dependencies = [ + "byteorder", + "crc", +] + +[[package]] +name = "macro_rules_attribute" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c" +dependencies = [ + "macro_rules_attribute-proc_macro", + "pastey 0.2.3", +] + +[[package]] +name = "macro_rules_attribute-proc_macro" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" + [[package]] name = "maybe-owned" version = "0.3.4" @@ -5861,6 +7181,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" dependencies = [ "cfg-if", + "rayon", ] [[package]] @@ -5883,6 +7204,15 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "md4" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd76fb0fd6b2e4be62a73f8e0858ca97f81babcb1af322dcaca196f735f17f80" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "memchr" version = "2.8.3" @@ -5896,6 +7226,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", + "stable_deref_trait", ] [[package]] @@ -5907,6 +7238,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "micromap" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74" + [[package]] name = "mime" version = "0.3.17" @@ -5960,6 +7297,28 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "monostate" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67" +dependencies = [ + "monostate-impl", + "serde", + "serde_core", +] + +[[package]] +name = "monostate-impl" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -6142,6 +7501,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -6151,6 +7519,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -6178,12 +7560,19 @@ dependencies = [ "zeroize", ] +[[package]] +name = "num-cmp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa" + [[package]] name = "num-complex" version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" dependencies = [ + "bytemuck", "num-traits", ] @@ -6244,6 +7633,16 @@ dependencies = [ "libm", ] +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + [[package]] name = "num_enum" version = "0.7.6" @@ -6444,6 +7843,16 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-io-surface" version = "0.3.2" @@ -6491,6 +7900,17 @@ dependencies = [ "objc2-foundation 0.3.2", ] +[[package]] +name = "objc2-open-directory" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb82bed227edf5201dfedf072bba4015a33d3d4a98519837295a90f0a23f676d" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-quartz-core" version = "0.2.2" @@ -6606,12 +8026,43 @@ dependencies = [ "phf 0.11.3", ] +[[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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "onig" +version = "6.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2" +dependencies = [ + "bitflags 2.13.2", + "libc", + "once_cell", + "onig_sys", +] + +[[package]] +name = "onig_sys" +version = "69.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "oorandom" version = "11.1.5" @@ -6684,6 +8135,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + [[package]] name = "p256" version = "0.13.2" @@ -6821,6 +8278,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pbkdf2" version = "0.13.0" @@ -6929,7 +8392,7 @@ dependencies = [ "generic-array", "getrandom 0.2.17", "hex", - "hkdf", + "hkdf 0.12.4", "idea", "k256", "log", @@ -7095,6 +8558,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" @@ -7399,6 +8877,29 @@ dependencies = [ "unarray", ] +[[package]] +name = "pulp" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" +dependencies = [ + "bytemuck", + "cfg-if", + "libm", + "num-complex", + "paste", + "pulp-wasm-simd-flag", + "raw-cpuid", + "reborrow", + "version_check", +] + +[[package]] +name = "pulp-wasm-simd-flag" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" + [[package]] name = "pxfm" version = "0.1.30" @@ -7604,6 +9105,16 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_distr" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463" +dependencies = [ + "num-traits", + "rand 0.9.5", +] + [[package]] name = "rand_pcg" version = "0.10.2" @@ -7674,9 +9185,19 @@ dependencies = [ "loop9", "quick-error 2.0.1", "rav1e", + "rayon", "rgb", ] +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -7705,6 +9226,17 @@ dependencies = [ "rayon-core", ] +[[package]] +name = "rayon-cond" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f" +dependencies = [ + "either", + "itertools 0.14.0", + "rayon", +] + [[package]] name = "rayon-core" version = "1.13.0" @@ -7724,6 +9256,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" @@ -7780,6 +9325,18 @@ dependencies = [ "yoke", ] +[[package]] +name = "reborrow" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" + +[[package]] +name = "recvmsg" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3edd4d5d42c92f0a659926464d4cce56b562761267ecf0f469d85b7de384175" + [[package]] name = "redox_syscall" version = "0.4.1" @@ -7817,6 +9374,66 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "referencing" +version = "0.49.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6efa2154ea6f5ce0fdecdd2a8d18f2fa1a39a8fbba91564f555a592e4dce8278" +dependencies = [ + "ahash", + "fluent-uri", + "getrandom 0.3.4", + "hashbrown 0.17.1", + "itoa", + "micromap", + "parking_lot", + "percent-encoding", + "serde_json", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + [[package]] name = "regex-lite" version = "0.1.9" @@ -7884,6 +9501,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "resize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71725ecd5e0197b54fe859055b108688472ab6a358f8fbe5cee4a556b1b5bfea" +dependencies = [ + "rgb", +] + [[package]] name = "resvg" version = "0.45.1" @@ -8091,6 +9717,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" @@ -8194,9 +9829,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -8258,6 +9893,17 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" +[[package]] +name = "safetensors" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "675656c1eabb620b921efea4f9199f97fc86e36dd6ffd1fbbe48d0f59a4987f5" +dependencies = [ + "hashbrown 0.16.1", + "serde", + "serde_json", +] + [[package]] name = "same-file" version = "1.0.6" @@ -8311,6 +9957,25 @@ dependencies = [ "zeroize", ] +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes 0.9.4", + "cbc", + "futures-util", + "getrandom 0.4.3", + "hkdf 0.13.0", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2 0.11.1", + "zbus", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -8356,6 +10021,12 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.229" @@ -8410,6 +10081,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "serde_plain" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50" +dependencies = [ + "serde", +] + [[package]] name = "serde_repr" version = "0.1.21" @@ -8621,7 +10301,7 @@ dependencies = [ "spki 0.7.3", "thiserror 2.0.21", "tracing", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -8670,7 +10350,7 @@ dependencies = [ "sigstore-crypto", "sigstore-types", "thiserror 2.0.21", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -8683,7 +10363,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cmpv2", - "cms", + "cms 0.2.3", "const-oid 0.9.6", "der 0.7.10", "hex", @@ -8695,7 +10375,7 @@ dependencies = [ "sigstore-types", "thiserror 2.0.21", "tracing", - "x509-cert", + "x509-cert 0.2.5", "x509-tsp", ] @@ -8722,7 +10402,7 @@ checksum = "d30aff69036e4579b416956e9ba68cec45b793116f78f10842d04c7f8b924bab" dependencies = [ "base64 0.22.1", "chrono", - "cms", + "cms 0.2.3", "const-oid 0.9.6", "hex", "pem", @@ -8741,7 +10421,7 @@ dependencies = [ "thiserror 2.0.21", "tls_codec", "tracing", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -8941,6 +10621,18 @@ dependencies = [ "der 0.8.3", ] +[[package]] +name = "spm_precompiled" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326" +dependencies = [ + "base64 0.13.1", + "nom 7.1.3", + "serde", + "unicode-segmentation", +] + [[package]] name = "sponge-cursor" version = "0.1.0" @@ -9292,6 +10984,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" @@ -9315,6 +11018,35 @@ dependencies = [ "web-sys", ] +[[package]] +name = "sysctl" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01198a2debb237c62b6826ec7081082d951f46dbb64b0e8c7649a452230d1dfc" +dependencies = [ + "bitflags 2.13.2", + "byteorder", + "enum-as-inner", + "libc", + "thiserror 1.0.69", + "walkdir", +] + +[[package]] +name = "sysinfo" +version = "0.39.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "objc2-open-directory", + "windows", +] + [[package]] name = "system-configuration" version = "0.7.0" @@ -9564,6 +11296,39 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "tokenizers" +version = "0.22.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b238e22d44a15349529690fb07bd645cf58149a1b1e44d6cb5bd1641ff1a6223" +dependencies = [ + "ahash", + "aho-corasick", + "compact_str", + "dary_heap", + "derive_builder", + "esaxx-rs", + "getrandom 0.3.4", + "itertools 0.14.0", + "log", + "macro_rules_attribute", + "monostate", + "onig", + "paste", + "rand 0.9.5", + "rayon", + "rayon-cond", + "regex", + "regex-syntax", + "serde", + "serde_json", + "spm_precompiled", + "thiserror 2.0.21", + "unicode-normalization-alignments", + "unicode-segmentation", + "unicode_categories", +] + [[package]] name = "tokio" version = "1.53.2" @@ -9575,9 +11340,21 @@ dependencies = [ "mio", "pin-project-lite", "socket2", + "tokio-macros", "windows-sys 0.61.2", ] +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "tokio-rustls" version = "0.26.6" @@ -9765,6 +11542,12 @@ dependencies = [ "rustc-hash 2.1.3", ] +[[package]] +name = "typed-path" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" + [[package]] name = "typed-path" version = "0.13.0" @@ -9839,6 +11622,15 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-normalization-alignments" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de" +dependencies = [ + "smallvec", +] + [[package]] name = "unicode-properties" version = "0.1.4" @@ -9875,6 +11667,12 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "unicode_categories" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" + [[package]] name = "universal-hash" version = "0.5.1" @@ -9904,12 +11702,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" dependencies = [ "base64 0.23.1", + "cookie_store", "flate2", "log", "percent-encoding", "rustls", "rustls-pki-types", "rustls-platform-verifier", + "serde", + "serde_json", "ureq-proto", "utf8-zero", "webpki-roots", @@ -10045,6 +11846,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "uuid-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8" +dependencies = [ + "outref", + "vsimd", +] + [[package]] name = "v_frame" version = "0.3.9" @@ -10367,6 +12178,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + [[package]] name = "wait-timeout" version = "0.2.1" @@ -10515,7 +12332,7 @@ dependencies = [ "wasmi_collections", "wasmi_core", "wasmi_ir", - "wasmparser", + "wasmparser 0.228.0", ] [[package]] @@ -10555,6 +12372,28 @@ dependencies = [ "indexmap", ] +[[package]] +name = "wasmparser" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" +dependencies = [ + "bitflags 2.13.2", + "indexmap", + "semver", +] + +[[package]] +name = "wasmprinter" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a21c9e3325655ba02de3e645bc8357a8b3651a2e3ada25b6dbc37560deb9b7" +dependencies = [ + "anyhow", + "termcolor", + "wasmparser 0.261.0", +] + [[package]] name = "wayland-backend" version = "0.3.17" @@ -10836,6 +12675,28 @@ dependencies = [ "web-sys", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -10845,6 +12706,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows" version = "0.62.2" @@ -10918,6 +12785,19 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "windows-numerics" version = "0.3.1" @@ -11112,7 +12992,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", @@ -11283,6 +13163,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" @@ -11290,7 +13199,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5ceece934a21607055b7ac5c25adb56a2ff559804b10705dc674d1d838c15e1" dependencies = [ "cmpv2", - "cms", + "cms 0.2.3", "der 0.7.10", ] @@ -11353,6 +13262,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" @@ -11384,7 +13303,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -11422,6 +13341,17 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + [[package]] name = "zbus_macros" version = "5.19.0" @@ -11495,7 +13425,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -11557,9 +13487,21 @@ dependencies = [ [[package]] name = "zip" -version = "9.1.0" +version = "7.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704" +checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980" +dependencies = [ + "crc32fast", + "indexmap", + "memchr", + "typed-path 0.12.4", +] + +[[package]] +name = "zip" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb" dependencies = [ "crc32fast", "flate2", @@ -11567,7 +13509,7 @@ dependencies = [ "indexmap", "memchr", "nix", - "typed-path", + "typed-path 0.13.0", "windows-sys 0.61.2", ] diff --git a/Cargo.toml b/Cargo.toml index 576efca6f..7ef038f99 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,15 +11,38 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-xfa = { path = "crates/xfa" } +craft-evm = { path = "crates/evm" } +craft-java-class = { path = "crates/java-class" } +craft-sourcemap = { path = "crates/sourcemap" } +craft-pcap = { path = "crates/pcap" } +craft-har = { path = "crates/har" } +craft-xfdf = { path = "crates/xfdf" } +craft-jsonc = { path = "crates/jsonc" } +craft-palette = { path = "crates/palette" } +craft-score = { path = "crates/score" } +craft-sqlite = { path = "crates/sqlite" } +craft-shx = { path = "crates/shx" } +craft-http-url = { path = "crates/http-url" } +craft-usd = { path = "crates/usd" } +craft-smime = { path = "crates/smime" } +craft-ssip = { path = "crates/ssip" } +craft-ber = { path = "crates/ber" } +craft-proto = { path = "crates/proto" } +craft-render-parity = { path = "crates/render-parity" } acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` +craft-plist = { path = "crates/plist" } +craft-wasm = { path = "crates/wasm" } craft-platform = { path = "crates/platform" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } +craft-ai = { path = "crates/ai" } craft-ai-core = { path = "crates/ai-core" } craft-anicraft-format = { path = "crates/anicraft-format" } craft-pdf = { path = "crates/pdf", version = "=0.1.0" } +craft-pe = { path = "crates/pe" } craft-ps = { path = "crates/ps", version = "=0.1.0" } craft-pdn = { path = "crates/pdn" } craft-plate-test = { path = "crates/plate-test" } @@ -34,12 +57,23 @@ hayro-syntax = { version = "=0.7.2", default-features = false, features = ["std" bytemuck = "1" kurbo = "0.13" thiserror = "2" +craft-gzip = { path = "crates/gzip" } +craft-gridcraft-format = { path = "crates/gridcraft-format" } craft-aaf = { path = "crates/aaf" } craft-atomic = { path = "crates/atomic" } +# The ArtCraft Launcher's app list for AI agents (storytold/craft-ai-integrations, crates/app/ai-agents). +craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "d94a3593adcff504eaaad9e5aee4c84fd2f07a72" } +craft-dex = { path = "crates/dex" } +craft-xtask = { path = "crates/xtask" } craft-captions = { path = "crates/captions" } craft-cfb = { path = "crates/cfb" } craft-codepage = { path = "crates/codepage" } craft-cms = { path = "crates/cms" } +craft-cloud = { path = "crates/cloud" } +craft-cloud-local = { path = "crates/cloud-local" } +craft-color = { path = "crates/color" } +craft-color-transform = { path = "crates/color-transform" } +craft-frame = { path = "crates/frame" } craft-crs = { path = "crates/crs" } craft-crw = { path = "crates/crw" } craft-csv = { path = "crates/csv" } @@ -48,10 +82,13 @@ 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-deckcraft-format = { path = "crates/deckcraft-format" } craft-designcraft-format = { path = "crates/designcraft-format" } craft-dxf = { path = "crates/dxf" } craft-drawingml = { path = "crates/drawingml" } craft-eps = { path = "crates/eps" } +craft-elf = { path = "crates/elf" } 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" } @@ -62,7 +99,9 @@ craft-doc = { path = "crates/doc" } craft-docpath = { path = "crates/docpath" } craft-dpx = { path = "crates/dpx" } craft-dwg = { path = "crates/dwg" } +craft-fcproj-format = { path = "crates/fcproj-format" } craft-ecproj-format = { path = "crates/ecproj-format" } +craft-esign = { path = "crates/esign" } craft-figma-rest = { path = "crates/figma-rest" } craft-exr = { path = "crates/exr" } craft-flags = { path = "crates/flags" } @@ -76,16 +115,25 @@ craft-gif = { path = "crates/gif" } craft-hdr = { path = "crates/hdr" } craft-mesh = { path = "crates/mesh" } craft-html = { path = "crates/html" } +craft-ipp = { path = "crates/ipp" } craft-heif = { path = "crates/heif" } craft-fig = { path = "crates/fig" } craft-fonts-build = { path = "crates/fonts-build" } +craft-gpu = { path = "crates/gpu" } +craft-gpu-null = { path = "crates/gpu-null" } +craft-gpu-providers = { path = "crates/gpu-providers" } +craft-gpu-wgpu = { path = "crates/gpu-wgpu" } craft-i18n = { path = "crates/i18n" } +craft-ipc = { path = "crates/ipc" } craft-idml = { path = "crates/idml" } craft-indd = { path = "crates/indd" } craft-jmap = { path = "crates/jmap" } craft-ical = { path = "crates/ical" } craft-jpeg = { path = "crates/jpeg" } -craft-jxl = { path = "crates/jxl" } +craft-control-protocol = { path = "crates/control-protocol" } +craft-jsonrpc = { path = "crates/jsonrpc" } +craft-mcp = { path = "crates/mcp" } +craft-jxl = { path = "crates/jxl", default-features = false } craft-kiwi = { path = "crates/kiwi" } craft-keymap = { path = "crates/keymap" } craft-assuan = { path = "crates/assuan" } @@ -93,9 +141,11 @@ craft-kra = { path = "crates/kra" } craft-audio = { path = "crates/audio" } craft-latex = { path = "crates/latex" } craft-markdown = { path = "crates/markdown" } +craft-macho = { path = "crates/macho" } 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-media-source = { path = "crates/media-source" } craft-materialx = { path = "crates/materialx" } craft-media-testkit = { path = "crates/media-testkit" } craft-midi = { path = "crates/midi" } @@ -112,33 +162,42 @@ craft-opc = { path = "crates/opc" } craft-openpgp = { path = "crates/openpgp" } craft-ora = { path = "crates/ora" } craft-pptx = { path = "crates/pptx" } +craft-ppt-binary = { path = "crates/ppt-binary" } craft-penpot = { path = "crates/penpot" } craft-pcraft-format = { path = "crates/pcraft-format" } craft-pcraft-bundle = { path = "crates/pcraft-bundle" } craft-pkcs7 = { path = "crates/pkcs7" } craft-plotter = { path = "crates/plotter" } craft-prepress = { path = "crates/prepress" } +craft-press-print = { path = "crates/press-print" } craft-print = { path = "crates/print" } craft-proof = { path = "crates/proof" } craft-raster-codecs = { path = "crates/raster-codecs" } craft-image-codecs = { path = "crates/image-codecs" } +craft-dds = { path = "crates/dds" } craft-psd = { path = "crates/psd" } craft-pst = { path = "crates/pst" } craft-quit = { path = "crates/quit" } craft-rtf = { path = "crates/rtf" } craft-raw = { path = "crates/raw" } +craft-geom = { path = "crates/geom" } +craft-develop = { path = "crates/develop" } +craft-develop-model = { path = "crates/develop-model" } craft-sheet = { path = "crates/sheet" } craft-sketch = { path = "crates/sketch" } craft-settings = { path = "crates/settings" } craft-scraft-format = { path = "crates/scraft-format" } craft-time = { path = "crates/time" } craft-silhouette-studio = { path = "crates/silhouette-studio" } +craft-suite-account = { path = "crates/suite-account" } craft-svg = { path = "crates/svg" } craft-stencilcraft-format = { path = "crates/stencilcraft-format" } craft-stencilcraft-document = { path = "crates/stencilcraft-document" } craft-svg-paths = { path = "crates/svg-paths" } craft-stream-codecs = { path = "crates/stream-codecs" } +craft-testkit = { path = "crates/testkit" } craft-text = { path = "crates/text" } +craft-tcraft = { path = "crates/tcraft" } craft-texture = { path = "crates/texture" } craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } @@ -158,6 +217,8 @@ craft-xcf = { path = "crates/xcf" } craft-xml = { path = "crates/xml" } craft-zip = { path = "crates/zip" } craft-y4m = { path = "crates/y4m" } +craft-sniff = { path = "crates/sniff" } +craft-tar = { path = "crates/tar" } craft-epub = { path = "crates/epub" } craft-ews = { path = "crates/ews" } craft-video = { path = "crates/video" } @@ -177,16 +238,20 @@ proptest = "1" encoding_rs = "0.8" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). chrono = { version = "0.4.45", default-features = false, features = ["std"] } +# Foundation crates for craft-gpu-wgpu. The versions match the ones the app repos already pin. +pollster = "0.4" +wgpu = { version = "30", default-features = false, features = ["std", "wgsl"] } [workspace.lints.rust] unsafe_code = "forbid" -unused_workspace_dependencies = "allow" unexpected_cfgs = { level = "warn", check-cfg = ["cfg(craft_pdf_unicode_fixtures)"] } +[workspace.lints.cargo] +unused_workspace_dependencies = "allow" + [workspace.lints.clippy] cognitive_complexity = "deny" too_many_arguments = "deny" -unused_workspace_dependencies = "allow" wildcard_imports = "deny" dbg_macro = "warn" todo = "warn" diff --git a/NOTICE b/NOTICE index 4fa5e4754..49bb9c0e4 100644 --- a/NOTICE +++ b/NOTICE @@ -108,6 +108,14 @@ Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. The format imp clean-room work based on their public specifications; dependency licences and X.Org's `rgb.txt` attribution are listed in ATTRIBUTION.md. +crates/develop (craft-develop) is moved from LightCraft, module by module: +- src/inpaint.rs and src/inpaint/ from crates/inpaint (lightcraft-inpaint), with its tests, revision a75497d6. + https://github.com/storytold/lightcraft + Copyright (c) 2026 ArtCraft Team and the LightCraft contributors. + That crate ports the inpainting (PatchMatch completion) and Poisson membrane fill code of PhotoCraft + (https://github.com/storytold/photocraft, crates/algo/src/inpaint.rs and poisson.rs), Copyright the PhotoCraft + contributors, MIT OR Apache-2.0; the port was modified by the LightCraft contributors (2026). + crates/raw (craft-raw) is moved from LightCraft, with behaviour ported from two other readers: - LightCraft, crates/raw (src/lib.rs, dng.rs, dngwrite.rs, tiffraw.rs, unpack.rs, ljpeg.rs, jxl.rs, opcodes.rs, profile.rs, gaintable.rs, semantic.rs, preview.rs, vendor/crw.rs, vendor/hasselblad.rs, @@ -254,11 +262,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 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. +vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs, +src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its manifest names Joe Neeman as author, and +its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/linesweeper/README.craft.md and +vendor/linesweeper/SOURCE.json for provenance, the local patches and the files left out. Platform lifecycle source provenance @@ -296,3 +303,126 @@ implementation, https://github.com/macosforge/alac at c38887c5c5e64a4b31108733bd (LICENSE-APACHE). The files are modified: translated to Rust, with bounds checks on hostile input, wrapping integer arithmetic, the unrolled predictor and per-width matrix routines folded into one, and the average bit rate filled in. Those files are Apache-2.0 only. + +JPEG encoding dependency: jpeg-encoder 0.6.1 + +Source: https://crates.io/crates/jpeg-encoder/0.6.1 +Declared license: (MIT OR Apache-2.0) AND IJG. +This software is based in part on the work of the Independent JPEG Group. + +The MIT license and unaltered upstream IJG and SIMD notices follow. The Apache-2.0 +alternative is also retained in licenses/jpeg-encoder-0.6.1 at the repository root. +The dependency is used unmodified; no encoder implementation is vendored here. + +LICENSE-MIT + +Copyright (c) 2021 Volker Ströbel + +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. +Original src/fdct.rs opening notice + +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ + +Original src/avx2/fdct.rs opening notice + +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/README.md b/README.md index c6e95bd4f..951298091 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ Craft App Libraries =================== Scanned by SonarCloud +Reviewed by CodeRabbit This repo contains libraries used by the various Craft Apps. It's a Rust monorepo workspace, and the libraries can be included by any Craft Apps that need them. @@ -61,6 +62,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit of compositions, layers, properties, keyframes, effects, masks, shapes, text and footage. Clean room, from EffectCraft. Mapping onto an app's document stays in the app. - [`craft-ai-core`](crates/ai-core/README.md): the data model and contract for AI in the Craft Apps (connections, models, tools, requests, jobs, consent, history, route spec). Pure, no I/O, wasm-safe. Contract in [docs/ai-shared-layer.md](docs/ai-shared-layer.md). +- [`craft-pe`](crates/pe/src/lib.rs): PE/COFF headers (`.exe`, `.dll`, `.sys`, `.efi`) from untrusted bytes, from Craft Anything: the COFF header, PE32/PE32+ optional header with its data directories bounded by the header's real size, the section table, RVA-to-file mapping and the decoded Rich header. - [`craft-pdf`](crates/pdf/README.md): independently optional PDF parsing, interpretation, rasterization and guarded authoring. Apps retain layout, fonts, editing and export policy; writer-only consumers do not enable the shared reader. - [`craft-pdn`](crates/pdn/README.md): Paint.NET documents (`.pdn`, PDN3), read: the layer list, blend modes and chunked gzip pixel blocks, with a data-only MS-NRBF (.NET binary serialization) reader. From PhotoCraft. @@ -68,6 +70,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-assuan`](crates/assuan/README.md): the Assuan protocol and gpg-agent's operations (key lookup, signing a digest, decrypting a session key) over any `Read + Write` stream, with a bounded canonical S-expression reader. No sockets; everything the agent sends is capped. - [`craft-affinity`](crates/affinity/README.md): bounded reader for native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): archive, object stream and a neutral document model with layers, artboards, vectors, text, tables, images and masks. Read only; mapping onto an app's document stays in the app. - [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite. +- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft. - [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from @@ -88,6 +91,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit black and white levels and as-shot white balance. The complete derivation record (plan, sources log, scripts, verification) is in `crates/crw/clean-room/`. Colour stays in each app. - [`craft-csv`](crates/csv/README.md): delimited text (CSV, TSV) and SYLK: encoding detection (UTF-8, UTF-16, Windows-1252 or Windows-1256), delimiter sniffing, a record parser with a cap on fields per record, field quoting for writers, and a SYLK (`.slk`) reader with R1C1 formulas rewritten to A1. +- [`craft-dds`](crates/dds/README.md): DirectDraw Surface (DDS) textures, read and written: the + top mip level of uncompressed, BC1 to BC3 (DXT1/3/5) and BC4/BC5 (grayscale data and normal + maps) textures, legacy and DX10 headers, and our own block encoder with optional mip chains. No dependencies (rayon behind `parallel`), so an + app that only exports textures needn't take the whole `craft-image-codecs` codec set and its + licences; `craft-image-codecs` reads and writes DDS through it. - [`craft-dialogs`](crates/dialogs/README.md): native file and message dialogs that never block the event loop: queued requests shown at the end of the frame and answered on a later frame, free-standing Open and Folder panels and Save sheets on macOS, case-insensitive filters. What @@ -108,6 +116,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit EMU units and `a:xfrm`, colours with theme slots and colour transforms, preset shape outlines (`a:prstGeom`), custom geometry with guide formulas (`a:custGeom`) and preset text warps (`a:prstTxWarp`). From DeckCraft. Takes `craft-xml` trees; packages stay with each format. +- [`craft-elf`](crates/elf/src/lib.rs): ELF program headers and dynamic section entries from untrusted bytes, from Craft Anything: 32- or 64-bit in either byte order, bounded counts and overflow-checked offsets, virtual-address-to-file mapping through `PT_LOAD`, and segment, permission and dynamic tag names. - [`craft-eps`](crates/eps/README.md): Encapsulated PostScript files as a container: the binary preview header (read and write), the DSC header comments and bounding boxes (also `(atend)`), the EPSI preview bitmap, ASCII85 data, and telling EPS, PostScript and Illustrator files @@ -120,6 +129,10 @@ 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-deckcraft-format`](crates/deckcraft-format/README.md): the DeckCraft `.deckcraft` package: + identity and sniffing, the `presentation.json` envelope with the presentation as a type + parameter, NaN-safe JSON and the reader for older files with `null` numbers, member names and + compression, and bounded, budgeted member reads. The presentation model and its mapping stay in DeckCraft. - [`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. @@ -172,6 +185,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit every frame's position, delay, disposal and transparent colour, the loop count and the first frame's colour table, without decompressing pixels. Tells an animation from a still and whether a file can hold the picture it declares before a decoder runs. +- [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook + (`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept + unread and written back into a list. The workbook model and what follows a read stay in GridCraft. - [`craft-hdr`](crates/hdr/src/lib.rs): Radiance HDR (RGBE) picture reader, from FilmCraft: flat, old and new run-length scan lines and all eight axis orders, to linear float RGB. Scan lines are validated before the picture is allocated. @@ -191,6 +207,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit Hasselblad 3FR/FFF, Minolta MRW, Epson ERF, Mamiya MEF, Kodak DCS, Pentax PEF, Samsung SRW, Canon CR2, Nikon NEF/NRW, Panasonic RW2, Fujifilm RAF, Olympus ORF (uncompressed), Sony ARW, Canon CR3 and Canon CRW (through `craft-crw`) so far; demosaicing and everything after stay with the develop pipeline. +- [`craft-render-parity`](crates/render-parity/README.md): test support for the shared develop + pipeline (#587): how far two renders of the same photo are apart (per-channel error, CIEDE2000, + the worst pixel) and whether that is within a stated tolerance. - [`craft-tga`](crates/tga/src/lib.rs): Truevision Targa, from FilmCraft (reader) and PhotoCraft (writer): true-colour, grayscale and colour-mapped pictures, raw or run-length encoded, any origin, to RGBA8, and a run-length writer whose packets end with their scan line. Bounded on @@ -227,6 +246,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit primitives (`.abr`, `.asl`, `.aco`, `.act`, `.ase`, `.grd`, `.pat`, `.atn`, `.csh`, `.shc`) and the Photoshop blocks of a layered TIFF. Bounded and panic-free on hostile input. Compositing and the mapping onto a document stay in each app. +- [`craft-ipc`](crates/ipc/README.md): Craft apps talking on one machine: per-user local sockets (Unix socket, Windows named pipe), token auth, instance discovery, launch on demand, focus hand-off, frame transfer and linked-file watching. Native only: it does not build for `wasm32`. Protocol in [PROTOCOL.md](crates/ipc/PROTOCOL.md). - [`craft-jmap`](crates/jmap/README.md): the JMAP protocol core (RFC 8620), from MailCraft, without 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 @@ -236,7 +256,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit 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 + from PhotoCraft: DDS (BC1 to BC3 read and write, BC4 and BC5 read), 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 panic-free on hostile input. Colour, orientation and the document mapping stay in each app. - [`craft-kiwi`](crates/kiwi/README.md): clean-room decoder and encoder for the kiwi binary schema @@ -250,11 +270,12 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit AC-3/E-AC-3, MP1/MP2, MP3 encoding), streaming and seeking, and packet decoding for any demuxer. See its README for formats and features. - [`craft-latex`](crates/latex/README.md): LaTeX documents read (the everyday subset) and written (a standalone article), to and from the craft-flow model. +- [`craft-macho`](crates/macho/src/lib.rs): Mach-O header pieces from untrusted bytes, from Craft Anything: universal (fat and fat64) slice tables checked against the file, CPU and load command names, the fixed size each load command needs before its fields are read, and the thread-state program counter. - [`craft-markdown`](crates/markdown/README.md): Markdown read and written (a CommonMark subset with GitHub tables and strikethrough), to and from the craft-flow model. - [`craft-math`](crates/math/README.md): equations as one tree (the Office Math object model) with its syntaxes, read and written: OMML, presentation MathML, LaTeX math and the UnicodeMath linear format. - [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV (`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`) and - MPEG-TS/PS (`mpegts`) demuxers, from FilmCraft, and an ISO BMFF box reader. Containers only; codecs are in `craft-audio`, and + MPEG-TS/PS (`mpegts`) demuxers, from FilmCraft, a Sierra VMD (`vmd`) demuxer, and an ISO BMFF box reader. Containers only; codecs are in `craft-audio`, and video codecs will go in a separate crate. - [`craft-lottie`](crates/lottie/README.md): Lottie (Bodymovin) JSON: the document model of lottie-spec 1.0 (animation, assets, layers by type, shape items, masks, effects, text, markers) @@ -267,9 +288,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit stay in each app. - [`craft-mesh`](crates/mesh/README.md): 3D mesh file formats behind one neutral model (meshes of polygons with per-corner indices, materials, a node hierarchy): STL, OBJ with MTL, PLY, - glTF 2.0 / GLB and 3MF, one feature each. Readers are bounded by `Limits`, never open a file themselves - glTF 2.0 / GLB and FBX, one feature each. Readers are bounded by `Limits`, never open a file themselves - and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft. + glTF 2.0 / GLB, FBX and 3MF, one feature each. Readers are bounded by `Limits`, never open a file + themselves and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft. - [`craft-midi`](crates/midi/README.md): Standard MIDI Files: a bounded reader for formats 0, 1 and 2 and a format-1 writer, over a neutral model of notes and channel events in ticks at 960 per quarter note. From SoundCraft. @@ -304,9 +324,14 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-plotter`](crates/plotter/README.md): cutter and pen-plotter command languages: HP-GL, DMPL and GP-GL (plain and the Silhouette dialect, three generations, registration marks) from a job in millimetres, plus the Silhouette device queries and reply parsers. No I/O. +- [`craft-ppt-binary`](crates/ppt-binary/README.md): the PowerPoint 97-2003 binary format (`.ppt`, `.pot`, `.pps`; + [MS-PPT], [MS-ODRAW]) read into `craft-pptx`, on `craft-cfb`. Import only. DeckCraft's reader. - [`craft-pptx`](crates/pptx/README.md): PresentationML, the model of a `.pptx` presentation: masters, layouts, slides, shapes, placeholders and their inheritance, transitions and animations, comments, sections, media and kept parts. From DeckCraft. DrawingML comes from `craft-drawingml`. +- [`craft-press-print`](crates/press-print/README.md): press-accurate printing: a PDF page separated + into plates by `craft-prepress`, composited into the printer's RGB profile and printed through + `craft-print`'s RGB transport, application-managed. - [`craft-print`](crates/print/README.md): PDF submission to CUPS and Windows, printer discovery, duplex/copies/colour and driver preferences. PDF generation stays in each app. - [`craft-proof`](crates/proof/README.md): proofing per language (spelling, suggestions, grammar, @@ -345,6 +370,13 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit check for drawing a tree with resvg. Apps take usvg from here, not as their own dependency. - [`craft-svg-paths`](crates/svg-paths/src/lib.rs): the former name of `craft-svg`'s `paths`, `color` and `write`; re-exports them for existing users. +- [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module + reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals + out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test + whose body runs past a limit, or whose condition does not hold in time; a variable the caller names + replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged + copies of a valid input, and fails the test with the case that panicked or did not finish. Not + published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). @@ -352,6 +384,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit 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; +- [`craft-ai`](crates/ai/README.md) *(spec)*: AI provider abstraction — BYO API keys (OpenAI-compatible) and one-click curated local models with capability probing, resumable checksummed downloads, and document segmentation that protects markup while translating prose; 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 (legacy character sets, quoted-printable, labels and Apple label groups, `KEY` certificates and @@ -379,13 +412,15 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit text-format crates read into and write from. WordCraft's model without its editing code. - [`craft-xlsx`](crates/xlsx/README.md): Excel workbooks (`.xlsx`, `.xlsm`, SpreadsheetML, transitional and strict) and binary workbooks (`.xlsb`) on `craft-opc`: the workbook part, shared strings, the styles tables and worksheet rows streamed one at a time, with limits on the package, the XML and the binary records. - [`craft-ora`](crates/ora/README.md): OpenRaster documents (`.ora`): the ZIP archive and the `stack.xml` layer tree as written, read with bounded sizes and written. From PhotoCraft. +- [`craft-sniff`](crates/sniff/src/lib.rs): what a file is from its first bytes: one dependency-free, wasm-safe signature table naming the format, its media type, extension and family for images, audio, video, 3D models, archives, compressed streams, executables and databases. Identifies only; parsing stays with each format's reader. +- [`craft-tar`](crates/tar/src/lib.rs): TAR (v7, ustar, GNU long names and base-256 sizes, local and global pax overrides) and cpio (newc, crc, odc) member walkers for hostile input, from Craft Anything: list each member, its kind, mode, link target and where its data lies, without extracting. Bounded by the input and a member cap; an optional `serde` feature serializes listings. - [`craft-y4m`](crates/y4m/src/lib.rs): YUV4MPEG2 (`.y4m`) reader, from FilmCraft: the stream header, colour space layouts at 8 to 16 bits, a frame index built from the `FRAME` lines without loading the file, and plane access. Bounded on hostile input. - [`craft-kra`](crates/kra/README.md): Krita documents (`.kra`, `.krz`), read: the ZIP archive, the `maindoc.xml` node tree as written, and the tiled pixel files with their LZF compression, a tile at a time. From PhotoCraft. - [`craft-xcf`](crates/xcf/README.md): GIMP XCF images (`.xcf`, `.xcf.gz`), read: header, properties, parasites, layers with their item paths, channels, and tiled pixels (uncompressed, RLE, zlib) at every precision, under a caller's byte budget. From PhotoCraft. - [`craft-xml`](crates/xml/README.md): bounded XML for hostile input: an owned element tree with limits on size, depth, nodes and attributes, streaming of repeated elements, namespace handling (as written, by local name, or canonical prefixes by URI), escaping and a writer. No DTDs and no entity expansion. -- [`craft-zip`](crates/zip/README.md): ZIP archives from untrusted files: an entry-count check before the archive is indexed (ZIP64 included), entry reads within per-entry and total budgets that count real bytes, duplicate-name detection, a strict structure preflight, and a deterministic stored/deflate writer. The shared ZIP layer for the package formats. +- [`craft-zip`](crates/zip/README.md): ZIP archives from untrusted files: an entry-count check before the archive is indexed (ZIP64 included), entry reads within per-entry and total budgets that count real bytes, duplicate-name detection, a strict structure preflight, and a deterministic stored/deflate writer. The shared ZIP layer for the package formats. With the `lenient` feature, also a reader of the raw bytes without the `zip` crate, from Craft Anything, for inspectors that must describe damaged archives rather than refuse them: the central-directory listing with ZIP64, prepended-stub and multi-volume checks, CP437 and Info-ZIP Unicode Path names, and entry reads (stored, DEFLATE, and bzip2, LZMA, XZ and Zstandard behind `lenient-*` features) checked against the declared size and CRC-32. - [Shared UI component audit](docs/ui-components-audit.md): source inventory, extraction priorities and compatibility boundaries across the Craft suite. - [Theme infrastructure](docs/theme-infrastructure.md): eight-app comparison and the small shared diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs index 05894f94e..efa618fb3 100644 --- a/crates/aaf/src/aaf.rs +++ b/crates/aaf/src/aaf.rs @@ -57,13 +57,56 @@ pub struct WriteOptions<'a> { /// reported. pub fn write(doc: &Document, opts: &WriteOptions<'_>, report: &mut Report) -> Result> { let version = if opts.small_sectors { craft_cfb::Version::V3 } else { craft_cfb::Version::V4 }; - write::write(doc, version, &opts.identity, report) + write::write(doc, version, &opts.identity, &ReferenceOptions::default(), report) +} + +/// Optional interpretation choices for applications retaining older interchange behavior. +#[derive(Clone, Copy, Debug)] +pub struct ReadOptions { + /// Interpret a source clip's start using its target slot's edit rate. + pub source_slot_rate: bool, + /// Use the referenced mob name when the clip has no explicit name. + pub infer_clip_name: bool, + /// Decode percent escapes in relative network locators. + pub decode_relative_locator: bool, + /// Report selector and nested-scope flattening. + pub report_flattening: bool, + /// Accept truncated PCM WAVE essence summaries. + pub permissive_pcm: bool, +} +impl Default for ReadOptions { + fn default() -> Self { + Self { source_slot_rate: true, infer_clip_name: true, decode_relative_locator: true, report_flattening: true, permissive_pcm: false } + } +} +/// Read using explicitly selected interpretation choices. +pub fn read_with_options(bytes: &[u8], options: &ReadOptions, report: &mut Report) -> Result { + read::read(bytes, options, report) +} + +/// Optional compatibility choices for writing source references and locators. +#[derive(Clone, Copy, Debug)] +pub struct ReferenceOptions { + /// Write source offsets in target-slot units. + pub source_slot_rate: bool, + /// Percent-encode relative locators. + pub encode_relative_locator: bool, +} +impl Default for ReferenceOptions { + fn default() -> Self { + Self { source_slot_rate: true, encode_relative_locator: true } + } +} +/// Write with explicitly selected reference and locator conventions. +pub fn write_with_references(doc: &Document, opts: &WriteOptions<'_>, references: &ReferenceOptions, report: &mut Report) -> Result> { + let version = if opts.small_sectors { craft_cfb::Version::V3 } else { craft_cfb::Version::V4 }; + write::write(doc, version, &opts.identity, references, report) } /// Read an AAF file: its top-level compositions, the compositions nested in them and their /// sources. What cannot be represented is skipped and named in `report`. pub fn read(bytes: &[u8], report: &mut Report) -> Result { - read::read(bytes, report) + read::read(bytes, &ReadOptions::default(), report) } /// Whether `bytes` look like an AAF file (a compound file whose root has the AAF root class or a diff --git a/crates/aaf/src/aaf/hostile_tests.rs b/crates/aaf/src/aaf/hostile_tests.rs index 853b0000c..527e50da8 100644 --- a/crates/aaf/src/aaf/hostile_tests.rs +++ b/crates/aaf/src/aaf/hostile_tests.rs @@ -108,3 +108,19 @@ fn objects_nested_too_deeply_are_an_error() { let e = store::read(&chain(250)).unwrap_err(); assert!(e.contains("nested too deeply"), "{e}"); } + +/// Many distinct property IDs still reject a duplicate without quadratic scanning. +#[test] +fn duplicate_after_many_distinct_properties_is_rejected() { + let mut props = vec![0x4C, 0x20]; + props.extend_from_slice(&8193u16.to_le_bytes()); + for id in (0..8192u16).chain(std::iter::once(7)) { + props.extend_from_slice(&id.to_le_bytes()); + props.extend_from_slice(&0x82u16.to_le_bytes()); + props.extend_from_slice(&0u16.to_le_bytes()); + } + let mut writer = Writer::new(Version::V3); + writer.stream(Writer::ROOT, "properties", props).unwrap(); + let e = store::read(&writer.finish()).unwrap_err(); + assert!(e.contains("duplicate property id"), "{e}"); +} diff --git a/crates/aaf/src/aaf/read.rs b/crates/aaf/src/aaf/read.rs index 31c841c5d..9739f87ba 100644 --- a/crates/aaf/src/aaf/read.rs +++ b/crates/aaf/src/aaf/read.rs @@ -67,6 +67,7 @@ fn indirect_f64(d: &[u8]) -> Option { struct R<'a> { report: &'a mut Report, + options: super::ReadOptions, mobs: HashMap, essence: HashMap, doc: Document, @@ -90,7 +91,7 @@ struct NestClip<'a> { /// Compositions nested deeper than this are read as gaps. const MAX_NESTING: usize = 16; -pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { +pub(crate) fn read(bytes: &[u8], options: &super::ReadOptions, report: &mut Report) -> Result { let root = store::read(bytes).map_err(|e| Error::Parse { format: "AAF", message: e })?; let header = root.strong(pid::ROOT_HEADER).ok_or_else(|| Error::Parse { format: "AAF", message: "no header object".into() })?; let content = header.strong(pid::CONTENT).ok_or_else(|| Error::Parse { format: "AAF", message: "no content storage".into() })?; @@ -106,7 +107,8 @@ pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { essence.insert(id, d); } } - let mut r = R { report, mobs, essence, doc: Document::default(), sources: HashMap::new(), nests: HashMap::new(), open: Vec::new() }; + let mut r = + R { report, options: *options, mobs, essence, doc: Document::default(), sources: HashMap::new(), nests: HashMap::new(), open: Vec::new() }; // Top-level compositions: those no other composition uses, among the ones tagged top-level // when any are. (Premiere Pro tags a nested sequence's composition top-level too; it is still // only a nested sequence.) Compositions that only use each other in a circle all count. The @@ -331,7 +333,9 @@ impl R<'_> { items } x if x == cls::SELECTOR => { - self.report.info("a selector was flattened to its selected input"); + if self.options.report_flattening { + self.report.info("a selector was flattened to its selected input"); + } match c.strong(pid::SELECTED) { Some(s) => { let mut items = self.segment(s, rate, kind, depth); @@ -342,7 +346,9 @@ impl R<'_> { } } x if x == cls::NESTED_SCOPE => { - self.report.info("a nested scope was flattened to its final input"); + if self.options.report_flattening { + self.report.info("a nested scope was flattened to its final input"); + } match c.objs(pid::NESTED_SLOTS).last() { Some(s) => { let mut items = self.segment(s, rate, kind, depth); @@ -388,7 +394,12 @@ impl R<'_> { let len = units_to_ticks(len_of(c), rate.0, rate.1); let tagged_name = tagged_values(c, pid::COMPONENT_USER_COMMENTS).into_iter().find(|(k, _)| k == "Clip Name").map(|(_, v)| v); let (Some(id), Some(slot)) = (c.mob_id(pid::SOURCE_ID), c.u32(pid::SOURCE_MOB_SLOT_ID)) else { return CItem::Filler(len) }; - let name = tagged_name.or_else(|| self.mobs.get(&id).and_then(|mob| mob.string(pid::MOB_NAME))).unwrap_or_default(); + let name = if self.options.infer_clip_name { + tagged_name.or_else(|| self.mobs.get(&id).and_then(|mob| mob.string(pid::MOB_NAME))) + } else { + tagged_name + } + .unwrap_or_default(); if id == [0; 32] { return CItem::Filler(len); } @@ -401,6 +412,7 @@ impl R<'_> { .and_then(|mob| mob.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(slot))) .and_then(|s| rate_of(s, pid::EDIT_RATE)) .unwrap_or(rate); + let source_rate = if self.options.source_slot_rate { source_rate } else { rate }; let start = units_to_ticks(c.i64(pid::START_TIME).unwrap_or(0), source_rate.0, source_rate.1); match self.resolve(id, slot, start, kind, master_key, 0) { Some((source, t)) => CItem::Clip(CClip { len, source, start: t, gain: None, name }), @@ -506,6 +518,7 @@ impl R<'_> { .and_then(|m| m.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(next_slot))) .and_then(|s| rate_of(s, pid::EDIT_RATE)) .unwrap_or(rate); + let source_rate = if self.options.source_slot_rate { source_rate } else { rate }; let inner = units_to_ticks(clip.i64(pid::START_TIME).unwrap_or(0), source_rate.0, source_rate.1); if next == [0; 32] { return None; @@ -545,7 +558,11 @@ impl R<'_> { DataKind::Sound => CKind::Sound, _ => kind, }; - let path = d.objs(pid::LOCATOR).iter().find_map(|l| l.string(pid::URL_STRING)).map(|u| locator_path(&u)); + let path = d + .objs(pid::LOCATOR) + .iter() + .find_map(|l| l.string(pid::URL_STRING)) + .map(|u| if self.options.decode_relative_locator { locator_path(&u) } else { craft_timeline::path::file_url_to_path(&u) }); let file_rate = rate_of(d, pid::SAMPLE_RATE).unwrap_or(rate); let length = d .i64(pid::FILE_LENGTH) @@ -604,7 +621,8 @@ impl R<'_> { if let Some(data) = self.essence.get(&id) { s.embedded = Some(data.to_vec()); // embedded essence may be a whole WAVE / AIFF file - if let Some((pcm, ch, sr, bits)) = crate::pcm::parse_wav(data) { + let pcm = if self.options.permissive_pcm { craft_audio::essence_pcm::parse_wav(data) } else { crate::pcm::parse_wav(data) }; + if let Some((pcm, ch, sr, bits)) = pcm { s.embedded = Some(pcm); s.file_channels = ch as u32; s.channels = if s.channel.is_some() { 1 } else { ch as u32 }; diff --git a/crates/aaf/src/aaf/store.rs b/crates/aaf/src/aaf/store.rs index 69b14fcf2..859c0ea77 100644 --- a/crates/aaf/src/aaf/store.rs +++ b/crates/aaf/src/aaf/store.rs @@ -461,11 +461,13 @@ impl R<'_> { if at > props.len() { return Err(bad("truncated property index")); } + // A properties stream can name tens of thousands of ids: do not rescan all earlier ids. + let mut seen = std::collections::HashSet::with_capacity(n); for i in 0..n { let (Some(pid), Some(sf), Some(len)) = (rd_u16(&props, 4 + i * 6), rd_u16(&props, 6 + i * 6), rd_u16(&props, 8 + i * 6)) else { return Err(bad("truncated property index")); }; - if o.props.iter().any(|(previous, _)| *previous == pid) { + if !seen.insert(pid) { return Err(bad("duplicate property id")); } let v = props.get(at..at + len as usize).ok_or_else(|| bad("truncated property value"))?; diff --git a/crates/aaf/src/aaf/tests.rs b/crates/aaf/src/aaf/tests.rs index 3e7794471..34eb2bbb3 100644 --- a/crates/aaf/src/aaf/tests.rs +++ b/crates/aaf/src/aaf/tests.rs @@ -557,3 +557,32 @@ fn relative_media_locator_round_trips_escaped_characters() { let got = read_clean(&bytes); assert!(got.sources.iter().any(|s| s.path.as_deref() == Some("Audio Files/100%20 #1.wav"))); } + +#[test] +fn compatibility_options_keep_relative_paths_and_parent_rate() { + let mut doc = crate::testdoc::sound_only(None); + doc.compositions[0].sample_rate = 44_100; + doc.sources[0].path = Some("Audio Files/100%20 #1.wav".into()); + let mut report = Report::default(); + let references = ReferenceOptions { source_slot_rate: false, encode_relative_locator: false }; + let bytes = write_with_references(&doc, &WriteOptions { identity: IDENTITY, small_sectors: false }, &references, &mut report).unwrap(); + let root = store::read(&bytes).unwrap(); + let mut all = Vec::new(); + walk(&root, &mut all); + assert!( + all.iter().filter(|o| o.class == cls::NETWORK_LOCATOR).any(|o| o.string(pid::URL_STRING).as_deref() == Some("Audio Files/100%20 #1.wav")) + ); + let starts: Vec = all.iter().filter(|o| o.class == cls::SOURCE_CLIP).filter_map(|o| o.i64(pid::START_TIME)).collect(); + assert!(starts.contains(&17_640), "parent rate start: {starts:?}"); + let opts = ReadOptions { + source_slot_rate: false, + infer_clip_name: false, + decode_relative_locator: false, + report_flattening: false, + permissive_pcm: true, + }; + let back = read_with_options(&bytes, &opts, &mut report).unwrap(); + assert!(back.sources.iter().any(|s| s.path.as_deref() == Some("Audio Files/100%20 #1.wav"))); + let clip = back.compositions[0].tracks[0].items.iter().find_map(|i| if let CItem::Clip(c) = i { Some(c) } else { None }).unwrap(); + assert_eq!(clip.start, FrameRate::FPS_25.tick_of(10)); +} diff --git a/crates/aaf/src/aaf/write.rs b/crates/aaf/src/aaf/write.rs index 8c9aae88e..1fcc6a332 100644 --- a/crates/aaf/src/aaf/write.rs +++ b/crates/aaf/src/aaf/write.rs @@ -75,6 +75,7 @@ fn definition(class: Auid, id: Auid, name: &str) -> Obj { struct W<'a> { report: &'a mut Report, inexact: bool, + references: super::ReferenceOptions, } struct IdGen { @@ -350,9 +351,15 @@ fn add_tape_mob(first: &Source, tape_id: [u8; 32], timecode: Option<(i64, FrameR } /// Serialise a composition document. -pub(crate) fn write(doc: &Document, version: craft_cfb::Version, identity: &Identity<'_>, report: &mut Report) -> Result> { +pub(crate) fn write( + doc: &Document, + version: craft_cfb::Version, + identity: &Identity<'_>, + references: &super::ReferenceOptions, + report: &mut Report, +) -> Result> { let comp = doc.compositions.first().ok_or(Error::Empty)?; - let mut w = W { report, inexact: false }; + let mut w = W { report, inexact: false, references: *references }; let mut ids = IdGen::for_document(doc, comp); let MediaOutput { mut mobs, essence, master_ref } = write_media(doc, &mut w, &mut ids); let mut used_ops: Vec = Vec::new(); @@ -360,7 +367,8 @@ pub(crate) fn write(doc: &Document, version: craft_cfb::Version, identity: &Iden // ---- nested compositions: a clip refers to one as it does to a master mob, through the // composition's first track of the clip's kind (a broken-out channel: that channel's track) - let mut refs = Refs { mobs: master_ref, rates: doc.sources.iter().enumerate().map(|(i, s)| (i, source_rate(s))).collect() }; + let rates = if references.source_slot_rate { doc.sources.iter().enumerate().map(|(i, s)| (i, source_rate(s))).collect() } else { HashMap::new() }; + let mut refs = Refs { mobs: master_ref, rates }; let nested_ids: Vec<[u8; 32]> = doc.nested.iter().map(|_| ids.next()).collect(); for (si, s) in doc.sources.iter().enumerate() { let Some((comp, id)) = s.nested.and_then(|n| Some((doc.nested.get(n)?, nested_ids.get(n)?))) else { continue }; @@ -795,8 +803,10 @@ fn descriptor(w: &mut W, s: &Source) -> Obj { if let Some(p) = &s.path { let url = if craft_timeline::path::is_absolute(p) { craft_timeline::path::path_to_file_url(p, false) - } else { + } else if w.references.encode_relative_locator { craft_timeline::path::encode_uri_path(p) + } else { + p.clone() }; d.set(pid::LOCATOR, Value::StrongVec(vec![Obj::new(cls::NETWORK_LOCATOR).data_prop(pid::URL_STRING, utf16z(&url))])); } diff --git a/crates/aaf/src/lib.rs b/crates/aaf/src/lib.rs index ee7448bc0..4968c5b39 100644 --- a/crates/aaf/src/lib.rs +++ b/crates/aaf/src/lib.rs @@ -29,7 +29,11 @@ mod roundtrip_tests; #[cfg(test)] mod testdoc; +/// Diagnostic types used by readers and writers. +pub use craft_timeline::report; pub use craft_timeline::report::Report; +/// Exact time types used by the composition model. +pub use craft_timeline::time; /// Error from a reader or writer. Unsupported *features* never error; they go in the [`Report`]. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] diff --git a/crates/aaf/src/omf.rs b/crates/aaf/src/omf.rs index 57e0f756c..bbd2e8571 100644 --- a/crates/aaf/src/omf.rs +++ b/crates/aaf/src/omf.rs @@ -21,7 +21,7 @@ //! transition's name) are not in the specification; they were first written by FilmCraft and keep //! their names so that existing files read back. -pub(crate) mod bento; +pub mod bento; mod read; mod write; diff --git a/crates/aaf/src/omf/bento.rs b/crates/aaf/src/omf/bento.rs index 00a7e2a26..171196fe1 100644 --- a/crates/aaf/src/omf/bento.rs +++ b/crates/aaf/src/omf/bento.rs @@ -35,8 +35,8 @@ use std::collections::{BTreeMap, HashMap}; -pub(crate) const MAGIC: [u8; 8] = [0xA4, b'C', b'M', 0xA5, b'H', b'd', b'r', 0xD7]; -pub(crate) const LABEL_SIZE: usize = 24; +pub const MAGIC: [u8; 8] = [0xA4, b'C', b'M', 0xA5, b'H', b'd', b'r', 0xD7]; +pub const LABEL_SIZE: usize = 24; // standard object ids const TOC_OBJECT: u32 = 1; @@ -82,7 +82,7 @@ const MAX_VALUE_BYTES: usize = 16 << 20; const MAX_NAME_BYTES: usize = 4 << 20; /// Builds a Bento container. -pub(crate) struct Writer { +pub struct Writer { data: Vec, names: HashMap<(u32, String), u32>, next: u32, @@ -90,6 +90,12 @@ pub(crate) struct Writer { entries: Vec<(u32, u32, u32, Vec)>, } +impl Default for Writer { + fn default() -> Self { + Self::new() + } +} + impl Writer { pub fn new() -> Writer { Writer { data: Vec::new(), names: HashMap::new(), next: MIN_USER_ID, entries: Vec::new() } @@ -217,9 +223,9 @@ pub(crate) struct Prop { } /// A parsed Bento container. -pub(crate) struct Container<'a> { +pub struct Container<'a> { data: &'a [u8], - pub objects: BTreeMap>, + pub(crate) objects: BTreeMap>, names: HashMap, by_name: HashMap, } @@ -229,11 +235,16 @@ fn be32(b: &[u8], at: usize) -> Option { } /// Whether `b` ends with a Bento label. -pub(crate) fn sniff(b: &[u8]) -> bool { +pub fn sniff(b: &[u8]) -> bool { b.len() >= LABEL_SIZE && b[b.len() - LABEL_SIZE..b.len() - LABEL_SIZE + 8] == MAGIC } impl<'a> Container<'a> { + /// Object identifiers in ascending order. + pub fn object_ids(&self) -> impl Iterator + '_ { + self.objects.keys().copied() + } + pub fn open(data: &'a [u8]) -> Result, String> { if !sniff(data) { return Err("no Bento label at the end of the file".into()); @@ -324,7 +335,7 @@ impl<'a> Container<'a> { } /// The bytes of a value. - pub fn value(&self, p: &Prop) -> Result, String> { + pub(crate) fn value(&self, p: &Prop) -> Result, String> { let total = p.segs.iter().try_fold(0usize, |total, s| { let len = match s { Seg::Imm(b) => b.len(), diff --git a/crates/aaf/src/omf/read.rs b/crates/aaf/src/omf/read.rs index d45b6ff63..9e892a0ce 100644 --- a/crates/aaf/src/omf/read.rs +++ b/crates/aaf/src/omf/read.rs @@ -12,6 +12,10 @@ type Uid = [u8; 12]; const MAX_REFERENCE_VISITS: usize = 65_536; +/// A source-clip search stopped at its work limit. +#[derive(Clone, Copy)] +struct SearchLimit; + struct R<'a, 'b> { c: &'b Container<'a>, report: &'b mut Report, @@ -21,15 +25,49 @@ struct R<'a, 'b> { media: HashMap>, doc: Document, sources: HashMap<(Uid, u32, String), usize>, + /// Component visits left for [`R::segment`] over the whole document. + budget: usize, + /// Outcome of the source-clip search under each segment: deterministic, so it is made once. + clip_search: HashMap, SearchLimit>>, + /// Visits and queued references left for source-clip searches over the whole document: + /// distinct roots over one shared graph would otherwise each search it in full. + search_budget: usize, } +/// Components one document may expand into timeline items; a small file can reference the same +/// sequence from many places and would otherwise multiply without bound. +const MAX_COMPONENT_VISITS: usize = 1_000_000; + +/// Reported when the shared component budget runs out. +const BUDGET_WARNING: &str = "OMF composition is too large to import completely (the remaining components are dropped)"; +/// Most visited components, and most queued references, one source-clip search may spend. +const MAX_CLIP_SEARCH_VISITS: usize = 100_000; +const MAX_CLIP_SEARCH_PENDING: usize = 1_000_000; +/// Work all source-clip searches in one document may spend together. +const MAX_DOCUMENT_SEARCH_WORK: usize = 2_000_000; + pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { + read_with_budget(bytes, report, MAX_COMPONENT_VISITS) +} + +fn read_with_budget(bytes: &[u8], report: &mut Report, budget: usize) -> Result { let perr = |m: String| Error::Parse { format: "OMF", message: m }; let c = Container::open(bytes).map_err(perr)?; let class_of = |o: u32| c.get(o, "OMFI:OOBJ:ObjClass").and_then(|v| v.get(..4).map(|b| [b[0], b[1], b[2], b[3]])); let head = c.objects.keys().copied().find(|&o| class_of(o) == Some(*b"HEAD")).ok_or_else(|| perr("no OMF header object".into()))?; let be = c.get(head, "OMFI:HEAD:ByteOrder").is_none_or(|v| v.first() != Some(&0x49)); - let mut r = R { c: &c, report, be, mobs: HashMap::new(), media: HashMap::new(), doc: Document::default(), sources: HashMap::new() }; + let mut r = R { + c: &c, + report, + be, + mobs: HashMap::new(), + media: HashMap::new(), + doc: Document::default(), + sources: HashMap::new(), + budget, + clip_search: HashMap::new(), + search_budget: MAX_DOCUMENT_SEARCH_WORK, + }; let mob_list = r.refs(head, "OMFI:HEAD:Mobs"); let mob_list = if mob_list.is_empty() { c.objects.keys().copied().filter(|&o| matches!(class_of(o).as_ref(), Some(b"CMOB" | b"MMOB" | b"SMOB"))).collect() @@ -66,8 +104,14 @@ pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { cmobs.iter().copied().filter(|m| r.uid(*m, "OMFI:MOBJ:MobID").is_none_or(|id| !referenced.contains(&id))).collect() }; for m in top { + // every composition spends from the budget too: a list of up to 65,535 repeated entries must not yield that many + if r.budget == 0 && !r.doc.compositions.is_empty() { + r.report.warn(BUDGET_WARNING); + break; + } let comp = r.composition(m); r.doc.compositions.push(comp); + r.budget = r.budget.saturating_sub(1); } if r.doc.compositions.is_empty() { return Err(Error::Empty); @@ -166,6 +210,13 @@ impl R<'_, '_> { let slots = self.refs(m, "OMFI:MOBJ:Slots"); let mut na = 0; for s in slots { + if self.budget == 0 { + self.report.warn(BUDGET_WARNING); + break; + } + // Every slot spends a unit, skipped ones too: a list of up to 65,535 repeated slots + // must not cost that much work in each of 65,535 repeated compositions. + self.budget -= 1; let Some(seg) = self.r#ref(s, "OMFI:MSLT:Segment") else { continue }; let rate = self.rational(s, "OMFI:MSLT:EditRate").filter(|r| r.0 > 0 && r.1 > 0).unwrap_or((25, 1)); let kind = self.data_kind(seg); @@ -213,13 +264,32 @@ impl R<'_, '_> { fn segment(&mut self, seg: u32, rate: (i64, i64), depth: usize) -> Vec { let len = units_to_ticks(self.len(seg), rate.0, rate.1); + // Depth alone does not bound a graph that references the same component many times at + // every level, so each visit also spends from a per-document budget. + // A visit stopped by depth spends from it too. + if self.budget == 0 { + self.report.warn(BUDGET_WARNING); + return vec![CItem::Filler(len)]; + } + self.budget -= 1; if depth > 32 { return vec![CItem::Filler(len)]; } match &self.class(seg) { b"SEQU" => { let mut out = Vec::new(); + let mut expanded = 0i64; for c in self.refs(seg, "OMFI:SEQU:Components") { + if self.budget == 0 { + // the rest of the sequence keeps its duration as one gap, not a gap per reference + self.report.warn(BUDGET_WARNING); + let rest = self.len(seg).saturating_sub(expanded); + if rest > 0 { + out.push(CItem::Filler(units_to_ticks(rest, rate.0, rate.1))); + } + break; + } + expanded = expanded.saturating_add(self.len(c)); out.extend(self.segment(c, rate, depth + 1)); } out @@ -306,12 +376,66 @@ impl R<'_, '_> { .find(|&s| self.r#ref(s, "OMFI:MSLT:TrackDesc").and_then(|t| self.u32(t, "OMFI:TRKD:TrackID")) == Some(track)) } - fn first_clip(&self, seg: u32) -> Option { - match &self.class(seg) { - b"SCLP" => Some(seg), - b"SEQU" => self.refs(seg, "OMFI:SEQU:Components").into_iter().find_map(|c| self.first_clip(c)), - _ => None, + /// First source clip under `seg`, depth-first; a sequence referencing itself (directly or + /// through a cycle) ends the search rather than the stack. `Err` when the search spent its + /// budget of visited components or queued references before finishing (the answer is unknown). + fn first_clip(&mut self, seg: u32) -> std::result::Result, SearchLimit> { + if let Some(found) = self.clip_search.get(&seg) { + return *found; } + let mut spent = 0; + let found = if self.search_budget == 0 { + Err(SearchLimit) + } else { + let visits = MAX_CLIP_SEARCH_VISITS.min(self.search_budget); + let pending = MAX_CLIP_SEARCH_PENDING.min(self.search_budget); + self.first_clip_within(seg, visits, pending, &mut spent) + }; + self.search_budget = self.search_budget.saturating_sub(spent); + self.clip_search.insert(seg, found); + found + } + + /// `spent` receives the visits plus queued references the search used. + fn first_clip_within(&self, seg: u32, max_visits: usize, max_pending: usize, spent: &mut usize) -> std::result::Result, SearchLimit> { + let mut visited = HashSet::new(); + let mut todo = vec![seg]; + let mut queued = 1usize; + let found = Self::search_from(self, &mut visited, &mut todo, &mut queued, max_visits, max_pending); + *spent = visited.len().saturating_add(queued); + found + } + + fn search_from( + &self, + visited: &mut HashSet, + todo: &mut Vec, + queued: &mut usize, + max_visits: usize, + max_pending: usize, + ) -> std::result::Result, SearchLimit> { + while let Some(seg) = todo.pop() { + if !visited.insert(seg) { + continue; + } + if visited.len() > max_visits { + return Err(SearchLimit); + } + match &self.class(seg) { + b"SCLP" => return Ok(Some(seg)), + b"SEQU" => { + let comps = self.refs(seg, "OMFI:SEQU:Components"); + // sequences may share one component list, so queued references grow with expansions, not visits + *queued = queued.saturating_add(comps.len()); + if *queued > max_pending { + return Err(SearchLimit); + } + todo.extend(comps.into_iter().rev()); + } + _ => {} + } + } + Ok(None) } fn resolve(&mut self, id: Uid, track: u32, start: Tick, master: Option, depth: usize) -> Option<(usize, Tick)> { @@ -328,7 +452,13 @@ impl R<'_, '_> { match &self.class(mob) { b"MMOB" => { let key = master.unwrap_or_else(|| id.iter().map(|b| format!("{b:02x}")).collect()); - let clip = self.first_clip(seg)?; + let clip = match self.first_clip(seg) { + Ok(c) => c?, + Err(SearchLimit) => { + self.report.warn("a master mob is too large to search for its source clip (imported as a gap)"); + return None; + } + }; let inner = units_to_ticks(self.i32(clip, "OMFI:SCLP:StartTime").unwrap_or(0), rate.0, rate.1); let next = self.uid(clip, "OMFI:SCLP:SourceID")?; let next_track = self.u32(clip, "OMFI:SCLP:SourceTrackID")?; @@ -353,7 +483,9 @@ impl R<'_, '_> { let file_rate = sr.filter(|r| r.0 > 0 && r.1 > 0).unwrap_or(rate); let length = units_to_ticks(self.i32(desc, "OMFI:MDFL:Length").unwrap_or(0), file_rate.0, file_rate.1); let summary = self.c.get(desc, "OMFI:WAVD:Summary").or_else(|| self.c.get(desc, "OMFI:AIFD:Summary")).unwrap_or_default(); - let fmt = crate::pcm::parse_wav(&summary).or_else(|| crate::pcm::parse_aiff(&summary)).map(|(_, ch, sr, bits)| (ch as u32, sr, bits)); + let fmt = craft_audio::essence_pcm::parse_wav(&summary) + .or_else(|| craft_audio::essence_pcm::parse_aiff(&summary)) + .map(|(_, ch, sr, bits)| (ch as u32, sr, bits)); let mut path = None; for l in self.refs(desc, "OMFI:MDES:Locator") { let p = match &self.class(l) { @@ -373,7 +505,8 @@ impl R<'_, '_> { let (file_channels, sample_rate, bits) = fmt.unwrap_or((1, file_rate.0 as u32, 16)); let channel = (file_channels > 1 && sound_slots > 1).then(|| track.saturating_sub(1).min(file_channels - 1)); // timecode of the physical source - let tc = self.first_clip(seg).and_then(|clip| { + let first = self.first_clip(seg).ok().flatten(); + let tc = first.and_then(|clip| { let tid = self.uid(clip, "OMFI:SCLP:SourceID")?; let tape = *self.mobs.get(&tid)?; let (start_tc, fps, trate) = self.refs(tape, "OMFI:MOBJ:Slots").into_iter().find_map(|s| { @@ -415,7 +548,7 @@ impl R<'_, '_> { nested: None, }; if let Some(d) = self.media.get(&id) { - if let Some((pcm, ch, sr, b)) = crate::pcm::parse_wav(d).or_else(|| crate::pcm::parse_aiff(d)) { + if let Some((pcm, ch, sr, b)) = craft_audio::essence_pcm::parse_wav(d).or_else(|| craft_audio::essence_pcm::parse_aiff(d)) { s.embedded = Some(pcm); s.file_channels = ch as u32; s.channels = if s.channel.is_some() { 1 } else { ch as u32 }; @@ -437,3 +570,200 @@ impl R<'_, '_> { } } } + +#[cfg(test)] +mod tests { + use super::super::bento::Writer; + use super::*; + + fn obj(w: &mut Writer, class: &[u8; 4]) -> u32 { + let id = w.new_object(); + w.set(id, "OMFI:OOBJ:ObjClass", "omfi:ClassID", class); + id + } + fn list(w: &mut Writer, o: u32, p: &str, targets: &[u32]) { + let mut v = (targets.len() as u16).to_be_bytes().to_vec(); + for t in targets { + v.extend_from_slice(&t.to_be_bytes()); + } + w.set(o, p, "omfi:ObjRefArray", &v); + } + + fn search(max_visits: usize, max_pending: usize, build: impl FnOnce(&mut Writer) -> u32) -> std::result::Result, SearchLimit> { + let mut w = Writer::new(); + let root = build(&mut w); + let bytes = w.finish(); + let c = Container::open(&bytes).unwrap(); + let mut report = Report::default(); + let r = R { + c: &c, + report: &mut report, + be: true, + mobs: HashMap::new(), + media: HashMap::new(), + doc: Document::default(), + sources: HashMap::new(), + budget: 0, + clip_search: HashMap::new(), + search_budget: MAX_DOCUMENT_SEARCH_WORK, + }; + r.first_clip_within(root, max_visits, max_pending, &mut 0) + } + + #[test] + fn clip_search_reports_its_limits() { + // found within the limits + assert!(matches!( + search(10, 10, |w| { + let (s, c) = (obj(w, b"SEQU"), obj(w, b"SCLP")); + list(w, s, "OMFI:SEQU:Components", &[c]); + s + }), + Ok(Some(_)) + )); + // too many distinct components before any clip + assert!( + search(5, 1000, |w| { + let (s, f) = (obj(w, b"SEQU"), (0..20).map(|_| obj(w, b"FILL")).collect::>()); + list(w, s, "OMFI:SEQU:Components", &f); + s + }) + .is_err() + ); + // few visits, but sequences that each queue a long list of references + assert!( + search(1000, 500, |w| { + let f = obj(w, b"FILL"); + let inner: Vec = (0..20).map(|_| obj(w, b"SEQU")).collect(); + for &i in &inner { + list(w, i, "OMFI:SEQU:Components", &[f; 100]); + } + let s = obj(w, b"SEQU"); + list(w, s, "OMFI:SEQU:Components", &inner); + s + }) + .is_err() + ); + // a search that ends without a clip is not a limit + assert!(matches!(search(10, 10, |w| obj(w, b"FILL")), Ok(None))); + } + + #[test] + fn skipped_slots_spend_the_budget() { + let mut w = Writer::new(); + let head = obj(&mut w, b"HEAD"); + let cm = obj(&mut w, b"CMOB"); + let slot = obj(&mut w, b"MSLT"); + list(&mut w, cm, "OMFI:MOBJ:Slots", &[slot; 200]); + list(&mut w, head, "OMFI:HEAD:Mobs", &[cm]); + list(&mut w, head, "OMFI:HEAD:PrimaryMobs", &[cm]); + let bytes = w.finish(); + let mut report = Report::default(); + read_with_budget(&bytes, &mut report, 50).unwrap(); + assert!(report.mentions(BUDGET_WARNING), "slots with no segment cost nothing before"); + } + + #[test] + fn a_source_clip_search_is_made_once_per_segment() { + let mut w = Writer::new(); + let (s, c) = (obj(&mut w, b"SEQU"), obj(&mut w, b"SCLP")); + list(&mut w, s, "OMFI:SEQU:Components", &[c]); + let bytes = w.finish(); + let c = Container::open(&bytes).unwrap(); + let mut report = Report::default(); + let mut r = R { + c: &c, + report: &mut report, + be: true, + mobs: HashMap::new(), + media: HashMap::new(), + doc: Document::default(), + sources: HashMap::new(), + budget: 0, + clip_search: HashMap::new(), + search_budget: MAX_DOCUMENT_SEARCH_WORK, + }; + let first = r.first_clip(s).ok(); + assert!(matches!(first, Some(Some(_)))); + assert_eq!(r.clip_search.len(), 1); + assert_eq!(r.first_clip(s).ok(), first); + assert_eq!(r.clip_search.len(), 1); + } + + #[test] + fn repeated_slots_and_compositions_spend_the_budget() { + let mut w = Writer::new(); + let head = obj(&mut w, b"HEAD"); + let cm = obj(&mut w, b"CMOB"); + let dd = obj(&mut w, b"DDEF"); + w.set(dd, "OMFI:DDEF:DataKindID", "omfi:UniqueName", b"omfi:data:Sound\0"); + let fill = obj(&mut w, b"FILL"); + w.set(fill, "OMFI:CPNT:DataKind", "omfi:ObjRef", &dd.to_be_bytes()); + let slot = obj(&mut w, b"MSLT"); + w.set(slot, "OMFI:MSLT:Segment", "omfi:ObjRef", &fill.to_be_bytes()); + list(&mut w, cm, "OMFI:MOBJ:Slots", &[slot; 200]); + list(&mut w, head, "OMFI:HEAD:Mobs", &[cm]); + list(&mut w, head, "OMFI:HEAD:PrimaryMobs", &[cm; 200]); + let bytes = w.finish(); + let mut report = Report::default(); + let doc = read_with_budget(&bytes, &mut report, 50).unwrap(); + let tracks: usize = doc.compositions.iter().map(|c| c.tracks.len()).sum(); + assert!(tracks <= 50, "{tracks} tracks from a budget of 50"); + assert!(doc.compositions.len() <= 2, "{} compositions", doc.compositions.len()); + assert!(report.has_warnings()); + } + + fn with_reader(bytes: &[u8], budget: usize, search_budget: usize, f: impl FnOnce(&mut R) -> T) -> (T, Report) { + let c = Container::open(bytes).unwrap(); + let mut report = Report::default(); + let mut r = R { + c: &c, + report: &mut report, + be: true, + mobs: HashMap::new(), + media: HashMap::new(), + doc: Document::default(), + sources: HashMap::new(), + budget, + clip_search: HashMap::new(), + search_budget, + }; + let out = f(&mut r); + (out, report) + } + + #[test] + fn depth_limited_components_spend_the_budget() { + // a chain 33 sequences deep whose last one repeats a depth-limited sequence many times + let mut w = Writer::new(); + let deep = obj(&mut w, b"SEQU"); + let chain: Vec = (0..33).map(|_| obj(&mut w, b"SEQU")).collect(); + for pair in chain.windows(2) { + list(&mut w, pair[0], "OMFI:SEQU:Components", &[pair[1]]); + } + list(&mut w, chain[32], "OMFI:SEQU:Components", &[deep; 1000]); + let bytes = w.finish(); + let (items, report) = with_reader(&bytes, 100, MAX_DOCUMENT_SEARCH_WORK, |r| r.segment(chain[0], (48_000, 1), 0)); + assert!(items.len() <= 100, "{} items from a budget of 100", items.len()); + assert!(report.mentions(BUDGET_WARNING)); + } + + #[test] + fn source_clip_searches_share_a_document_budget() { + // distinct roots over one shared clip-free graph + let mut w = Writer::new(); + let fills: Vec = (0..50).map(|_| obj(&mut w, b"FILL")).collect(); + let shared = obj(&mut w, b"SEQU"); + list(&mut w, shared, "OMFI:SEQU:Components", &fills); + let roots: Vec = (0..30).map(|_| obj(&mut w, b"SEQU")).collect(); + for &root in &roots { + list(&mut w, root, "OMFI:SEQU:Components", &[shared]); + } + let bytes = w.finish(); + let (results, _) = with_reader(&bytes, 0, 500, |r| roots.iter().map(|&root| r.first_clip(root)).collect::>()); + assert!(matches!(results[0], Ok(None)), "the first search fits"); + assert!(results.iter().any(|r| r.is_err()), "later searches run out of the shared budget"); + let (results, _) = with_reader(&bytes, 0, MAX_DOCUMENT_SEARCH_WORK, |r| roots.iter().map(|&root| r.first_clip(root)).collect::>()); + assert!(results.iter().all(|r| matches!(r, Ok(None)))); + } +} diff --git a/crates/aaf/src/pcm.rs b/crates/aaf/src/pcm.rs index 789c976a8..9992b2d3b 100644 --- a/crates/aaf/src/pcm.rs +++ b/crates/aaf/src/pcm.rs @@ -4,8 +4,3 @@ pub(crate) fn parse_wav(b: &[u8]) -> Option<(Vec, u16, u32, u16)> { craft_audio::wav_pcm(b).map(|p| (p.data, p.channels, p.sample_rate, p.bits)) } - -/// The same for an AIFF / AIFF-C (`NONE`, `twos`, `sowt`) file. -pub(crate) fn parse_aiff(b: &[u8]) -> Option<(Vec, u16, u32, u16)> { - craft_audio::aiff_pcm(b).map(|p| (p.data, p.channels, p.sample_rate, p.bits)) -} diff --git a/crates/aaf/tests/bento_api.rs b/crates/aaf/tests/bento_api.rs new file mode 100644 index 000000000..93adc33c1 --- /dev/null +++ b/crates/aaf/tests/bento_api.rs @@ -0,0 +1,27 @@ +use craft_aaf::omf::bento::{Container, Writer, sniff}; + +#[test] +fn external_consumer_reads_named_values_and_references() { + let mut writer = Writer::new(); + let first = writer.new_object(); + let second = writer.new_object(); + writer.set(first, "test:value", "test:type", b"long value"); + writer.set_references(first, &[second]); + let bytes = writer.finish(); + assert!(sniff(&bytes)); + let container = Container::open(&bytes).unwrap(); + assert!(container.object_ids().any(|id| id == first)); + assert_eq!(container.get(first, "test:value").as_deref(), Some(b"long value".as_slice())); + assert_eq!(container.resolve(first, second), second); + assert!(Container::open(&bytes[..bytes.len() - 1]).is_err()); +} + +#[test] +fn default_writer_builds_a_readable_empty_container() -> Result<(), String> { + let bytes = Writer::default().finish(); + let container = Container::open(&bytes)?; + let ids: Vec<_> = container.object_ids().collect(); + assert!(!ids.is_empty()); + assert!(ids.windows(2).all(|pair| pair[0] < pair[1])); + Ok(()) +} diff --git a/crates/affinity/README.md b/crates/affinity/README.md index 8567507e8..4a15037a5 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -115,11 +115,15 @@ text-frame fixture. against the limits below: grids of 16 million cells, grids and stories shared by many layers, 200 000 paragraphs, a document embedded hundreds of times, compounds that fan out or contain themselves, lists of a million null slots linked many times. -* `scripts/fetch-affinity-corpus.sh` fetches 51 public CC0/MIT/Apache-2.0 documents at pinned - commits, SHA-256 verified against `tests/support/corpus.tsv` (which names each file's source and - licence), with the upstream licence notices. Of these, 33 are current `.af`: four CC0 vector - illustrations and 28 original Affinity 3.2.3 feature probes plus one separately identified - derived regression input from [SethRobinson/Patchy](https://github.com/SethRobinson/Patchy) +* `scripts/fetch-affinity-corpus.sh` fetches 113 files at pinned commits, SHA-256 verified + against `tests/support/corpus.tsv` (which names each file's source and license): 90 public + CC0/MIT/Apache-2.0 documents, the 21 PNG files published with the + [satoshoe-dev/affinity-samples](https://github.com/satoshoe-dev/affinity-samples) documents, and + two upstream license notices. The manifest holds every name from the PhotoCraft and VectorCraft + corpus lists, so 21 files are fetched under two names. Of the documents, 55 are current `.af`: + four CC0 vector illustrations (each under two names), 18 CC0 Affinity 3.1.0 samples from + satoshoe-dev/affinity-samples, and 28 original Affinity 3.2.3 feature probes plus one separately + identified derived regression input from [SethRobinson/Patchy](https://github.com/SethRobinson/Patchy) (MIT). Only document data and provenance notices were inspected, never that project's importer or authoring scripts. The files are never committed. @@ -129,11 +133,14 @@ text-frame fixture. ``` Without `AFFINITY_CORPUS` the corpus tests are skipped. `AFFINITY_SAMPLES` names any other - folder of documents to parse. -* `tests/it/real_files.rs` parses every file and freezes the modelled features of all 33 current - `.af` files (`tests/support/affinity3-signatures.txt`: counts, fonts, artboards, warnings and a - CRC of the whole model). Native raster tests compare decoded pixels with independent embedded - images; text tests assert Unicode run boundaries, fallback fonts and feature retention. + folder of documents to parse. A corpus folder fetched for an older manifest fails the tests + until the script is run on it again. +* `tests/it/real_files.rs` checks the shape of every manifest row (four fields, a SHA-256, a + relative name listed once, a license and an `https` URL), parses every file and freezes the + modeled features of all 55 `.af` files (`tests/support/affinity3-signatures.txt`: counts, + fonts, artboards, warnings and a CRC of the whole model). Native raster tests compare decoded + pixels with independent embedded images; text tests assert Unicode run boundaries, fallback + fonts and feature retention. * `fuzz/` has `cargo-fuzz` targets for the whole reader (`container`) and the object stream (`stream`): diff --git a/crates/affinity/tests/it/real_files.rs b/crates/affinity/tests/it/real_files.rs index 18228bfc2..673173c80 100644 --- a/crates/affinity/tests/it/real_files.rs +++ b/crates/affinity/tests/it/real_files.rs @@ -22,8 +22,55 @@ fn files(dir: &Path, out: &mut Vec) { } fn samples() -> Option { - let pinned = corpus::pinned(); - std::env::var_os("AFFINITY_SAMPLES").map(PathBuf::from).or(pinned) + folder(std::env::var_os("AFFINITY_SAMPLES"), corpus::pinned) +} + +/// The `AFFINITY_SAMPLES` folder when one is given, without reading the pinned corpus; otherwise +/// the pinned corpus. +fn folder(samples: Option, pinned: impl FnOnce() -> Option) -> Option { + samples.map(PathBuf::from).or_else(pinned) +} + +#[test] +fn a_samples_folder_is_used_without_the_pinned_corpus() { + assert_eq!(folder(Some("samples".into()), || panic!("the pinned corpus was read")), Some(PathBuf::from("samples"))); + assert_eq!(folder(None, || Some(PathBuf::from("pinned"))), Some(PathBuf::from("pinned"))); + assert_eq!(folder(None, || None), None); +} + +#[test] +fn the_pinned_manifest_is_well_formed() { + let rows = corpus::rows(corpus::MANIFEST).unwrap(); + assert!(rows.iter().filter(|r| r.name.ends_with(".af")).count() >= 4); +} + +#[test] +fn the_manifest_check_rejects_malformed_rows() { + let digest = "0".repeat(64); + let url = "https://example.com/a.af"; + let row = |name: &str| format!("{digest}\t{name}\tMIT\t{url}\n"); + // Two names may share a digest. + assert!(corpus::rows(&(row("a.af") + &row("dir/b.af"))).is_ok()); + for (bad, why) in [ + (row("a.af") + &row("a.af"), "listed twice"), + (format!("{digest}\ta.af\tMIT\n"), "four tab-separated fields"), + (format!("{digest}\ta.af\tMIT\t{url}\textra\n"), "four tab-separated fields"), + (format!("{}\ta.af\tMIT\t{url}\n", "0".repeat(63)), "invalid SHA-256"), + (format!("{}\ta.af\tMIT\t{url}\n", "A".repeat(64)), "invalid SHA-256"), + (row("../a.af"), "relative path"), + (row("/a.af"), "relative path"), + (row("dir//a.af"), "relative path"), + (row("dir\\a.af"), "relative path"), + (row("C:a.af"), "relative path"), + (format!("{digest}\ta.af\t \t{url}\n"), "no license"), + (format!("{digest}\ta.af\tMIT\thttp://example.com/a.af\n"), "https"), + (format!("{digest}\ta.af\tMIT\thttps://\n"), "https"), + ] { + match corpus::rows(&bad) { + Ok(_) => panic!("accepted {bad:?}"), + Err(e) => assert!(e.contains(why), "{bad:?}: {e}"), + } + } } #[test] diff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txt index 79ed6df5e..f6b20d056 100644 --- a/crates/affinity/tests/support/affinity3-signatures.txt +++ b/crates/affinity/tests/support/affinity3-signatures.txt @@ -1,3 +1,21 @@ +affinity-samples/01-layer-effects.af dpi=72;spreads=1;model_crc32=9a2e65d6;counts={"depth": 2, "fills": 13, "gradients": 0, "layers": 12, "nodes": 38, "segments": 51, "shapes": 13, "strokes": 0, "subpaths": 13, "text_chars": 166, "text_runs": 13, "texts": 13};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["blur effects (left out)", "layer effects of other kinds (left out) (2×)", "paragraph leading of an unknown kind (imported as automatic) (13×)", "unknown layers attached to other layers (imported without them) (2×)"] +affinity-samples/02-adjustment-layers.af dpi=72;spreads=1;model_crc32=fc8b239f;counts={"depth": 2, "fills": 17, "gradients": 16, "layers": 8, "nodes": 42, "segments": 51, "shapes": 17, "strokes": 0, "subpaths": 17, "text_chars": 96, "text_runs": 9, "texts": 9, "unsupported": 8};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["adjustment layers (8×)", "paragraph leading of an unknown kind (imported as automatic) (9×)"] +affinity-samples/03-brush-strokes.af dpi=72;spreads=1;model_crc32=a492c413;counts={"depth": 1, "fills": 1, "gradients": 0, "hidden": 4, "images": 2, "nodes": 14, "segments": 15, "shapes": 7, "strokes": 6, "subpaths": 7, "text_chars": 107, "text_runs": 5, "texts": 5};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (5×)"] +affinity-samples/04-master-page.af dpi=300;spreads=3;model_crc32=ba260d8d;counts={"depth": 3, "fills": 1, "gradients": 0, "layers": 6, "master_instances": 3, "nodes": 30, "segments": 18, "shapes": 9, "strokes": 0, "subpaths": 9, "text_chars": 31, "text_runs": 3, "texts": 3, "unsupported": 9};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (3×)", "text fields such as page numbers (left out of the text)", "text whose story could not be read (master-page text, or an unknown layout) (9×)"] +affinity-samples/05-symbols.af dpi=72;spreads=1;model_crc32=fe74faa6;counts={"depth": 2, "fills": 5, "gradients": 0, "groups": 1, "layers": 3, "nodes": 40, "segments": 129, "shapes": 32, "strokes": 1, "subpaths": 32, "text_chars": 179, "text_runs": 4, "texts": 4};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (4×)"] +affinity-samples/06-special-shapes.af dpi=72;spreads=1;model_crc32=7e9a9eb3;counts={"depth": 1, "fills": 17, "gradients": 0, "nodes": 50, "segments": 268, "shapes": 33, "strokes": 16, "subpaths": 34, "text_chars": 182, "text_runs": 17, "texts": 17};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (17×)"] +affinity-samples/07-transparency.af dpi=72;spreads=1;model_crc32=6595042f;counts={"depth": 1, "fills": 18, "gradients": 1, "nodes": 26, "opacity": 1, "segments": 57, "shapes": 19, "strokes": 0, "subpaths": 19, "text_chars": 151, "text_runs": 7, "texts": 7};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["bitmap and pattern fills (left empty)", "paragraph leading of an unknown kind (imported as automatic) (7×)", "transparency gradients (imported without them) (2×)"] +affinity-samples/08-gradients.af dpi=72;spreads=1;model_crc32=5638db4d;counts={"depth": 1, "fills": 7, "gradients": 6, "nodes": 14, "segments": 27, "shapes": 7, "strokes": 0, "subpaths": 7, "text_chars": 97, "text_runs": 7, "texts": 7};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (7×)"] +affinity-samples/09-corners-stars.af dpi=72;spreads=1;model_crc32=e3528065;counts={"depth": 2, "fills": 9, "gradients": 0, "layers": 8, "nodes": 26, "segments": 81, "shapes": 9, "strokes": 0, "subpaths": 9, "text_chars": 122, "text_runs": 9, "texts": 9};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (9×)"] +affinity-samples/10-multiple-fills.af dpi=72;spreads=1;model_crc32=07d2e434;counts={"depth": 2, "fills": 7, "gradients": 3, "layers": 6, "nodes": 20, "segments": 21, "shapes": 7, "strokes": 3, "subpaths": 7, "text_chars": 140, "text_runs": 7, "texts": 7};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (7×)", "several fills or strokes on one object (only the active one is imported) (6×)"] +affinity-samples/11-text.af dpi=72;spreads=1;model_crc32=de077247;counts={"depth": 2, "fills": 13, "gradients": 0, "groups": 1, "layers": 1, "nodes": 28, "segments": 198, "shapes": 13, "strokes": 0, "subpaths": 18, "text_chars": 452, "text_runs": 11, "texts": 11, "unsupported": 2};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (10×)", "text fields such as page numbers (left out of the text) (2×)", "text frames with several columns (imported as one column)", "unknown layers (2×)"] +affinity-samples/12-cmyk8.af dpi=72;spreads=1;model_crc32=f40c0d8e;counts={"depth": 1, "fills": 31, "gradients": 1, "nodes": 41, "segments": 93, "shapes": 31, "strokes": 8, "subpaths": 31, "text_chars": 148, "text_runs": 10, "texts": 10};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (10×)"] +affinity-samples/12-grey8.af dpi=72;spreads=1;model_crc32=f40c0d8e;counts={"depth": 1, "fills": 31, "gradients": 1, "nodes": 41, "segments": 93, "shapes": 31, "strokes": 8, "subpaths": 31, "text_chars": 148, "text_runs": 10, "texts": 10};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (10×)"] +affinity-samples/12-lab16.af dpi=72;spreads=1;model_crc32=f40c0d8e;counts={"depth": 1, "fills": 31, "gradients": 1, "nodes": 41, "segments": 93, "shapes": 31, "strokes": 8, "subpaths": 31, "text_chars": 148, "text_runs": 10, "texts": 10};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (10×)"] +affinity-samples/12-rgb16.af dpi=72;spreads=1;model_crc32=f40c0d8e;counts={"depth": 1, "fills": 31, "gradients": 1, "nodes": 41, "segments": 93, "shapes": 31, "strokes": 8, "subpaths": 31, "text_chars": 148, "text_runs": 10, "texts": 10};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (10×)"] +affinity-samples/12-rgb32.af dpi=72;spreads=1;model_crc32=a9aeb9ab;counts={"depth": 1, "fills": 31, "gradients": 1, "nodes": 41, "segments": 93, "shapes": 31, "strokes": 8, "subpaths": 31, "text_chars": 148, "text_runs": 10, "texts": 10};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (10×)"] +affinity-samples/12-rgb8.af dpi=72;spreads=1;model_crc32=f40c0d8e;counts={"depth": 1, "fills": 31, "gradients": 1, "nodes": 41, "segments": 93, "shapes": 31, "strokes": 8, "subpaths": 31, "text_chars": 148, "text_runs": 10, "texts": 10};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (10×)"] +affinity-samples/13-blend-modes.af dpi=72;spreads=1;model_crc32=13f9c6d7;counts={"depth": 2, "fills": 13, "gradients": 6, "layers": 6, "nodes": 26, "segments": 45, "shapes": 13, "strokes": 0, "subpaths": 13, "text_chars": 169, "text_runs": 7, "texts": 7};boards=[];fonts={"Fira Sans:FiraSans-Regular:400:false"};warnings=["paragraph leading of an unknown kind (imported as automatic) (7×)"] affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"] affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"] affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"] @@ -31,3 +49,7 @@ patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "n patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"] patchy-vector.af dpi=72;spreads=1;model_crc32=3b16c7ed;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] +vector-art/mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"] +vector-art/mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"] +vector-art/mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"] +vector-art/playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"] diff --git a/crates/affinity/tests/support/corpus.rs b/crates/affinity/tests/support/corpus.rs index 21458a6f8..425aa7632 100644 --- a/crates/affinity/tests/support/corpus.rs +++ b/crates/affinity/tests/support/corpus.rs @@ -10,9 +10,56 @@ use sha2::{Digest, Sha256}; /// `sha256 name licence url` rows. pub const MANIFEST: &str = include_str!("corpus.tsv"); +/// One manifest row. +pub struct Row<'a> { + pub digest: &'a str, + pub name: &'a str, + pub license: &'a str, + pub url: &'a str, +} + +/// The rows of `manifest`. A row has exactly four tab-separated fields: a lowercase hexadecimal +/// SHA-256, a relative `/`-separated name without empty, `.` or `..` parts, a license and an +/// `https://` URL. Each name is listed once; several names may share a digest. +pub fn rows(manifest: &str) -> Result>, String> { + let mut seen = std::collections::BTreeSet::new(); + let mut rows = Vec::new(); + for line in manifest.lines().filter(|l| !l.trim().is_empty()) { + let cols: Vec<&str> = line.split('\t').collect(); + let &[digest, name, license, url] = cols.as_slice() else { + return Err(format!("corpus row needs four tab-separated fields: {line}")); + }; + if digest.len() != 64 || !digest.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) { + return Err(format!("{name}: invalid SHA-256 {digest:?}")); + } + if name.starts_with('/') + || name.contains(['\\', ':']) + || name.chars().any(char::is_control) + || name.split('/').any(|part| part.is_empty() || part == "." || part == "..") + { + return Err(format!("{name:?}: the name must be a relative path inside the corpus folder")); + } + if license.trim().is_empty() { + return Err(format!("{name}: no license")); + } + if !url.starts_with("https://") || url.len() == "https://".len() { + return Err(format!("{name}: the URL must use https: {url:?}")); + } + if !seen.insert(name) { + return Err(format!("{name}: listed twice")); + } + rows.push(Row { digest, name, license, url }); + } + Ok(rows) +} + +fn manifest() -> Vec> { + rows(MANIFEST).unwrap_or_else(|e| panic!("malformed corpus.tsv: {e}")) +} + /// The names of the pinned files. pub fn names() -> impl Iterator { - MANIFEST.lines().filter_map(|l| l.split('\t').nth(1)) + manifest().into_iter().map(|row| row.name) } pub fn pinned() -> Option { @@ -21,10 +68,7 @@ pub fn pinned() -> Option { return None; }; let mut count = 0; - for line in MANIFEST.lines().filter(|l| !l.trim().is_empty()) { - let mut cols = line.split('\t'); - let (Some(digest), Some(name)) = (cols.next(), cols.next()) else { panic!("malformed corpus row: {line}") }; - assert_eq!(digest.len(), 64, "invalid SHA256 for {name}"); + for Row { digest, name, .. } in manifest() { let bytes = std::fs::read(dir.join(name)).unwrap_or_else(|e| panic!("missing pinned Affinity file {name}: {e}")); let hex: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect(); assert_eq!(hex, digest, "{name}: pinned corpus modified; run scripts/fetch-affinity-corpus.sh"); diff --git a/crates/affinity/tests/support/corpus.tsv b/crates/affinity/tests/support/corpus.tsv index bf6bc4e22..2fab83b8f 100644 --- a/crates/affinity/tests/support/corpus.tsv +++ b/crates/affinity/tests/support/corpus.tsv @@ -7,10 +7,59 @@ e56c35f876277b101790ff4384cfde103a093ed6c81790a2d62176de21da339f afdesignload-re 08946c60c0da1c8aeea92d65acfb244721eeb3b480ed358609f4a48bbecfc5b9 afdesignload-shape_test.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/shape_test.afdesign 7306ab4fcbdc225d816f32a0d2aca15ac887053f60170459ac947e70f4ef343d afdesignload-slice_test.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/slice_test.afdesign e5d04bac0235af9386aea251cdd6903ed7810d335fdb6194d0483ea30b14e24a afdesignload-test_path.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/test_path.afdesign +cc8ca0db0d8fc545eb29153be900f153fa6b7b7eac068d05e54a502aba1264fe afdesignload/color.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/color.afdesign +9a17f500d09fb3b1a70d24aabdc2882955ec3eac3700a474549e6100be3a8484 afdesignload/layer_mode.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/layer_mode.afdesign +77ae60c02749224fe2c52691c951568138eaed5f8584ebc5da83715fae0234dd afdesignload/layer_test.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/layer_test.afdesign +04944918ff8e29c5c1b466b7e43c232f7ab80db15fb934080bbcd7baaf093e22 afdesignload/margins.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/margins.afdesign +35afa31b89f2b9970eb3701ee64e2a19476383637e8b07689334d6ffe556b593 afdesignload/raster_test.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/raster_test.afdesign +e56c35f876277b101790ff4384cfde103a093ed6c81790a2d62176de21da339f afdesignload/revision_test.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/revision_test.afdesign +08946c60c0da1c8aeea92d65acfb244721eeb3b480ed358609f4a48bbecfc5b9 afdesignload/shape_test.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/shape_test.afdesign +7306ab4fcbdc225d816f32a0d2aca15ac887053f60170459ac947e70f4ef343d afdesignload/slice_test.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/slice_test.afdesign +e5d04bac0235af9386aea251cdd6903ed7810d335fdb6194d0483ea30b14e24a afdesignload/test_path.afdesign MIT https://raw.githubusercontent.com/NickBeeuwsaert/AFDesignLoad/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns/test_path.afdesign +5f5b98f0ab2121f75f24362792c00cd5b610767820eb754b5660668f478b0c86 affinity-samples/01-layer-effects.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/01-layer-effects.af +33c1ad5022abc14e6136f4cb9fa0751c9778a0a564bc3abc2e0e6b051f7e00bb affinity-samples/01-layer-effects.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/01-layer-effects.png +4d19e95abe3423692f5bdfd0ede5bf3aebdd4bf16c32eaa304cead91a7a2e9b7 affinity-samples/02-adjustment-layers.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/02-adjustment-layers.af +726b7939e23a745f7578fa84188b56c2eb845cde28493499f1b18b4ede9b8a6e affinity-samples/02-adjustment-layers.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/02-adjustment-layers.png +c6ca86439c89d83ba43c76e9d783865ac09ca0ff524d5b347caa77f473caac98 affinity-samples/03-brush-strokes.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/03-brush-strokes.af +e57e36ffffdd88d3a62ebdb142435d7d3056286b22130f459c404a3ef529f61f affinity-samples/03-brush-strokes.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/03-brush-strokes.png +e3bf04f7cc02e1d49ec79503f2b4044f385de1e890bd461013a5a6fca09b5223 affinity-samples/04-master-page.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/04-master-page.af +246279f00d1f08917409b34e60359bd3bba158bcf4e8d5847a806f575d8eb98f affinity-samples/04-master-page_1.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/04-master-page_1.png +0e023792ce89f724b1dfedb6360556348309e483c23e32b91d87afab5d64c9cc affinity-samples/04-master-page_2.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/04-master-page_2.png +f431b15027e20ab760c4d241aa6981130560409cb270bbc6d4dd9241d1883f0a affinity-samples/04-master-page_3.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/04-master-page_3.png +ef779b58a6721001ee961b42eacb96fb47dcaa35ccb7e6ccf2ec6f33106070b2 affinity-samples/05-symbols.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/05-symbols.af +6675fc4a1563f61b7fcaa64978447e0fa6e1b0bb8073b4e63f958db1cf726fef affinity-samples/05-symbols.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/05-symbols.png +9e463b4d1ca8e7a1b67b3c30351a28af8ed05b9cd11f3cea2159319c9974bc67 affinity-samples/06-special-shapes.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/06-special-shapes.af +a897c607631acbea31c5a926af6ca20c0acb2744636003b8c9ef07861752d947 affinity-samples/06-special-shapes.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/06-special-shapes.png +3aba0d83055f09da4dba465a3abf66c77d4362dc6060548e54db943029b3996e affinity-samples/07-transparency.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/07-transparency.af +3b73945b7302627caf679a961053f30a9593bab7d709e27acb1df54dadc53968 affinity-samples/07-transparency.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/07-transparency.png +4292c1571b6c8c19b80c530602ca21d5996df7b99221639a4cde76d8307ffbcb affinity-samples/08-gradients.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/08-gradients.af +f6fb427c9715ea193e595d0c441b462224971fcda2aa2b4d8b71631d0f59f992 affinity-samples/08-gradients.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/08-gradients.png +c913882b3bea7a4218aa88e96890181cdc08ce37f0859196a1ad1828be78b347 affinity-samples/09-corners-stars.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/09-corners-stars.af +068bcc7599336a174d7ce87962da414ccf429d549484ccbe8f68f669779d84d0 affinity-samples/09-corners-stars.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/09-corners-stars.png +f03e797d6dbf8a31eab9d0b9cf9a8bddcc8440c6003863f31d97fe23c195c4b2 affinity-samples/10-multiple-fills.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/10-multiple-fills.af +e1951aa6d8acdbeccc281b6a20a03df9b257c0d739aa5f6aec27c105151fef3f affinity-samples/10-multiple-fills.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/10-multiple-fills.png +6da8b59b40d0e082435c5a2004c50fa90e3c4f15c3a02763b8edf84b8b9f4506 affinity-samples/11-text.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/11-text.af +bb2040cda017cb753d0594416ac0501a1049bc333a7cf2c1c832356e2bbe1a45 affinity-samples/11-text.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/11-text.png +0c13cfe0f716902199775251b0983f28d60a64c1f79d3c6f496f2c019365bdb5 affinity-samples/12-cmyk8.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-cmyk8.af +cfef257c50201968121332e8ae12a7fe2ecdcc3bce1faeb5e581751662098c05 affinity-samples/12-cmyk8.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-cmyk8.png +03d4cfe5ce4b80833d83de89848e88639056e8984c049865c8f29b9ef41b40e5 affinity-samples/12-grey8.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-grey8.af +855e4f08f21c60f1d2080c9533b98f99c7a635c5804abf8ec9d6ee1a29029cef affinity-samples/12-grey8.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-grey8.png +9adc0d4242b5448ac84aef886bd7afc165e1959015125ce21bf402ddb65caba1 affinity-samples/12-lab16.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-lab16.af +6c30cef8304fd08539d631988280a6b3bc8570db3f1425fa771d83c1591dfc8d affinity-samples/12-lab16.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-lab16.png +26b47861275b2f83517e7d42ec051efc3cd22956440784b6df0bc016ecb0e008 affinity-samples/12-rgb16.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-rgb16.af +967ba0cb7d93496a7e454dcc37013c1b19089cc283c7e08f2dea7023ad330e80 affinity-samples/12-rgb16.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-rgb16.png +36e62b0de8488712c04831ba3ef466da68bf080ec3caf9fbe6646905d3fb87e8 affinity-samples/12-rgb32.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-rgb32.af +0ebcf7211447d64158c21c27eeb19b8737cb2cdcc708dcdf3b4fed5041b449e9 affinity-samples/12-rgb32.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-rgb32.png +4d210ce4724409fb6c9715046ad9efa0049442f8324a21174068a02c6df10632 affinity-samples/12-rgb8.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-rgb8.af +4e4dda966c337119165ba5d88cb3d4af10bf6507b9a69986d33060a8eeb37c21 affinity-samples/12-rgb8.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/12-rgb8.png +b84815dbb5e3a7f7842d860acb888f93dbd1f949bcb6a3bf858515b85ea3c3b7 affinity-samples/13-blend-modes.af CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/13-blend-modes.af +a49d2fe6043002aef4f4c6b8cf64a04838d21cf29795324c02fb1772d5519a21 affinity-samples/13-blend-modes.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/13-blend-modes.png +b73eceb73a45df1a424d60164b7e1b521b9f01f56fe86159e477b49c9cd90f78 affinity-samples/source/07-texture.png CC0-1.0 https://raw.githubusercontent.com/satoshoe-dev/affinity-samples/96aca6bd86bbe7a677f1cf0630bd832d23943be8/source/07-texture.png c499cf3ca73cf7cd3e2e65bed048d1b8ecf03e7167b74d54f0ae6db31868cab8 affinity3-mexican-guy.af CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/mexican-guy.af 730e3fae51d9044ada58f51c7b5f9327d99e8d62376453bc251d0d26cda47743 affinity3-mexican-man.af CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/mexican-man.af 5f5fccc0bd8be2bb3b2a07461ec77a012a61eef1883485d7c80f72d4383231ce affinity3-mexican-woman.af CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/mexican-woman.af 0a52bb923c949c566a4339b996bce1a67b683f61def1a73dfefb910effaa450d affinity3-playing-cards.af CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/playing-cards.af +e1b121d7c3d02356baa5dea512f5aa1fe77249c28d7b227e29cab2bc67ec323a asset-store-template/AssetStore.aftemplate MIT https://raw.githubusercontent.com/eviltwo/AssetStoreTemplate/f671981ee89d15526285b3cc87b4393d3defe644/AssetStoreTemplate/AssetStore.aftemplate 87a7bd93de16c404f6c6dd9cdebff96ec47832a3b342d2ce0af73d9a87e209e0 designer-beer.afdesign CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/beer.afdesign 09ba790c428e8e09dc0b9ddebb4f3db6daefaa2af1da492ee34e73fba1b8af69 designer-cactus.afdesign CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/cactus.afdesign c3bcd0395b407493bc9d2877d424029b70f0e4c817a56e893f7ac74973df52e5 designer-car.afdesign CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/car.afdesign @@ -19,6 +68,8 @@ c3bcd0395b407493bc9d2877d424029b70f0e4c817a56e893f7ac74973df52e5 designer-car.af e1b121d7c3d02356baa5dea512f5aa1fe77249c28d7b227e29cab2bc67ec323a eviltwo-AssetStore.aftemplate MIT https://raw.githubusercontent.com/eviltwo/AssetStoreTemplate/f671981ee89d15526285b3cc87b4393d3defe644/AssetStoreTemplate/AssetStore.aftemplate fbb196e918e302c16f8de9f2e6dffaef70ab3c317b32a9f44607fd4b2ead0206 jac21-SimpleLogo.afdesign MIT https://raw.githubusercontent.com/Jac21/Branding/57ae3f45bf4637f6927c0b07de25b922c55f944f/Logos/JC/DesignerFiles/Affinity/SimpleLogo.afdesign 9d874245936483de3ec04cca48b383028d33666801dff1814246a44e695e29b8 jac21-SimpleLogoBanner.afdesign MIT https://raw.githubusercontent.com/Jac21/Branding/57ae3f45bf4637f6927c0b07de25b922c55f944f/Logos/JC/DesignerFiles/Affinity/SimpleLogoBanner.afdesign +fbb196e918e302c16f8de9f2e6dffaef70ab3c317b32a9f44607fd4b2ead0206 jac21/SimpleLogo.afdesign MIT https://raw.githubusercontent.com/Jac21/Branding/57ae3f45bf4637f6927c0b07de25b922c55f944f/Logos/JC/DesignerFiles/Affinity/SimpleLogo.afdesign +9d874245936483de3ec04cca48b383028d33666801dff1814246a44e695e29b8 jac21/SimpleLogoBanner.afdesign MIT https://raw.githubusercontent.com/Jac21/Branding/57ae3f45bf4637f6927c0b07de25b922c55f944f/Logos/JC/DesignerFiles/Affinity/SimpleLogoBanner.afdesign ec1072cb03fcd0ed7ac1dfc7e087f4920df545fe9c84a386a7dac2fd33fbbe1f leakcanary-vector_icon.afdesign Apache-2.0 https://raw.githubusercontent.com/square/leakcanary/00880a8fb66eb4046a0124bff8303a04874bc07e/docs/assets/vector_icon.afdesign bbc50c8c376e0e5980939be7df6769feed1a30289c7efc6391b204dfb15de88d patchy-LICENSE.txt MIT https://raw.githubusercontent.com/SethRobinson/Patchy/de84eab550758b30fa062e479f5778cce7693b73/LICENSE 150e423be0c5eb22f252a38c2de68ab3ccec7e20bfba166f7ddd622ac243d8f4 patchy-NOTICE.txt MIT https://raw.githubusercontent.com/SethRobinson/Patchy/de84eab550758b30fa062e479f5778cce7693b73/NOTICE-THIRD-PARTY.md @@ -51,3 +102,12 @@ a5ccb62ee8d7e36d1a19a037aba989a5ba0232767e9f3305f7d9f7d4603291dd patchy-text-rot 87e1dee23769932b7e414116233063a8d68726cbffdebb975b3cd0ef447c602a patchy-transform.af MIT https://raw.githubusercontent.com/SethRobinson/Patchy/de84eab550758b30fa062e479f5778cce7693b73/test-fixtures/af/tiny-transform.af fa5dd80f44ae0712a9888c62953fd442a28119034d343db93b7892d5d2a61328 patchy-vector-mask.af MIT https://raw.githubusercontent.com/SethRobinson/Patchy/de84eab550758b30fa062e479f5778cce7693b73/test-fixtures/af/tiny-vector-mask.af 8ab1995ecbd9306ebcb7a4d2cd81701f34401e67f08b242f14dc3e3d04c94803 patchy-vector.af MIT https://raw.githubusercontent.com/SethRobinson/Patchy/de84eab550758b30fa062e479f5778cce7693b73/test-fixtures/af/tiny-vector.af +87a7bd93de16c404f6c6dd9cdebff96ec47832a3b342d2ce0af73d9a87e209e0 vector-art/beer.afdesign CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/beer.afdesign +09ba790c428e8e09dc0b9ddebb4f3db6daefaa2af1da492ee34e73fba1b8af69 vector-art/cactus.afdesign CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/cactus.afdesign +c3bcd0395b407493bc9d2877d424029b70f0e4c817a56e893f7ac74973df52e5 vector-art/car.afdesign CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/car.afdesign +112562bc91e7cccf003d34364430544208373c4fb4bb4ab9acdaf27cf0125047 vector-art/flowers.afdesign CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/flowers.afdesign +023531b8216f2d4da24ab715e3b313506712e50d5f5bf7da927f434def1d0ea2 vector-art/lion-track.afdesign CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/lion-track.afdesign +c499cf3ca73cf7cd3e2e65bed048d1b8ecf03e7167b74d54f0ae6db31868cab8 vector-art/mexican-guy.af CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/mexican-guy.af +730e3fae51d9044ada58f51c7b5f9327d99e8d62376453bc251d0d26cda47743 vector-art/mexican-man.af CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/mexican-man.af +5f5fccc0bd8be2bb3b2a07461ec77a012a61eef1883485d7c80f72d4383231ce vector-art/mexican-woman.af CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/mexican-woman.af +0a52bb923c949c566a4339b996bce1a67b683f61def1a73dfefb910effaa450d vector-art/playing-cards.af CC0-1.0 https://raw.githubusercontent.com/samuel-etver/vector-art/255f8add3c8f0740196e22bd59502b811b532f0b/simple/playing-cards.af diff --git a/crates/ai/Cargo.toml b/crates/ai/Cargo.toml new file mode 100644 index 000000000..cca808c9c --- /dev/null +++ b/crates/ai/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "craft-ai" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +description = "AI provider abstraction for the Craft suite — BYO API keys and one-click local models" + +[lints] +workspace = true + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +dirs = "7" +sysinfo = "0.39" +ureq = { version = "3", features = ["json"] } +sha2 = "0.11" +candle-core = { version = "0.9", optional = true } +candle-nn = { version = "0.9", optional = true } +candle-transformers = { version = "0.9", optional = true } +tokenizers = { version = "0.22", optional = true, default-features = false, features = ["onig"] } + +[features] +# Local GGUF inference on candle. Heavy dependency tree; apps opt in. +local = ["dep:candle-core", "dep:candle-nn", "dep:candle-transformers", "dep:tokenizers"] + +[dev-dependencies] +tempfile = "3" diff --git a/crates/ai/README.md b/crates/ai/README.md new file mode 100644 index 000000000..90170c8eb --- /dev/null +++ b/crates/ai/README.md @@ -0,0 +1,145 @@ +# craft-ai — AI providers for the Craft suite + +Shared AI abstraction for every Craft app: translation, rewriting, summaries, +vision captions — one crate, one settings store, one model cache. + +Status: **spec** — this file is the contract; implementation follows. + +## The feature this powers + +A per-app **AI tab** offering document-wide operations — the flagship being +"translate this whole document" — backed by either: + +1. **BYOT** — the user's own API token against an OpenAI-compatible endpoint + (OpenAI, Azure, Ollama, LM Studio, any compatible proxy), or +2. **Local model** — a one-click download of a curated open model, chosen for + the machine it's running on. + +The user experience is deliberately *informed*: every step reports what is +happening, why this model was picked, what it will cost in disk/RAM, and that +nothing leaves the machine in local mode. + +## Modules + +### `probe` — capability detection + +Runs once, caches the result: + +| Signal | Source | +| --- | --- | +| Total/free RAM | `sysinfo` or `std::alloc`-safe OS calls | +| CPU threads + features | `std::thread`, `is_x86_feature_detected!` (AVX2 gates Q4 speed) | +| GPU + VRAM | `wgpu` adapter info (apps already link wgpu — reuse, don't re-probe) | +| Free disk at the model cache dir | `fs2`/`std::fs` | +| Network reachability | optional HEAD to the model host, skipped offline | + +Output: `MachineCaps { ram_gb, vram_gb, threads, avx2, disk_free_gb }`. + +### `registry` — the curated model list + +A small hand-maintained table (Rust consts, not runtime-fetched — supply +chain stays auditable). Each entry: `id`, display name, HF repo + file, +`sha256`, size, min RAM, recommended RAM, license id, quality tier, +languages covered. + +Curation rule — **permissive licenses only** (the suite is MIT OR Apache-2.0 +and commercial users run it): + +- ✅ Qwen2.5-0.5B / 1.5B / 3B Instruct (Apache-2.0) +- ✅ SmolLM2-1.7B (Apache-2.0) +- ✅ Gemma-3 (Gemma Terms — allowed, flag in UI) +- ✅ Helsinki-NLP opus-mt-* per-language pairs (CC-BY/MIT) +- ❌ NLLB-200, M2M-100 — CC-BY-NC, excluded +- ❌ Llama-* — custom license acceptable? default: exclude until reviewed + +`registry::suggest(&caps)` picks the best fitting model: prefers 3B when +VRAM ≥ 6 GB or RAM ≥ 16 GB, falls to 1.5B at 8 GB, 0.5B below. Always shows +alternatives — the suggestion is a default, not a cage. + +### `provider` — inference backends + +```rust +trait Provider { + fn name(&self) -> &str; + fn complete(&self, prompt: &str, opts: &GenOpts) -> Result; + fn test(&self) -> Result; +} +``` + +- `OpenAiCompat` — POST `/v1/chat/completions`, configurable endpoint+token+ + model. Covers OpenAI, Ollama (`http://localhost:11434/v1`), LM Studio, + Groq, OpenRouter… Token stored via the OS keyring (`keyring` crate) or a + 0600-permissioned config file — never in project files, never logged. +- `LocalGguf` — GGUF inference. First implementation target: **candle** + (pure Rust, Apache/MIT — keeps the no-C++ toolchain rule). `llama-cpp-2` + stays a possible perf upgrade later, gated behind a feature flag. + +### `fetch` — one-click download + +- Resumable HTTP GET (range requests), streamed to `*.part` then renamed — + a half-downloaded GGUF can never be mistaken for a valid one. +- SHA-256 checked against the registry entry; mismatch = hard fail, delete. +- Progress events (`Download { bytes_done, bytes_total, bytes_per_sec }`) + feed the UI's live status line. +- Cache dir is **shared across the suite**: + `%LOCALAPPDATA%\artcraft\models` (Windows), `~/Library/Application + Support/artcraft/models` (macOS), `~/.cache/artcraft/models` (Linux). + +### `translate` — document segmentation + +The model is the easy part; the hard part is *what not to touch*. The +translator walks the document as segments, not raw text: + +- **Protected**: LaTeX commands/envs/math (`\cite{…}`, `$…$`), code fences, + placeholders (`{count}`), URLs, citation keys, markup tags. +- **Translated**: prose runs, captions, headings, table cells. +- Per-app adapters declare the grammar: TexCraft protects `\command{…}` and + math mode; WordCraft protects field codes; MatCraft protects code. +- Batch-friendly: segments → prompt with numbered items → parse numbered + output; verify count matches, retry split halves on mismatch. +- Deterministic options: temperature 0-ish, glossary hook (`HashMap`) applied post-hoc. + +## The AI tab (per app, `ui-egui/src/ai.rs`) + +First-open flow — the "smooth informed" sequence: + +1. Two cards: **Use an API provider** / **Run on this PC**. +2. BYOT card: endpoint, token, model fields + **Test connection** → green + check with model list echo. +3. Local card: **Detect this PC** → probe runs → + `Suggested: Qwen2.5-1.5B-Instruct (Q4_K_M, 1.1 GB) — fits your 16 GB RAM; + est. ~8 tok/s` with an "Other models ▸" disclosure showing the registry. +4. **Download** → progress bar with MB/%/speed → `Verifying checksum…` → + `Loading…` → `Ready — local, offline, nothing leaves this PC`. +5. Then the operations: "Translate document to [language ▾]", "Summarize + selection", custom prompt box. Status line narrates each step; + expandable activity log for the curious. +6. Language detected vs document language → gentle offer chip: + `This document is French — translate to English?` + +## Non-negotiables + +- **Honesty**: the UI always says which provider is active, what model, + and "cloud — your document text is sent to the endpoint" vs "local — + nothing leaves this PC". No silent cloud calls; AI is strictly opt-in. +- **No crash**: model load failures, corrupt GGUFs, OOM — all `Result`, + all surfaced as messages. +- **Rust only**: candle over llama.cpp bindings preserves the wasm story + (local inference on wasm is future-possible with `candle` + WGPU backend). +- **Licensing**: registry carries SPDX ids; the UI shows them; CC-BY-NC and + unreviewed custom licenses are excluded by policy. +- **Everything is a command**: `ai.translate_doc`, `ai.status`, + `ai.models.list`, `ai.model.download`, `ai.provider.test` — reachable + from the app's control channel and MCP, same as every Craft convention. + +## Milestones + +| # | Deliverable | Done when | +| --- | --- | --- | +| A1 | `probe` + `registry` + `fetch` | CLI-free test: probe reports real caps; `suggest` picks sanely per fixture; a tiny model downloads + sha256 verifies | +| A2 | `OpenAiCompat` provider | `translate` a string through Ollama/OpenAI with mocked HTTP tests | +| A3 | `LocalGguf` on candle | Qwen2.5-0.5B loads and answers on CPU in a test (model fixture fetched in-test, skipped without network) | +| A4 | `translate` segmentation | LaTeX/code/placeholder round-trip tests — protected spans byte-identical | +| A5 | AI tab in one pilot app (suggest TexCraft or WordCraft) | download → translate document end-to-end, live status UX | +| A6 | Commands + MCP surface | `ai.*` commands reachable via control channel | diff --git a/crates/ai/src/error.rs b/crates/ai/src/error.rs new file mode 100644 index 000000000..5955b260c --- /dev/null +++ b/crates/ai/src/error.rs @@ -0,0 +1,52 @@ +//! The crate's error type: everything fails with `Result`, never a panic. + +use std::fmt; + +/// Every failure a caller can act on: the variant says what went wrong, +/// the message says why. +#[derive(Debug)] +pub enum AiError { + /// The HTTP layer failed (DNS, TLS, status code, body). + Http(String), + /// A downloaded file's SHA-256 did not match the expected digest. + Checksum { expected: String, got: String }, + /// The local disk refused us (permissions, full, vanished mid-write). + Io(std::io::Error), + /// The provider returned a response we could not parse. + BadResponse(String), + /// The provider rejected the request (bad token, quota, model name). + Rejected(String), + /// No provider is configured — the UI should route to setup. + NotConfigured, + /// Local model inference failed (load, OOM, bad GGUF). + Inference(String), + /// The operation was cancelled by the user. + Cancelled, + /// The same cache entry is already being downloaded by another + /// caller — only one may hold the `.part` file at a time. + Busy, +} + +impl fmt::Display for AiError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Http(m) => write!(f, "network error: {m}"), + Self::Checksum { expected, got } => write!(f, "checksum mismatch: expected {expected}, got {got}"), + Self::Io(e) => write!(f, "disk error: {e}"), + Self::BadResponse(m) => write!(f, "unreadable response: {m}"), + Self::Rejected(m) => write!(f, "provider rejected the request: {m}"), + Self::NotConfigured => write!(f, "no AI provider configured"), + Self::Inference(m) => write!(f, "local model error: {m}"), + Self::Cancelled => write!(f, "cancelled"), + Self::Busy => write!(f, "a download of this model is already in progress"), + } + } +} + +impl std::error::Error for AiError {} + +impl From for AiError { + fn from(e: std::io::Error) -> Self { + Self::Io(e) + } +} diff --git a/crates/ai/src/fetch.rs b/crates/ai/src/fetch.rs new file mode 100644 index 000000000..d725127a2 --- /dev/null +++ b/crates/ai/src/fetch.rs @@ -0,0 +1,338 @@ +//! One-click model download: resumable, `.part`-suffixed while in flight +//! (a half-downloaded GGUF is never mistaken for a valid one), SHA-256 +//! verified, then atomically renamed. + +use std::fs::{self, File, OpenOptions}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use sha2::Digest; + +use crate::error::AiError; +use crate::registry::ModelEntry; + +/// Progress + lifecycle events, fed to the UI's status line. +#[derive(Clone, Debug)] +pub enum Event { + /// We know the total; download is starting or resuming. + Started { total: u64, resumed_from: u64 }, + /// Bytes on disk so far. `bytes_per_sec` is a running average. + Progress { done: u64, total: u64, bytes_per_sec: u64 }, + /// Body finished; hashing the file before we trust it. + Verifying, + /// Download is complete. `verified` is false when no reference digest + /// existed anywhere (registry table and the host's ETag) — the file is + /// kept but the UI should say "unverified" rather than pretend. + Done { verified: bool }, +} + +/// A handle to abort a download: `cancel` returns false → `AiError::Cancelled`. +pub type Cancel<'a> = &'a dyn Fn() -> bool; + +/// ureq's `timeout_recv_body` is a *total* budget, not a stall timer, so a +/// single fixed cap would kill slow-but-alive downloads of multi-GB models. +/// Instead the GET's body deadline scales with the registry's declared +/// size: a floor rate of 256 KiB/s, between 5 min and 6 h. A dead +/// connection can therefore never block the read loop indefinitely, and a +/// retry still resumes from the `.part` file. +const MIN_BODY_RATE: u64 = 256 * 1024; +const BODY_BUDGET_MIN: Duration = Duration::from_secs(5 * 60); +const BODY_BUDGET_MAX: Duration = Duration::from_secs(6 * 60 * 60); + +fn body_agent(remaining_bytes: u64) -> ureq::Agent { + let budget = Duration::from_secs(remaining_bytes / MIN_BODY_RATE).clamp(BODY_BUDGET_MIN, BODY_BUDGET_MAX); + ureq::Agent::config_builder() + .timeout_connect(Some(Duration::from_secs(15))) + .timeout_send_request(Some(Duration::from_secs(30))) + .timeout_recv_response(Some(Duration::from_secs(60))) + .timeout_recv_body(Some(budget)) + .build() + .into() +} + +/// OS-level lock guarding one cache entry against concurrent downloads; +/// released automatically on close/process exit, so no stale lock files. +fn lock_entry(part_path: &Path) -> Result { + let mut lock_name = part_path.as_os_str().to_os_string(); + lock_name.push(".lock"); + let lock = OpenOptions::new().write(true).create(true).truncate(false).open(PathBuf::from(lock_name))?; + match lock.try_lock() { + Ok(()) => Ok(lock), + Err(std::fs::TryLockError::WouldBlock) => Err(AiError::Busy), + Err(std::fs::TryLockError::Error(e)) => Err(AiError::Io(e)), + } +} + +/// Download `entry` into `cache_dir`, calling `on` with progress events. +/// Resumes an existing `*.part` via HTTP Range. Returns the final path. +pub fn download(entry: &ModelEntry, cache_dir: &Path, on: impl Fn(&Event), cancel: Option>) -> Result { + if cancel.is_some_and(|c| !c()) { + return Err(AiError::Cancelled); + } + fs::create_dir_all(cache_dir)?; + let final_path = cache_dir.join(entry.file); + if final_path.is_file() { + // Already on disk — verify once, reuse if good. + on(&Event::Verifying); + if let Some(expected) = expected_sha256(entry)? { + let got = sha256_file(&final_path)?; + if got.eq_ignore_ascii_case(&expected) { + on(&Event::Done { verified: true }); + return Ok(final_path); + } + return Err(AiError::Checksum { expected, got }); + } + on(&Event::Done { verified: false }); + return Ok(final_path); + } + + let part_path = cache_dir.join(format!("{}.part", entry.file)); + // One downloader per cache entry: two concurrent calls would read the + // same resume offset and append the same bytes twice, corrupting the + // `.part`. The lock is held through the final rename. + let _entry_lock = lock_entry(&part_path)?; + let mut resumed_from = part_path.metadata().map_or(0, |m| m.len()); + + let expected = expected_sha256(entry)?; + + let get = |range_from: u64| { + // Budget for the *full* size, not the remainder: a 200 that + // ignores Range means we re-download the whole model. + let mut req = body_agent(entry.size_mb.saturating_mul(1 << 20)).get(entry.url); + if range_from > 0 { + req = req.header("Range", &format!("bytes={range_from}-")); + } + req.call() + }; + let mut resp = match get(resumed_from) { + Ok(r) => r, + // A 416 means the server found our resume offset unsatisfiable — + // the common cause is a `.part` that already holds the complete + // file (cancelled between the last byte and the rename). If it + // verifies, finish the job; otherwise restart from scratch. + Err(ureq::Error::StatusCode(416)) if resumed_from > 0 => { + if let Some(expected) = &expected + && sha256_file(&part_path).is_ok_and(|got| got.eq_ignore_ascii_case(expected)) + { + on(&Event::Verifying); + fs::rename(&part_path, &final_path)?; + on(&Event::Done { verified: true }); + return Ok(final_path); + } + fs::remove_file(&part_path)?; + resumed_from = 0; + get(0).map_err(http_err)? + } + Err(e) => return Err(http_err(e)), + }; + + // A 200 to a Range request means the server ignored resume — truncate. + let honored_resume = resumed_from > 0 && resp.status() == 206; + let total = content_length(&resp).map(|len| if honored_resume { len + resumed_from } else { len }); + + on(&Event::Started { total: total.unwrap_or(0), resumed_from: if honored_resume { resumed_from } else { 0 } }); + + let mut file = if honored_resume { OpenOptions::new().append(true).open(&part_path)? } else { File::create(&part_path)? }; + + let mut body = resp.body_mut().as_reader(); + let mut buf = vec![0u8; 256 * 1024]; + let mut done = if honored_resume { resumed_from } else { 0 }; + let started = Instant::now(); + loop { + if cancel.is_some_and(|c| !c()) { + return Err(AiError::Cancelled); + } + let n = match body.read(&mut buf) { + Ok(0) => break, + Ok(n) => n, + Err(e) => return Err(AiError::Io(e)), + }; + file.write_all(&buf[..n])?; + done += n as u64; + let secs = started.elapsed().as_secs_f64().max(0.001); + on(&Event::Progress { done, total: total.unwrap_or(0), bytes_per_sec: (done.saturating_sub(resumed_from) as f64 / secs) as u64 }); + } + file.flush()?; + drop(file); + + // A short read means the connection dropped mid-body — keep the .part + // for resume and report it as an HTTP failure, not a success. + if let Some(t) = total + && done < t + { + return Err(AiError::Http(format!("connection dropped at {done}/{t} bytes — retry to resume"))); + } + + on(&Event::Verifying); + let verified = if let Some(expected) = expected { + let got = sha256_file(&part_path)?; + if !got.eq_ignore_ascii_case(&expected) { + // A corrupt download is deleted — it can never silently pass. + let _ = fs::remove_file(&part_path); + return Err(AiError::Checksum { expected, got }); + } + true + } else { + false + }; + + fs::rename(&part_path, &final_path)?; + on(&Event::Done { verified }); + Ok(final_path) +} + +/// The digest we hold this file to: our registry hash if pinned, else the +/// ETag of the resolved URL (Hugging Face serves the LFS sha256 there). +fn expected_sha256(entry: &ModelEntry) -> Result, AiError> { + if let Some(s) = entry.sha256 { + return Ok(Some(s.to_string())); + } + // No redirects: HF serves the LFS sha256 in `x-linked-etag` on the + // 302 itself; following it would return the CDN's own etag instead. + let agent: ureq::Agent = ureq::Agent::config_builder() + .max_redirects(0) + .timeout_connect(Some(Duration::from_secs(15))) + .timeout_recv_response(Some(Duration::from_secs(30))) + .build() + .into(); + match agent.head(entry.url).call() { + Ok(resp) => Ok(etag(&resp)), + // HEAD unsupported/unreachable → proceed without verification. + Err(_) => Ok(None), + } +} + +fn etag(resp: &ureq::http::Response) -> Option { + // Prefer the redirect target's etag (the LFS object), fall back to + // the response's own. Quotes stripped; weak etags ("W/…") ignored. + for name in ["x-linked-etag", "etag"] { + if let Some(v) = resp.headers().get(name).and_then(|v| v.to_str().ok()) { + let v = v.trim().trim_matches('"'); + if !v.starts_with("W/") && v.len() == 64 && v.bytes().all(|b| b.is_ascii_hexdigit()) { + return Some(v.to_string()); + } + } + } + None +} + +fn content_length(resp: &ureq::http::Response) -> Option { + resp.headers() + .get("content-length") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.trim().parse().ok()) + // A redirect's own length is meaningless; only trust it after + // ureq followed redirects (it does — so the final body length). + .filter(|&n: &u64| n > 0) +} + +fn sha256_file(path: &Path) -> Result { + let mut file = File::open(path)?; + let mut hasher = sha2::Sha256::new(); + let mut buf = vec![0u8; 256 * 1024]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + } + Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect()) +} + +fn http_err(e: ureq::Error) -> AiError { + match e { + ureq::Error::StatusCode(code) => AiError::Rejected(format!("HTTP {code}")), + other => AiError::Http(other.to_string()), + } +} + +/// Where a model would land once downloaded. +pub fn model_path(entry: &ModelEntry, cache_dir: &Path) -> PathBuf { + cache_dir.join(entry.file) +} + +/// Is `entry` already fully downloaded? +pub fn is_downloaded(entry: &ModelEntry, cache_dir: &Path) -> bool { + cache_dir.join(entry.file).is_file() +} + +/// `tokenizer.json` beside the GGUF: `.tokenizer.json`. +pub fn tokenizer_path(entry: &ModelEntry, cache_dir: &Path) -> PathBuf { + cache_dir.join(format!("{}.tokenizer.json", entry.file)) +} + +/// The companion tokenizer — small (a few MB), so no resume loop, but the +/// same `.part`-then-rename rule applies. +pub fn download_tokenizer(entry: &ModelEntry, cache_dir: &Path) -> Result { + let dest = tokenizer_path(entry, cache_dir); + if dest.is_file() { + return Ok(dest); + } + let tmp = dest.with_extension("part"); + let mut resp = body_agent(32 * 1024 * 1024).get(entry.tokenizer_url).call().map_err(http_err)?; + let bytes = resp.body_mut().read_to_vec().map_err(|e| AiError::Http(e.to_string()))?; + fs::write(&tmp, bytes)?; + fs::rename(&tmp, &dest)?; + Ok(dest) +} + +/// Remove `entry`'s file (and any `.part` remnant). Missing is fine; +/// other failures (permissions, locked) are surfaced to the caller. +pub fn delete(entry: &ModelEntry, cache_dir: &Path) -> Result<(), AiError> { + for p in [cache_dir.join(entry.file), cache_dir.join(format!("{}.part", entry.file))] { + match fs::remove_file(&p) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(AiError::Io(e)), + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::registry::Arch; + + fn entry() -> &'static ModelEntry { + static E: ModelEntry = ModelEntry { + id: "t", + name: "t", + url: "", + file: "m.gguf", + tokenizer_url: "", + sha256: None, + size_mb: 1, + min_ram_gb: 0.0, + rec_ram_gb: 0.0, + license: "MIT", + quality: crate::registry::Quality::Tiny, + arch: Arch::Llama, + langs: "", + }; + &E + } + + #[test] + fn second_lock_on_same_entry_is_busy() { + let dir = tempfile::tempdir().expect("tempdir"); + let part = dir.path().join("m.gguf.part"); + let _lock = lock_entry(&part).expect("first lock"); + assert!(matches!(lock_entry(&part), Err(AiError::Busy))); + // Releasing lets the next caller in. + drop(_lock); + assert!(lock_entry(&part).is_ok()); + } + + #[test] + fn delete_reports_failures_beyond_not_found() { + let dir = tempfile::tempdir().expect("tempdir"); + // Absent paths are fine. + delete(entry(), dir.path()).expect("missing ok"); + // A directory where the file would be fails removal on every OS. + fs::create_dir(dir.path().join("m.gguf")).expect("mkdir"); + assert!(matches!(delete(entry(), dir.path()), Err(AiError::Io(_)))); + } +} diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rs new file mode 100644 index 000000000..b180040bc --- /dev/null +++ b/crates/ai/src/lib.rs @@ -0,0 +1,27 @@ +//! craft-ai — AI provider abstraction for the Craft suite. +//! +//! See `README.md` for the design: BYO API provider (OpenAI-compatible) + +//! one-click local models with capability detection. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod error; +mod provider; +mod registry; +mod translate; + +#[cfg(not(target_arch = "wasm32"))] +pub mod fetch; +#[cfg(not(target_arch = "wasm32"))] +#[cfg(feature = "local")] +pub mod local; +// `MachineCaps` is portable data the registry needs on every target; only +// the OS probe itself is native-only. +pub mod probe; + +pub use error::AiError; +#[cfg(not(target_arch = "wasm32"))] +pub use provider::OpenAiCompat; +pub use provider::{GenOpts, Provider, ProviderInfo}; +pub use registry::{Arch, MODELS, ModelEntry, Quality, by_id, fits, suggest}; +pub use translate::{PdfGrammar, Segment, TranslateGrammar, is_protected_token, segment, translate_segments}; diff --git a/crates/ai/src/local.rs b/crates/ai/src/local.rs new file mode 100644 index 000000000..6c42aabae --- /dev/null +++ b/crates/ai/src/local.rs @@ -0,0 +1,144 @@ +//! Local GGUF inference on candle (pure Rust — keeps the no-C++ rule and +//! the door open for wasm later). CPU only for now; GPU comes from the +//! app's wgpu adapter in a later milestone. +//! +//! Both supported architectures speak ChatML — one prompt template covers +//! Qwen2.5 and SmolLM2. + +use std::fs::File; +use std::path::Path; + +use candle_core::quantized::gguf_file; +use candle_core::{Device, IndexOp, Tensor}; +use candle_transformers::generation::LogitsProcessor; +use candle_transformers::models::{quantized_llama, quantized_qwen2}; +use tokenizers::Tokenizer; + +use crate::error::AiError; +use crate::provider::{GenOpts, Provider, ProviderInfo}; +use crate::registry::{Arch, ModelEntry}; + +enum Weights { + Qwen2(quantized_qwen2::ModelWeights), + Llama(quantized_llama::ModelWeights), +} + +impl Weights { + fn forward(&mut self, ids: &Tensor, pos: usize) -> Result { + match self { + Self::Qwen2(w) => w.forward(ids, pos), + Self::Llama(w) => w.forward(ids, pos), + } + } +} + +/// A downloaded GGUF loaded and ready. Construction is the expensive +/// part; `complete` is then just a forward loop. +pub struct LocalGguf { + weights: Weights, + tokenizer: Tokenizer, + device: Device, + eos: u32, + entry: &'static ModelEntry, +} + +const SEED: u64 = 0xC0FFEE; + +impl LocalGguf { + /// Load the GGUF + tokenizer.json of `entry` from the model cache. + /// All failures are `Inference` errors — a corrupt file, an OOM, a + /// wrong-arch GGUF, all land in the status line, never in a panic. + pub fn load(entry: &'static ModelEntry, gguf_path: &Path, tokenizer_path: &Path) -> Result { + let device = Device::Cpu; + let mut file = File::open(gguf_path).map_err(AiError::Io)?; + // Malformed GGUF metadata (e.g. `general.alignment = 0`) makes + // candle's parser panic on a division — hostile input must come + // back as an error, not a crash. + // Malformed GGUF metadata (e.g. `general.alignment = 0`, or a + // zero `attention.head_count` reaching a division in the weight + // constructors) makes candle panic — hostile input must come + // back as an error, not a crash. The guard covers parsing *and* + // weight construction. + let weights = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result { + let content = gguf_file::Content::read(&mut file).map_err(|e| AiError::Inference(format!("bad GGUF: {e}")))?; + match entry.arch { + Arch::Qwen2 => Ok(Weights::Qwen2( + quantized_qwen2::ModelWeights::from_gguf(content, &mut file, &device) + .map_err(|e| AiError::Inference(format!("cannot load {}: {e}", entry.file)))?, + )), + Arch::Llama => Ok(Weights::Llama( + quantized_llama::ModelWeights::from_gguf(content, &mut file, &device) + .map_err(|e| AiError::Inference(format!("cannot load {}: {e}", entry.file)))?, + )), + } + })) + .map_err(|_| AiError::Inference("GGUF loader panicked on malformed metadata".to_owned()))??; + let tokenizer = Tokenizer::from_file(tokenizer_path).map_err(|e| AiError::Inference(format!("bad tokenizer.json: {e}")))?; + let eos = tokenizer.token_to_id("<|im_end|>").ok_or_else(|| AiError::Inference("tokenizer has no EOS token".into()))?; + Ok(Self { weights, tokenizer, device, eos, entry }) + } + + /// ChatML wrap — Qwen2.5 and SmolLM2 both ship this template. + fn chat(prompt: &str) -> String { + format!( + "<|im_start|>system\nYou are a precise translation engine. Follow the instructions exactly.<|im_end|>\n<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n", + ) + } + + fn generate(&mut self, prompt: &str, opts: &GenOpts) -> Result { + let text = Self::chat(prompt); + let encoding = self.tokenizer.encode(text, true).map_err(|e| AiError::Inference(format!("encode failed: {e}")))?; + let mut tokens: Vec = encoding.get_ids().to_vec(); + + let temp = if opts.temperature <= 0.02 { None } else { Some(f64::from(opts.temperature)) }; + let mut sampler = LogitsProcessor::new(SEED, temp, None); + + let mut pos = 0usize; + let mut generated: Vec = Vec::with_capacity(opts.max_tokens.min(4096) as usize); + let mut hit_eos = false; + for _ in 0..opts.max_tokens { + let input_len = tokens.len() - pos; + let input = + Tensor::new(&tokens[pos..], &self.device).and_then(|t| t.reshape((1, t.dims1()?))).map_err(|e| AiError::Inference(e.to_string()))?; + let logits = self.weights.forward(&input, pos).map_err(|e| AiError::Inference(e.to_string()))?; + pos += input_len; + // `forward` already returns the last sequence position's + // logits [batch, vocab] — index the batch row only. + let logits = logits.i(0).map_err(|e| AiError::Inference(e.to_string()))?; + let next = sampler.sample(&logits).map_err(|e| AiError::Inference(e.to_string()))?; + if next == self.eos { + hit_eos = true; + break; + } + tokens.push(next); + generated.push(next); + } + // No EOS inside the budget → the reply was cut mid-translation; + // partial output would silently truncate the document. + if !hit_eos { + return Err(AiError::Inference(format!("generation hit max_tokens ({}) without EOS", opts.max_tokens))); + } + // Decode the generated ids through the tokenizer: byte-level BPE + // vocab strings can't be concatenated (spaces/newlines/non-ASCII + // bytes stay encoded, and UTF-8 can split across tokens). + self.tokenizer.decode(&generated, true).map_err(|e| AiError::Inference(format!("decode failed: {e}"))) + } +} + +impl Provider for LocalGguf { + fn name(&self) -> String { + format!("local: {}", self.entry.name) + } + + fn complete(&mut self, prompt: &str, opts: &GenOpts) -> Result { + self.generate(prompt, opts).map(|s| s.trim().to_string()) + } + + fn test(&mut self) -> Result { + Ok(ProviderInfo { label: format!("loaded: {}", self.entry.name), models: vec![self.entry.id.to_string()] }) + } + + fn is_local(&self) -> bool { + true + } +} diff --git a/crates/ai/src/probe.rs b/crates/ai/src/probe.rs new file mode 100644 index 000000000..23c948b37 --- /dev/null +++ b/crates/ai/src/probe.rs @@ -0,0 +1,82 @@ +//! Machine capability detection — runs once, cache the result. +//! +//! GPU/VRAM is deliberately *not* probed here: apps already link wgpu, so +//! they read their own adapter info and fill `MachineCaps::vram_gb` after +//! calling [`probe`]. Re-probing the GPU would double the surface for a +//! bug that reports nonsense VRAM on hybrid laptops. + +/// What this machine can comfortably run. +#[derive(Clone, Debug, PartialEq)] +pub struct MachineCaps { + /// Total physical RAM, in GiB. + pub ram_gb: f32, + /// Free space on the volume holding the model cache, in GiB. + pub disk_free_gb: f32, + /// Logical CPU threads. + pub threads: usize, + /// AVX2 detected — without it quantized GGUF inference crawls. + pub avx2: bool, + /// Dedicated VRAM in GiB, when the app supplied it from its wgpu adapter. + /// `None` means "unknown or no discrete GPU" — never guessed. + pub vram_gb: Option, +} + +impl MachineCaps { + /// Rough throughput hint for a model of `size_mb`: tokens/sec on CPU. + /// Deliberately conservative — an honest underestimate beats an + /// optimistic one that makes the app look slow. + pub fn est_tokens_per_sec(&self, size_mb: u64) -> f32 { + let base = if self.avx2 { 6.0 } else { 1.2 }; + // ~0.5B params ≈ 350 MiB Q4; speed scales inversely with size. + let scale = 350.0 / (size_mb.max(1) as f32); + let thread_boost = (self.threads as f32 / 4.0).min(1.5); + (base * scale * thread_boost).max(0.3) + } +} + +/// Probe the real machine once. `cache_dir` is the future model-cache +/// location — disk space is measured on *its* volume, which may not be +/// the OS volume. +#[cfg(not(target_arch = "wasm32"))] +pub fn probe(cache_dir: &std::path::Path) -> MachineCaps { + let mut sys = sysinfo::System::new(); + sys.refresh_memory(); + let ram_gb = sys.total_memory() as f32 / (1 << 30) as f32; + + let disk_free_gb = disk_free(cache_dir); + + MachineCaps { ram_gb, disk_free_gb, threads: std::thread::available_parallelism().map_or(1, |n| n.get()), avx2: avx2(), vram_gb: None } +} + +#[cfg(all(not(target_arch = "wasm32"), any(target_arch = "x86_64", target_arch = "x86")))] +fn avx2() -> bool { + std::arch::is_x86_feature_detected!("avx2") +} + +#[cfg(all(not(target_arch = "wasm32"), not(any(target_arch = "x86_64", target_arch = "x86"))))] +fn avx2() -> bool { + // AArch64 NEON is mandatory, so the honest answer is "fast enough". + true +} + +/// Free bytes on the volume containing `dir`, walking up to the nearest +/// existing ancestor if `dir` doesn't exist yet (the common case). +#[cfg(not(target_arch = "wasm32"))] +fn disk_free(dir: &std::path::Path) -> f32 { + // Canonicalize the existing ancestor: a relative or symlinked + // `cache_dir` must still match an absolute mount point. + let probe: std::path::PathBuf = + dir.ancestors().find(|p| p.exists()).and_then(|p| p.canonicalize().ok()).unwrap_or_else(|| std::path::PathBuf::from(".")); + let disks = sysinfo::Disks::new_with_refreshed_list(); + // The longest mount point that prefixes our dir owns it. + let best = disks.iter().filter(|d| probe.starts_with(d.mount_point())).max_by_key(|d| d.mount_point().as_os_str().len()); + best.map_or(0.0, |d| d.available_space() as f32 / (1 << 30) as f32) +} + +/// The suite-shared model cache (`%LOCALAPPDATA%\artcraft\models` etc.). +/// `None` on platforms without a cache dir — the caller should refuse +/// local models rather than splashing files into the cwd. +#[cfg(not(target_arch = "wasm32"))] +pub fn models_dir() -> Option { + dirs::cache_dir().map(|d| d.join("artcraft").join("models")) +} diff --git a/crates/ai/src/provider.rs b/crates/ai/src/provider.rs new file mode 100644 index 000000000..ae7bd757d --- /dev/null +++ b/crates/ai/src/provider.rs @@ -0,0 +1,196 @@ +//! Inference backends behind one trait. Apps hold a `Box` +//! and never care whether the bytes went to OpenAI, Ollama or a local GGUF. + +use crate::error::AiError; + +/// Generation parameters — kept minimal on purpose; the UI exposes +/// "translate", not a sampler playground. +#[derive(Clone, Debug)] +pub struct GenOpts { + /// Max tokens to generate. + pub max_tokens: u32, + /// Sampling temperature; translation wants ~0. + pub temperature: f32, +} + +impl Default for GenOpts { + fn default() -> Self { + Self { max_tokens: 2048, temperature: 0.1 } + } +} + +/// What `test()` learned about a provider — shown next to the green check. +#[derive(Clone, Debug)] +pub struct ProviderInfo { + /// Human label, e.g. "Ollama at http://localhost:11434". + pub label: String, + /// Model ids the endpoint advertised (may be empty if it doesn't say). + pub models: Vec, +} + +/// An AI backend the suite can use. `Send` so apps can move a loaded +/// provider onto a worker thread for long generations. +pub trait Provider: Send { + /// Short name for the status line ("local: Qwen2.5 1.5B", "OpenAI-compatible"). + fn name(&self) -> String; + /// One completion. Prompt construction is the caller's job — this + /// trait is deliberately text-in/text-out so every consumer (translate, + /// summarize, custom prompt) shares one path. + fn complete(&mut self, prompt: &str, opts: &GenOpts) -> Result; + /// Can we reach it? Never sends document text — just a handshake. + fn test(&mut self) -> Result; + /// True when document text stays on this machine. + fn is_local(&self) -> bool; +} + +/// Any OpenAI-compatible `/v1/chat/completions` endpoint: OpenAI, Azure, +/// Ollama (`http://localhost:11434/v1`), LM Studio, Groq, OpenRouter… +/// The token is a plain string — storage (OS keyring, settings file) is +/// the app's choice, and it is never logged or echoed into errors. +#[cfg(not(target_arch = "wasm32"))] +pub struct OpenAiCompat { + /// Base URL ending at the API root, e.g. `https://api.openai.com/v1`. + pub endpoint: String, + /// Bearer token; `None` for unauthenticated local endpoints (Ollama). + pub token: Option, + /// Model id sent in every request. + pub model: String, +} + +#[cfg(not(target_arch = "wasm32"))] +impl OpenAiCompat { + pub fn new(endpoint: impl Into, token: Option, model: impl Into) -> Self { + Self { endpoint: endpoint.into(), token, model: model.into() } + } + + fn url(&self, path: &str) -> String { + format!("{}/{}", self.endpoint.trim_end_matches('/'), path) + } + + /// ureq sets no timeouts by default — an endpoint that accepts the + /// socket and never replies would block the caller forever, so every + /// request goes through an agent with finite deadlines. The response + /// budgets are generous: a non-streamed chat completion only sends + /// headers once generation is done, which can take minutes. + fn agent() -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_connect(Some(std::time::Duration::from_secs(15))) + .timeout_send_request(Some(std::time::Duration::from_secs(30))) + .timeout_send_body(Some(std::time::Duration::from_secs(60))) + .timeout_recv_response(Some(std::time::Duration::from_secs(300))) + .timeout_recv_body(Some(std::time::Duration::from_secs(300))) + .build() + .into() + } + + fn auth(&self, req: ureq::RequestBuilder) -> ureq::RequestBuilder { + match &self.token { + Some(t) if !t.is_empty() => req.header("Authorization", format!("Bearer {t}")), + _ => req, + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Provider for OpenAiCompat { + fn name(&self) -> String { + format!("{} ({})", self.model, self.endpoint) + } + + fn complete(&mut self, prompt: &str, opts: &GenOpts) -> Result { + if self.endpoint.trim().is_empty() { + return Err(AiError::NotConfigured); + } + let body = serde_json::json!({ + "model": self.model, + "messages": [{"role": "user", "content": prompt}], + "temperature": opts.temperature, + "max_tokens": opts.max_tokens, + }); + let mut resp = + self.auth(Self::agent().post(self.url("chat/completions"))).header("Content-Type", "application/json").send_json(body).map_err(|e| { + match e { + ureq::Error::StatusCode(401 | 403) => AiError::Rejected("authentication failed — check the API token".into()), + ureq::Error::StatusCode(404) => AiError::Rejected("model or endpoint not found — check both fields".into()), + ureq::Error::StatusCode(c) => AiError::Rejected(format!("HTTP {c}")), + other => AiError::Http(other.to_string()), + } + })?; + let v: serde_json::Value = resp.body_mut().read_json().map_err(|e| AiError::BadResponse(e.to_string()))?; + // A completion cut off at max_tokens ("length") or aborted is not + // a translation — returning it would silently truncate the doc. + match v.pointer("/choices/0/finish_reason").and_then(serde_json::Value::as_str) { + Some("stop") | Some("tool_calls") | None => {} + Some(reason) => return Err(AiError::BadResponse(format!("incomplete completion (finish_reason={reason})"))), + } + v.pointer("/choices/0/message/content") + .and_then(serde_json::Value::as_str) + .map(str::to_string) + .ok_or_else(|| AiError::BadResponse("no choices[0].message.content in response".into())) + } + + fn test(&mut self) -> Result { + if self.endpoint.trim().is_empty() { + return Err(AiError::NotConfigured); + } + // GET /v1/models — a handshake only, no user text leaves the app. + let mut req = Self::agent().get(self.url("models")); + if let Some(t) = &self.token + && !t.is_empty() + { + req = req.header("Authorization", format!("Bearer {t}")); + } + let mut resp = req.call().map_err(|e| match e { + ureq::Error::StatusCode(401 | 403) => AiError::Rejected("authentication failed — check the API token".into()), + ureq::Error::StatusCode(c) => AiError::Rejected(format!("HTTP {c}")), + other => AiError::Http(other.to_string()), + })?; + let v: serde_json::Value = resp.body_mut().read_json().map_err(|e| AiError::BadResponse(e.to_string()))?; + let models = v + .get("data") + .and_then(serde_json::Value::as_array) + .map(|arr| arr.iter().filter_map(|m| m.get("id").and_then(serde_json::Value::as_str).map(str::to_string)).collect()) + .unwrap_or_default(); + Ok(ProviderInfo { label: format!("reachable: {}", self.endpoint), models }) + } + + fn is_local(&self) -> bool { + // Local endpoints keep text on the machine; we can't verify a + // remote URL's forwarding, so honesty means: loopback → local. + // Parse the authority properly — a prefix match would call + // `localhost.example.com` or `127.0.0.1.example.com` "local" + // while document text leaves the machine. + let e = self.endpoint.trim(); + let after_scheme = e.split_once("://").map_or(e, |(_, rest)| rest); + let authority = after_scheme.split(['/', '?', '#']).next().unwrap_or(""); + let host_port = authority.rsplit('@').next().unwrap_or(""); // strip userinfo + let host = if let Some(rest) = host_port.strip_prefix('[') { + rest.split(']').next().unwrap_or("") + } else { + host_port.split(':').next().unwrap_or("") + }; + host.eq_ignore_ascii_case("localhost") || host.parse::().is_ok_and(|ip| ip.is_loopback()) + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + #[test] + fn is_local_accepts_only_real_loopback() { + let local = |ep: &str| OpenAiCompat::new(ep, None, "m").is_local(); + assert!(local("http://localhost:11434/v1")); + assert!(local("https://localhost/v1")); + assert!(local("http://127.0.0.1:8080/v1")); + assert!(local("http://127.99.0.1/v1")); // whole 127/8 is loopback + assert!(local("http://[::1]:11434/v1")); + // Lookalike hostnames must NOT report local — document text would + // leave the machine while the UI promises it stays. + assert!(!local("https://localhost.example.com/v1")); + assert!(!local("https://127.0.0.1.example.com/v1")); + assert!(!local("https://localhost.evil.io/v1")); + assert!(!local("https://api.openai.com/v1")); + assert!(!local("https://example.com/localhost/v1")); + } +} diff --git a/crates/ai/src/registry.rs b/crates/ai/src/registry.rs new file mode 100644 index 000000000..2035ab836 --- /dev/null +++ b/crates/ai/src/registry.rs @@ -0,0 +1,138 @@ +//! The curated model registry — a hand-maintained table, compiled in. +//! Runtime-fetching this list would make our supply chain un-auditable. +//! +//! Curation rule: **permissive licenses only** (the suite is MIT OR +//! Apache-2.0 and commercial users run it). CC-BY-NC models like NLLB-200 +//! are excluded by policy; their absence is deliberate. +//! +//! `sha256` may be `None`: Hugging Face serves the LFS digest in the +//! `X-Linked-ETag` header of the resolve redirect, which [`crate::fetch`] +//! uses as the expected checksum. We only hard-code a hash when we've +//! verified it ourselves — never a guessed one. + +use crate::probe::MachineCaps; + +/// Model quality tier — higher is better output, bigger download. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Quality { + Tiny, + Small, + Medium, +} + +/// Which candle architecture loads the GGUF. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Arch { + Qwen2, + Llama, +} + +/// One downloadable model. +#[derive(Clone, Copy, Debug)] +pub struct ModelEntry { + /// Stable identifier stored in settings (`"qwen2.5-1.5b-q4km"`). + pub id: &'static str, + /// Display name for the picker. + pub name: &'static str, + /// Canonical download URL (Hugging Face `resolve` endpoint). + pub url: &'static str, + /// Filename inside the model cache. + pub file: &'static str, + /// Companion tokenizer (needed by local inference; the GGUF ships + /// vocab only, not the chat-time tokenizer.json). + pub tokenizer_url: &'static str, + /// Verified SHA-256 of the GGUF, when we have one. + pub sha256: Option<&'static str>, + /// Download size, MiB — shown to the user before they commit. + pub size_mb: u64, + /// Below this RAM the model is refused outright. + pub min_ram_gb: f32, + /// Recommended RAM for comfortable use. + pub rec_ram_gb: f32, + /// SPDX license id, displayed in the UI. + pub license: &'static str, + pub quality: Quality, + pub arch: Arch, + /// Human-readable language coverage for the picker. + pub langs: &'static str, +} + +/// The registry, smallest first. +pub static MODELS: &[ModelEntry] = &[ + ModelEntry { + id: "qwen2.5-0.5b-q4km", + name: "Qwen2.5 0.5B Instruct (Q4_K_M)", + url: "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf", + file: "qwen2.5-0.5b-instruct-q4_k_m.gguf", + tokenizer_url: "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct/resolve/main/tokenizer.json", + sha256: None, + size_mb: 389, + min_ram_gb: 2.0, + rec_ram_gb: 4.0, + license: "Apache-2.0", + quality: Quality::Tiny, + arch: Arch::Qwen2, + langs: "29+ languages incl. EN/ZH/FR/DE/ES/JA/KO/RU", + }, + ModelEntry { + id: "smollm2-1.7b-q4km", + name: "SmolLM2 1.7B Instruct (Q4_K_M)", + url: "https://huggingface.co/bartowski/SmolLM2-1.7B-Instruct-GGUF/resolve/main/SmolLM2-1.7B-Instruct-Q4_K_M.gguf", + file: "SmolLM2-1.7B-Instruct-Q4_K_M.gguf", + tokenizer_url: "https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct/resolve/main/tokenizer.json", + sha256: None, + size_mb: 1033, + min_ram_gb: 4.0, + rec_ram_gb: 8.0, + license: "Apache-2.0", + quality: Quality::Small, + arch: Arch::Llama, + langs: "primarily EN/FR/DE/ES/IT", + }, + ModelEntry { + id: "qwen2.5-1.5b-q4km", + name: "Qwen2.5 1.5B Instruct (Q4_K_M)", + url: "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf", + file: "qwen2.5-1.5b-instruct-q4_k_m.gguf", + tokenizer_url: "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct/resolve/main/tokenizer.json", + sha256: None, + size_mb: 986, + min_ram_gb: 4.0, + rec_ram_gb: 8.0, + license: "Apache-2.0", + quality: Quality::Small, + arch: Arch::Qwen2, + langs: "29+ languages incl. EN/ZH/FR/DE/ES/JA/KO/RU", + }, + // NOTE: Qwen2.5-3B was removed — its `qwen-research` license is + // non-commercial and breaks the permissive-only rule above. No + // permissively-licensed Medium-tier candidate is currently curated. +]; + +/// Look up a model by stable id. +pub fn by_id(id: &str) -> Option<&'static ModelEntry> { + MODELS.iter().find(|m| m.id == id) +} + +/// Whether `entry` can run at all on this machine. +pub fn fits(caps: &MachineCaps, entry: &ModelEntry) -> bool { + let ram_ok = caps.ram_gb >= entry.min_ram_gb; + let disk_ok = caps.disk_free_gb >= entry.size_mb as f32 / 1024.0 * 1.3; // file + headroom + ram_ok && disk_ok +} + +/// The default suggestion for `caps`: best quality that fits, preferring +/// 3B on roomy machines, 1.5B mid-range, 0.5B on small ones. Returns +/// `None` when nothing fits — the UI then says so honestly instead of +/// offering a download that can't run. +pub fn suggest(caps: &MachineCaps) -> Option<&'static ModelEntry> { + let capable: Vec<&ModelEntry> = MODELS.iter().filter(|m| fits(caps, m)).collect(); + let best_allowed = if caps.vram_gb.is_some_and(|v| v >= 6.0) || caps.ram_gb >= 16.0 { + Quality::Medium + } else if caps.ram_gb >= 8.0 { + Quality::Small + } else { + Quality::Tiny + }; + capable.into_iter().filter(|m| m.quality <= best_allowed).max_by_key(|m| m.quality) +} diff --git a/crates/ai/src/translate.rs b/crates/ai/src/translate.rs new file mode 100644 index 000000000..a5de0622c --- /dev/null +++ b/crates/ai/src/translate.rs @@ -0,0 +1,525 @@ +//! Document translation as *segments*, never raw text: the model sees +//! only translatable runs, and protected spans (URLs, placeholders, +//! markup, numbers-only runs) come back byte-identical because we never +//! sent them. +//! +//! Each app declares its grammar via [`TranslateGrammar`]; the default +//! [`PdfGrammar`] suits extracted PDF text. + +use crate::error::AiError; +use crate::provider::{GenOpts, Provider}; + +/// A unit of text the translator decided on. +#[derive(Clone, Debug, PartialEq)] +pub enum Segment { + /// Sent to the model; replace with the translation. + Text(String), + /// Never sent; re-inserted verbatim. + Protected(String), +} + +impl Segment { + /// The source text, translated or not. + pub fn source(&self) -> &str { + match self { + Self::Text(s) | Self::Protected(s) => s, + } + } +} + +/// Which runs of a document's text must never be translated. +pub trait TranslateGrammar { + /// True when `token` (already delimited — a word, symbol, or + /// whitespace-free run) is structural and must survive verbatim. + fn is_protected(&self, token: &str) -> bool; +} + +/// Grammar for text extracted from a PDF: protects URLs, e-mail +/// addresses, `{placeholders}`, ``, and runs with no letters +/// (page furniture, digits, punctuation). +pub struct PdfGrammar; + +impl TranslateGrammar for PdfGrammar { + fn is_protected(&self, token: &str) -> bool { + is_protected_token(token) + } +} + +/// Shared protected-token test, useful to other apps' grammars. +pub fn is_protected_token(token: &str) -> bool { + let t = token.trim(); + if t.is_empty() { + return true; + } + if !t.chars().any(|c| c.is_alphabetic()) { + return true; // numbers, punctuation, symbols + } + let lower = t.to_ascii_lowercase(); + lower.starts_with("http://") + || lower.starts_with("https://") + || lower.starts_with("www.") + || lower.contains('@') && lower.contains('.') && !lower.contains(' ') + || (t.starts_with('{') && t.ends_with('}')) + || (t.starts_with('<') && t.ends_with('>')) +} + +/// Split `text` into segments on whitespace boundaries, grouping +/// consecutive protected or translatable tokens. `` spans are +/// carved out first — a tag with attributes contains whitespace, and a +/// whole `Hello` run must keep "Hello" translatable while the +/// tags themselves stay byte-identical. +pub fn segment(text: &str, grammar: &dyn TranslateGrammar) -> Vec { + fn flush(out: &mut Vec, buf: &mut String, protected: bool) { + if buf.is_empty() { + return; + } + let seg = if protected { Segment::Protected(std::mem::take(buf)) } else { Segment::Text(std::mem::take(buf)) }; + out.push(seg); + } + + let mut out: Vec = Vec::new(); + let mut buf = String::new(); + let mut buf_protected = false; + let mut started = false; + + for (token, is_tag) in split_tokens(text) { + let ws = token.chars().all(char::is_whitespace); + // Whitespace glues to whatever the current run is; markup tags + // are always protected. + let this_protected = if ws { buf_protected } else { is_tag || grammar.is_protected(token) }; + if started && this_protected != buf_protected { + flush(&mut out, &mut buf, buf_protected); + } + buf_protected = this_protected; + started = true; + buf.push_str(token); + } + flush(&mut out, &mut buf, buf_protected); + out +} + +/// Tokenize into `(slice, is_tag)`: markup tags are whole `<…>` spans +/// (attributes included), everything else alternates between maximal +/// whitespace and non-whitespace runs. +fn split_tokens(text: &str) -> Vec<(&str, bool)> { + let mut out = Vec::new(); + let mut pos = 0usize; + let bytes = text.as_bytes(); + while pos < bytes.len() { + if bytes[pos] == b'<' + && let Some(tag_len) = tag_len(&text[pos..]) + { + out.push((&text[pos..pos + tag_len], true)); + pos += tag_len; + continue; + } + // Advance a non-tag run up to the next '<' that starts a tag; + // bare '<' characters just stay inside the run. + let mut scan = pos; + let mut run_end = bytes.len(); + while let Some(lt) = bytes[scan..].iter().position(|&b| b == b'<') { + let at = scan + lt; + if tag_len(&text[at..]).is_some() { + run_end = at; + break; + } + scan = at + 1; + } + for piece in split_words_ws(&text[pos..run_end]) { + out.push((piece, false)); + } + pos = run_end; + } + out +} + +/// Length of a `<…>` tag starting at `s[0]`, or `None` when `<` does not +/// begin markup (bare `<`, `<3`, `< hello`). Tags start `` before any `<` or newline; +/// the scan is capped so pathological input can't stall it. +fn tag_len(s: &str) -> Option { + const MAX_TAG: usize = 512; + let second = s.as_bytes().get(1)?; + let opener_ok = second.is_ascii_alphabetic() || matches!(second, b'/' | b'!' | b'?'); + if !opener_ok { + return None; + } + s.char_indices().skip(2).take(MAX_TAG).find(|(_, c)| matches!(c, '>' | '<' | '\n')).and_then(|(i, c)| (c == '>').then_some(i + 1)) +} + +/// Split into alternating word/whitespace runs (like `split_inclusive` +/// but grouping every maximal run of whitespace or non-whitespace). +fn split_words_ws(text: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut start = 0usize; + let mut prev_ws: Option = None; + for (i, c) in text.char_indices() { + let ws = c.is_whitespace(); + if let Some(p) = prev_ws + && p != ws + { + out.push(&text[start..i]); + start = i; + } + prev_ws = Some(ws); + } + if start < text.len() { + out.push(&text[start..]); + } + out +} + +/// How many segments one prompt carries — keeps responses snappy and +/// makes a numbering slip cheap to retry. +const BATCH: usize = 20; +/// …and how many bytes one prompt carries. A document with no protected +/// tokens is one `Text` segment of arbitrary length — without a size +/// bound the request can exceed `max_tokens` and come back truncated +/// (which providers must reject, not return as success). +const BATCH_BYTES: usize = 4 * 1024; +/// A single `Text` run larger than this is chopped into pieces before +/// batching, so no one request is unbounded. +const RUN_BYTES: usize = 3 * 1024; + +/// A translatable piece of one segment: the whitespace-stripped `core` +/// is sent to the model, `lead`/`trail` are restored verbatim around the +/// translation so `Visitez` never glues to `https://a.io`. +struct Run<'a> { + seg: usize, + lead: &'a str, + core: &'a str, + trail: &'a str, + /// False for whitespace-only pieces: never sent to the model, but + /// still reassembled into the segment. + send: bool, +} + +/// `(leading ws, core, trailing ws)` of `s`, all on char boundaries. +fn ws_edges(s: &str) -> (&str, &str, &str) { + let lead = s.len() - s.trim_start().len(); + let tail = s.len() - s.trim_end().len(); + if lead + tail >= s.len() { + return (s, "", ""); // all-whitespace run: nothing to translate + } + (&s[..lead], &s[lead..s.len() - tail], &s[s.len() - tail..]) +} + +/// Chop `s` into ≤ `max`-byte pieces on whitespace boundaries (the last +/// ws before the limit; a run with no ws is hard-cut at the limit). The +/// boundary whitespace stays inside the pieces — nothing is lost. +fn split_run(s: &str, max: usize) -> Vec<&str> { + let mut out = Vec::new(); + let mut rest = s; + while rest.len() > max { + let mut ws_cut = None; + let mut boundary = 0usize; + for (i, c) in rest.char_indices() { + if i >= max { + break; + } + boundary = i + c.len_utf8(); + if c.is_whitespace() { + ws_cut = Some(i); // cut *before* the ws — it leads the next piece + } + } + let cut = match ws_cut.filter(|w| *w > max / 4) { + Some(w) => w, + None => boundary.max(1), + }; + out.push(&rest[..cut]); + rest = &rest[cut..]; + } + if !rest.is_empty() { + out.push(rest); + } + out +} + +/// Translate every `Text` segment to `target_lang`, leaving `Protected` +/// untouched. Batched with numbered items; a count mismatch retries the +/// offending half rather than misaligning the whole document. +pub fn translate_segments(provider: &mut dyn Provider, segs: &[Segment], target_lang: &str) -> Result, AiError> { + // Source whitespace never reaches the model: each Text segment is + // split edge-to-edge, and oversized runs are chopped further. + let mut runs: Vec> = Vec::new(); + for (i, s) in segs.iter().enumerate() { + let Segment::Text(src) = s else { continue }; + for piece in split_run(src, RUN_BYTES) { + let (lead, core, trail) = ws_edges(piece); + // Pure-whitespace pieces (possible after a long run is chopped) + // keep their bytes in the output but skip the provider. + runs.push(Run { seg: i, lead, core, trail, send: !core.is_empty() }); + } + } + let run_segs: std::collections::HashSet = runs.iter().map(|r| r.seg).collect(); + + let mut out: Vec = segs.iter().map(|s| s.source().to_string()).collect(); + for &i in &run_segs { + out[i].clear(); // rebuilt from translated runs below + } + let mut i = 0; + while i < runs.len() { + // Whitespace-only pieces restore verbatim, in order, and never + // reach the model. + while i < runs.len() && !runs[i].send { + let r = &runs[i]; + out[r.seg].push_str(r.lead); + out[r.seg].push_str(r.trail); + i += 1; + } + // A batch is bounded by item count *and* total prompt bytes. + let mut bytes = 0usize; + let start = i; + while i < runs.len() && runs[i].send && i - start < BATCH && bytes + runs[i].core.len() <= BATCH_BYTES { + bytes += runs[i].core.len(); + i += 1; + } + if i == start { + if i < runs.len() { + i += 1; // never spin on an oversized single item + } + continue; + } + let chunk = &runs[start..i]; + let translated = translate_batch(provider, chunk, target_lang)?; + for (run, t) in chunk.iter().zip(translated) { + out[run.seg].push_str(run.lead); + out[run.seg].push_str(&t); + out[run.seg].push_str(run.trail); + } + } + Ok(out) +} + +/// One numbered batch; splits recursively on count mismatch so a single +/// malformed reply can't corrupt neighbors. +fn translate_batch(provider: &mut dyn Provider, runs: &[Run<'_>], lang: &str) -> Result, AiError> { + if runs.len() == 1 { + return Ok(vec![translate_one(provider, runs[0].core, lang)?]); + } + let prompt = numbered_prompt(&runs.iter().map(|r| r.core.to_string()).collect::>(), lang); + let reply = provider.complete(&prompt, &GenOpts::default())?; + match parse_numbered(&reply, runs.len()) { + Some(v) => Ok(v), + None => { + let mid = runs.len() / 2; + let mut a = translate_batch(provider, &runs[..mid], lang)?; + let b = translate_batch(provider, &runs[mid..], lang)?; + a.extend(b); + Ok(a) + } + } +} + +fn translate_one(provider: &mut dyn Provider, source: &str, lang: &str) -> Result { + let prompt = format!("Translate the following text to {lang}. Reply with ONLY the translation, no quotes, no notes.\n\n{source}"); + Ok(provider.complete(&prompt, &GenOpts::default())?.trim().to_string()) +} + +/// `"1. …"`-style numbered prompt — models follow it far more reliably +/// than delimiter schemes. +fn numbered_prompt(sources: &[String], lang: &str) -> String { + let mut p = format!( + "Translate each numbered item to {lang}. Keep the numbering. \ + Preserve all formatting, placeholders like {{name}}, URLs and markup verbatim. \ + Reply with ONLY the numbered translations.\n\n" + ); + for (i, s) in sources.iter().enumerate() { + p.push_str(&format!("{}. {}\n", i + 1, s.replace('\n', " "))); + } + p +} + +/// Parse `"1. …\n2. …"` back into items; `None` when the reply is +/// malformed — duplicates, out-of-range numbers, or a missing item all +/// mean the numbering slipped, and the caller retries/splits rather +/// than accepting corrupted text. Non-numbered lines after an item are +/// continuations of it; non-numbered chatter before item 1 is rejected +/// the same way, so nothing is silently dropped. +fn parse_numbered(reply: &str, want: usize) -> Option> { + let mut out = vec![String::new(); want]; + let mut seen = vec![false; want]; + let mut current: Option = None; + for line in reply.lines() { + let line = line.trim(); + if line.is_empty() { + continue; + } + match numbered_line(line) { + Some(idx) if idx >= 1 && idx <= want => { + if seen[idx - 1] { + return None; // "1. un\n2. deux\n1. trois" overwrites — reject + } + seen[idx - 1] = true; + let rest = line.split_once(['.', ')']).map_or("", |(_, r)| r).trim().to_string(); + out[idx - 1] = rest; + current = Some(idx - 1); + } + Some(_) => return None, // numbered but out of range — malformed reply + // A wrapped/multi-line item: keep the continuation, not + // "1. Première phrase.\nSuite" dropping "Suite". Unnumbered + // preamble is rejected — not our format. + None => { + let i = current?; + out[i].push('\n'); + out[i].push_str(line); + } + } + } + (seen.iter().all(|s| *s) && out.iter().all(|s| !s.is_empty())).then_some(out) +} + +/// `Some(idx)` when `line` opens as `"12."` / `"12)"` — a 1-3 digit +/// number followed by `'.'` or `')'`. Anything else is `None`, so +/// "Section 2. notes" is a continuation, not item 2. +fn numbered_line(line: &str) -> Option { + let line = line.trim_start(); + let digits = line.bytes().take_while(|b| b.is_ascii_digit()).count(); + if digits == 0 || digits > 3 || !matches!(line.as_bytes().get(digits), Some(b'.' | b')')) { + return None; + } + line.get(..digits)?.parse().ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn split_words_ws_groups_runs() { + assert_eq!(split_words_ws("a b\tc"), vec!["a", " ", "b", "\t", "c"]); + } + + #[test] + fn pdf_grammar_protects() { + let g = PdfGrammar; + assert!(g.is_protected("https://x.io/a")); + assert!(g.is_protected("{count}")); + assert!(g.is_protected("42.5")); + assert!(!g.is_protected("Bonjour")); + } + + #[test] + fn segmentation_glues_whitespace_and_protects_spans() { + let segs = segment("Visit https://a.io now {n} times", &PdfGrammar); + // "Visit " text, protected url, " now " text, protected {n}, " times" text + let texts: Vec<&Segment> = segs.iter().filter(|s| matches!(s, Segment::Text(_))).collect(); + assert!(segs.iter().any(|s| matches!(s, Segment::Protected(p) if p.trim() == "https://a.io"))); + assert!(segs.iter().any(|s| matches!(s, Segment::Protected(p) if p.trim() == "{n}"))); + assert!(texts.iter().any(|s| s.source().contains("Visit"))); + } + + #[test] + fn numbered_parse_roundtrip() { + let r = "1. un\n2. deux\n3. trois"; + assert_eq!(parse_numbered(r, 3), Some(vec!["un".into(), "deux".into(), "trois".into()])); + assert_eq!(parse_numbered("1. un\n3. trois", 3), None); + } + + #[test] + fn numbered_parse_rejects_duplicates_and_overflow() { + assert_eq!(parse_numbered("1. un\n2. deux\n1. trois", 2), None); + assert_eq!(parse_numbered("1. un\n2. deux\n3. trois", 2), None); + assert_eq!(parse_numbered("0. zero\n1. un\n2. deux", 2), None); + } + + #[test] + fn numbered_parse_keeps_continuation_lines() { + let r = "1. Première phrase.\nSuite du paragraphe\n2. Deuxième élément."; + assert_eq!(parse_numbered(r, 2), Some(vec!["Première phrase.\nSuite du paragraphe".into(), "Deuxième élément.".into()])); + // Preamble chatter that isn't a numbered item is rejected, not + // silently dropped. + assert_eq!(parse_numbered("Sure, here you go:\n1. un\n2. deux", 2), None); + // "Section 2. notes" looks numbered but isn't → continuation. + let r2 = "1. un\nSection 2. notes\n2. deux"; + assert_eq!(parse_numbered(r2, 2), Some(vec!["un\nSection 2. notes".into(), "deux".into()])); + } + + #[test] + fn markup_tags_split_from_their_text() { + let segs = segment("Hello world", &PdfGrammar); + assert!(segs.iter().any(|s| matches!(s, Segment::Protected(p) if p == ""))); + assert!(segs.iter().any(|s| matches!(s, Segment::Protected(p) if p.trim() == ""))); + assert!(segs.iter().any(|s| matches!(s, Segment::Text(t) if t.contains("Hello")))); + assert!(segs.iter().any(|s| matches!(s, Segment::Text(t) if t.contains("world")))); + // Tags containing spaces stay whole and protected. + let segs = segment("link", &PdfGrammar); + assert!(segs.iter().any(|s| matches!(s, Segment::Protected(p) if p == ""))); + // A bare '<' is text, not a tag opener — words around it stay + // translatable (the lone '<' itself is protected as punctuation). + let segs = segment("a < b and <3 hearts", &PdfGrammar); + assert!(segs.iter().any(|s| matches!(s, Segment::Text(t) if t.contains("hearts")))); + assert!(!segs.iter().any(|s| matches!(s, Segment::Protected(p) if p.contains('<') && p.contains('>')))); + } + + #[test] + fn ws_edges_and_split_run_preserve_every_byte() { + assert_eq!(ws_edges(" héllo \n"), (" ", "héllo", " \n")); + assert_eq!(ws_edges(" "), (" ", "", "")); + let s = "alpha beta gamma delta epsilon"; + let pieces = split_run(s, 12); + assert!(pieces.iter().all(|p| p.len() <= 12)); + assert_eq!(pieces.concat(), s); // boundary whitespace survives + // A run with no whitespace is hard-cut at a char boundary. + let long = "x".repeat(50); + let pieces = split_run(&long, 20); + assert!(pieces.iter().all(|p| p.len() <= 20)); + assert_eq!(pieces.concat(), long); + } + + /// A provider that echoes numbered replies — exercises the batching, + /// whitespace restore and reassembly end to end without a network. + struct Echo; + + impl Provider for Echo { + fn name(&self) -> String { + "echo".into() + } + + fn complete(&mut self, prompt: &str, _opts: &GenOpts) -> Result { + if prompt.starts_with("Translate each numbered item") { + // Parse our own prompt's numbering and echo each item. + let body = prompt.split("\n\n").nth(1).unwrap_or(""); + let mut out = String::new(); + for line in body.lines() { + out.push_str(line); + out.push('\n'); + } + return Ok(out); + } + Ok(prompt.rsplit("\n\n").next().unwrap_or(prompt).to_string()) + } + + fn test(&mut self) -> Result { + Ok(crate::provider::ProviderInfo { label: "echo".into(), models: vec![] }) + } + + fn is_local(&self) -> bool { + true + } + } + + #[test] + fn numbered_parse_accepts_paren_markers() { + // "1) …" replies contain sentence-ending periods inside items — + // the leading delimiter must be picked before inspecting text. + let r = "1) Première phrase.\nSuite.\n2) Deuxième élément."; + assert_eq!(parse_numbered(r, 2), Some(vec!["Première phrase.\nSuite.".into(), "Deuxième élément.".into()])); + } + + #[test] + fn whitespace_only_pieces_survive_reconstruction() { + let segs = vec![Segment::Text(format!("{}Hello", " ".repeat(RUN_BYTES)))]; + let mut echo = Echo; + let out = translate_segments(&mut echo, &segs, "fr").unwrap_or_default(); + assert_eq!(out.concat(), format!("{}Hello", " ".repeat(RUN_BYTES))); + } + + #[test] + fn translate_restores_whitespace_around_protected_spans() { + let segs = segment("Visit https://a.io now", &PdfGrammar); + let mut echo = Echo; + let out = translate_segments(&mut echo, &segs, "fr").unwrap_or_default(); + assert_eq!(out.concat(), "Visit https://a.io now"); + } +} diff --git a/crates/anicraft-format/src/lib.rs b/crates/anicraft-format/src/lib.rs index 7cc5dc261..6ff5d81e1 100644 --- a/crates/anicraft-format/src/lib.rs +++ b/crates/anicraft-format/src/lib.rs @@ -34,7 +34,12 @@ struct EnvelopeOut<'a, P, 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 }; + write_version(FORMAT_VERSION, generator, paths, document) +} + +/// Serializes the envelope with an explicit format version and AniCraft's compact/pretty threshold. +pub fn write_version(version: u32, generator: &str, paths: &[P], document: &T) -> Result { + let envelope = EnvelopeOut { format: FORMAT_NAME, 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) } } diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 1590372ad..08b881e17 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -70,6 +70,9 @@ pub trait AtomicFs { fn sync_dir(&self, dir: &Path) -> io::Result<()>; /// Give the open temporary file its final permissions. fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()>; + /// Put the open temporary file in group `gid` (Unix only). + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()>; } /// The production file system implementation. @@ -126,6 +129,11 @@ impl AtomicFs for RealFs { fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { file.set_permissions(perms) } + + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { + std::os::unix::fs::fchown(file, None, Some(gid)) + } } /// Flush `file` to stable storage (`sync_all`). @@ -342,10 +350,29 @@ fn split(target: &Path, path: &Path) -> io::Result<(PathBuf, String)> { Ok((dir, name.to_string_lossy().into_owned())) } -/// Create a temporary file in `dir`, fill it with `fill`, give it the permissions of the file it -/// replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when the mode -/// already matches after `fill`. A leftover file with the same name is skipped. When any step -/// fails, the temporary file is removed. +/// Give `perms` the replaced file's group, or drop its group bits when the stage cannot join +/// that group. A stage already in the group needs no fchown, which some filesystems reject even +/// as a no-op, and dropping the bits there would narrow a mode the replaced file granted. +#[cfg(unix)] +fn adopt_group(fs: &dyn AtomicFs, file: &File, stage_gid: u32, replaced_gid: u32, perms: std::fs::Permissions) -> io::Result { + use std::os::unix::fs::PermissionsExt; + if perms.mode() & 0o070 == 0 || stage_gid == replaced_gid { + return Ok(perms); + } + if fs.set_group(file, replaced_gid).is_ok() { + return Ok(perms); + } + let mut narrowed = perms; + narrowed.set_mode(narrowed.mode() & !0o070); + Ok(narrowed) +} + +/// Create a temporary file in `dir`, fill it with `fill`, give it the permissions and group of +/// the file it replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when +/// the mode already matches after `fill`; the group bits are dropped when the file cannot be put +/// in the replaced file's group, so they never open the file to a group that was not granted +/// them. A leftover file with the same name is skipped. When any step fails, the temporary file +/// is removed. fn stage( fs: &dyn AtomicFs, dir: &Path, @@ -383,6 +410,14 @@ fn stage( if (file.metadata()?.permissions().mode() & 0o7777) == (p.mode() & 0o7777) { return Ok(()); } + // The group bits belong to the replaced file's group, which a new + // inode need not be in (setgid directory, another primary group). + if let Some(replaced) = replaced { + let stage_gid = std::os::unix::fs::MetadataExt::gid(&file.metadata()?); + let replaced_gid = std::os::unix::fs::MetadataExt::gid(replaced); + let perms = adopt_group(fs, &file, stage_gid, replaced_gid, p)?; + return fs.set_permissions(&file, perms); + } } fs.set_permissions(&file, p) }) @@ -678,6 +713,9 @@ mod tests { fixed_mode: Option, fail_sync_dir: bool, fail_normal_create: bool, + /// Simulate a filesystem that refuses the stage's group change. + #[cfg(unix)] + fail_set_group: bool, normal_collisions: Cell, /// Another process creates the target just before the hard link. created_meanwhile: Option<&'static [u8]>, @@ -750,6 +788,15 @@ mod tests { } /// Record permission restoration and payload length, then inject a configured error /// or delegate the mode change to the real filesystem. + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { + self.events.borrow_mut().push("set_group"); + if self.fail_set_group { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: set_group failed")); + } + RealFs.set_group(file, gid) + } + fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { self.events.borrow_mut().push("set_permissions"); #[cfg(unix)] @@ -1090,6 +1137,36 @@ mod tests { Ok(()) } + #[cfg(unix)] + #[test] + fn group_bits_are_dropped_when_the_stage_cannot_join_the_replaced_group() -> io::Result<()> { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let d = TempDir::new("group-fallback"); + let file = File::create(d.0.join("stage"))?; + let gid = file.metadata()?.gid(); + let elsewhere = gid.wrapping_add(1); + + let fs = Faulty { fail_set_group: true, ..Default::default() }; + let mode = adopt_group(&fs, &file, gid, elsewhere, std::fs::Permissions::from_mode(0o640))?.mode(); + assert_eq!(mode & 0o777, 0o600, "group bits are dropped when the group cannot be joined"); + assert!(fs.events.borrow().contains(&"set_group")); + + // No group bits: the group change is never attempted. + let fs = Faulty { fail_set_group: true, ..Default::default() }; + let mode = adopt_group(&fs, &file, gid, elsewhere, std::fs::Permissions::from_mode(0o600))?.mode(); + assert_eq!(mode & 0o777, 0o600); + assert!(!fs.events.borrow().contains(&"set_group")); + + // A stage already in the replaced file's group keeps its bits untouched. + let fs = Faulty { fail_set_group: true, ..Default::default() }; + let mode = adopt_group(&fs, &file, gid, gid, std::fs::Permissions::from_mode(0o640))?.mode(); + assert_eq!(mode & 0o777, 0o640); + assert!(!fs.events.borrow().contains(&"set_group")); + + assert_no_temp(&d.0); + Ok(()) + } + #[cfg(unix)] #[test] fn normal_policy_preserves_existing_modes_with_private_staging() -> io::Result<()> { @@ -1102,6 +1179,11 @@ mod tests { let fs = Faulty { fail_normal_create: true, ..Default::default() }; replace_with_options(&fs, NO_RETRY, &p, NewFilePermissions::PlatformDefault, |f| f.write_all(b"replacement"))?; assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, mode); + assert_eq!( + std::os::unix::fs::MetadataExt::gid(&std::fs::metadata(&p)?), + std::os::unix::fs::MetadataExt::gid(&d.0.metadata()?), + "kept in the directory's group" + ); assert!(!fs.events.borrow().contains(&"create_new_normal")); assert_eq!(*fs.created_modes.borrow(), [0o600]); } diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index d132f23da..ae633a05d 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 decoder and encoder, 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, Vorbis encoder, MP1/MP2 decoders." version.workspace = true edition.workspace = true license.workspace = true @@ -19,24 +19,45 @@ 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, 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"] +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 = [] +# Decode FLAC files and frames natively (`flac::decode`, `flac::Decoder`). +flac-decode = [] # Encode FLAC files. flac-encode = ["craft-media/bitstream"] +# The pure-Rust Vorbis encoder (`vorbis::encoder`) and Ogg Vorbis files through `encode` and +# `encode_ogg_vorbis`. +vorbis-encode = ["craft-media/ogg"] +# The pure-Rust Vorbis decoder (`vorbis::decoder`), packets and whole Ogg Vorbis files. +vorbis-decode = ["craft-media/ogg"] # Codec modules on their own, for packet-level use. aac-decode = ["craft-media/bitstream"] # The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`. aac-encode = ["craft-media/bitstream", "craft-media/isobmff"] opus-decode = [] +# ADPCM (`adpcm`): IMA WAV, Microsoft, Yamaha and Flash (SWF) decoders and encoders. +adpcm = ["craft-media/bitstream"] +# QOA (Quite OK Audio) files: decoder and encoder in the `qoa` module, each on its own. +qoa = ["qoa-decode", "qoa-encode"] +qoa-decode = [] +qoa-encode = [] +# ITU-T G.722 wideband sub-band ADPCM speech codec (64 kbit/s). +g722 = [] +# ITU-T G.726 ADPCM speech codec (16/24/32/40 kbit/s). +g726 = [] opus-encode = [] +# GSM 06.10 full-rate speech: decoder and encoder in the `gsm` module, each on its own. +gsm = ["gsm-decode", "gsm-encode"] +gsm-decode = [] +gsm-encode = [] ac3-decode = ["craft-media/bitstream"] mpa-decode = ["craft-media/bitstream"] # MPEG-1/2 Layer III (MP3) decoder (`mp3::Decoder`). @@ -49,6 +70,16 @@ ac3-encode = ["craft-media/bitstream"] eac3-encode = ["craft-media/bitstream"] # MPEG-1/2 Layer III (MP3) encoder (`mp3`). mp3-encode = ["craft-media/bitstream"] +# Direct Stream Digital (DSD) files: DSF and DSDIFF decoders and DSD-to-PCM decimation. +dsd = [] + +# MPEG-1/2 Layer II (MP2) encoder (`mpa::encoder`). It shares the polyphase analysis filter of the +# MP3 encoder and the tables of the MP1/MP2 decoder. +mpa-encode = ["mpa-decode", "mp3-encode"] +# Bluetooth Low Complexity Subband Coding (SBC) audio codec (`sbc`). +sbc = [] +# Sierra VMD sound decoder (`vmd::Decoder`): 8-bit PCM and 16-bit DPCM. +vmd-decode = [] # Multi-resolution waveform overviews (`peaks`). peaks = [] # Encode AAC channels in parallel (with `aac-encode`). @@ -58,6 +89,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 } @@ -67,6 +99,8 @@ symphonia = { version = "0.6.1", optional = true, default-features = false, feat [dev-dependencies] craft-media-testkit = { workspace = true } +# The VMD demuxer, for the VMD sound decoder's tests. +craft-media = { workspace = true, features = ["vmd"] } proptest = { workspace = true } serde_json = { workspace = true } @@ -74,10 +108,62 @@ serde_json = { workspace = true } name = "audio" required-features = ["decode", "lossless-encode", "peaks"] +[[test]] +name = "vmd" +required-features = ["vmd-decode"] + [[test]] name = "codecs" required-features = ["decode", "encode"] +[[test]] +name = "mp2_encoder_oracle" +required-features = ["mpa-encode"] + +[[test]] +name = "adpcm_oracle" +required-features = ["adpcm"] + +[[test]] +name = "flac_decode" +required-features = ["flac-decode", "flac-encode"] + +[[test]] +name = "vorbis_decode_oracle" +required-features = ["vorbis-decode", "vorbis-encode", "decode"] + +[[test]] +name = "vorbis_decode_hostile" +required-features = ["vorbis-decode", "vorbis-encode"] + +[[test]] +name = "vorbis_decode_synthetic" +required-features = ["vorbis-decode"] + +[[test]] +name = "gsm_oracle" +required-features = ["gsm"] + +[[test]] +name = "qoa_oracle" +required-features = ["qoa"] + +[[test]] +name = "dsd_oracle" +required-features = ["dsd"] + +[[test]] +name = "g722_oracle" +required-features = ["g722"] + +[[test]] +name = "g726_oracle" +required-features = ["g726"] + +[[test]] +name = "sbc_oracle" +required-features = ["sbc"] + [[example]] name = "info" required-features = ["decode"] @@ -93,3 +179,11 @@ required-features = ["decode"] [[example]] name = "encode" required-features = ["lossless-encode", "aac-encode"] + +[[test]] +name = "dsd_bounds" +required-features = ["dsd"] + +[[test]] +name = "dsd_metadata" +required-features = ["dsd"] diff --git a/crates/audio/README.md b/crates/audio/README.md index 5a5df4f2f..bd80b5406 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -29,19 +29,26 @@ 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, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-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`, `vorbis-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | | `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | +| `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | | `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` | | `alac-decode` | `alac::Decoder` | none | | `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` | | `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none | +| `vorbis-encode` | `vorbis::encoder::Encoder` (pure Rust); `encode_ogg_vorbis`, `encode_ogg` and `encode` for Ogg Vorbis files (whole buffer; not `FileEncoder`) | craft-media `ogg` | +| `vorbis-decode` | `vorbis::decoder::Decoder` (packets), `vorbis::decoder::decode_ogg` (whole Ogg Vorbis files); native Vorbis I: floors 0 and 1, residues 0 to 2, channel coupling, both block sizes. `decode` still reads Vorbis files through symphonia | craft-media `ogg` | | `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` | | `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` | | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | | `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` | | `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` | +| `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` | +| `adpcm` | `adpcm::{ima, ms, yamaha, swf}`: decoders and encoders for IMA WAV, Microsoft, Yamaha and Flash ADPCM | craft-media `bitstream` | +| `gsm-decode`, `gsm-encode` (`gsm`) | `gsm::Decoder`, `gsm::Encoder`, `gsm::decode`, `gsm::encode`: GSM 06.10 full-rate speech, bit-exact, raw `.gsm` and WAV (GSM 6.10) packings | none | +| `vmd-decode` | `vmd::Decoder`: Sierra VMD sound (8-bit PCM and 16-bit DPCM), frame by frame from `craft_media::vmd` | none | | `peaks` | `peaks::Peaks` | none | | `rayon` | parallel AAC encoding (with `aac-encode`) | `rayon` | | `serde` | `Serialize`/`Deserialize` on the shared types | `serde` | @@ -355,8 +362,12 @@ 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: +Opus goes into Ogg, Matroska/WebM or MP4: + +- **Ogg (`.opus`):** `craft_media::ogg::PageWriter` with `head` and `opus_tags` as the two header + packets, each packet's granule position the samples decoded so far (pre-skip included, as + the input above starts with it), and `finish(Some(pre_skip + length))` to trim the end + (RFC 7845 §4). - **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 @@ -368,6 +379,27 @@ Matroska/WebM or MP4: timescale), `segment_duration` the audio's length (movie timescale), `media_rate` `0x0001_0000`. +### Encode Ogg Vorbis + +```rust +use craft_audio::{OggVorbisOptions, encode_ogg_vorbis}; + +// 1–8 channels in Vorbis order (5.1: L C R Ls Rs LFE), any sample rate. +let opts = OggVorbisOptions::new(6.0).with_tag("TITLE", "Take 3").with_tag("ARTIST", "Me"); +let ogg: Vec = encode_ogg_vorbis(&buf, &opts)?; +``` + +The encoder is pure Rust (`vorbis::encoder`, from FilmCraft #4481) and builds for wasm32. Quality +runs from -1 to 10 at a variable bit rate: about 18 kbit/s per channel at -1, 100 at 6 and 140 +at 10 on music. `encode` with `EncodeFormat::Ogg` takes a WAV-order layout and writes it in +Vorbis order; its `RateControl::Bitrate` (64–500 kbit/s) picks the quality whose nominal rate +that is (`quality_for_bitrate`), and `RateControl::Quality` 0.0–1.0 is quality -1 to 10. For +streaming, feed `vorbis::encoder::Encoder` and write its packets with `craft_media::ogg::PageWriter` +(identification, `vorbis_comment`, setup, then the audio with each packet's granule position). + +Not yet: short blocks (transients may pre-echo), channel coupling (stereo costs +about twice mono) and bit-rate management. + ### Waveform overviews ```rust @@ -538,6 +570,7 @@ Each codec module's rustdoc lists the coding tools it implements. | 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 | +| MP2 encoder (`mpa::encoder`) | ISO/IEC 11172-3 (§2.4, Annex B and C), 13818-3 | Layer II, constant bit rate, mono or stereo (no joint stereo), 32/44.1/48 kHz at the spec's rate/mode pairs and 16/22.05/24 kHz at 8–160 kbit/s; no CRC | our decoder and ffmpeg decode the frames; SNR of 20–37 dB on tone mixes, and the 481-sample filter delay matches | | MP3 decoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, MPEG-1/2/2.5, 8–48 kHz, every bit rate, CBR and VBR; mono, stereo, dual channel, joint stereo (mid/side and intensity); long, short and mixed blocks; bit reservoir; CRC read, not checked; Xing / Info / VBRI and LAME tags; no free format (read through symphonia) | ffmpeg's float decoder: 127–131 dB SNR on LAME streams of every sampling frequency (CBR, VBR, CRC, no reservoir, transients with short blocks) and on this crate's encoder's; intensity stereo and mixed blocks through LAME frames edited to use them (112–131 dB) | | MP3 encoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, constant bit rate: 32–320 kbit/s at 32/44.1/48 kHz, 8–160 kbit/s at 16/22.05/24 kHz; mono, stereo, joint stereo (mid/side); bit reservoir; long blocks only; no Xing/Info tag, VBR, CRC or free format | ffmpeg decodes every Huffman code as intended; full encodes at every sampling frequency checked with ffprobe and by SNR of ffmpeg's decode | | ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder, same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | @@ -704,6 +737,7 @@ the full tests with ffmpeg and the vectors required. | 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) | +| Vorbis encoder | FilmCraft `filmcraft-vorbis` by @JordyUSA ([storytold/filmcraft#4481](https://github.com/storytold/filmcraft/pull/4481)), with partitions of whole sample frames so libvorbis reads surround | Where apps had overlapping implementations, the one that measured better was kept, with the tests of both: @@ -761,3 +795,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/src/aac/config.rs b/crates/audio/src/aac/config.rs index 88be1e214..3d12b0343 100644 --- a/crates/audio/src/aac/config.rs +++ b/crates/audio/src/aac/config.rs @@ -343,6 +343,51 @@ impl AudioSpecificConfig { } } +/// Why an AudioSpecificConfig prefix cannot be written as an ADTS header. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AdtsConfigError { + /// Fewer than two bytes were supplied. + Short, + /// The prefix names a profile, indexed rate or channel configuration ADTS cannot carry. + Unsupported { + /// Audio object type from the prefix. + object_type: u8, + /// Sampling frequency index from the prefix. + sf_index: u8, + /// Channel configuration from the prefix. + channel_config: u8, + }, +} + +/// ADTS fixed fields taken from the prefix of an AudioSpecificConfig. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AdtsConfig { + /// Audio object type, 1 through 4. + pub object_type: u8, + /// Indexed sample rate, 0 through 12. + pub sf_index: u8, + /// Channel configuration, 1 through 7. + pub channel_config: u8, +} +impl AdtsConfig { + /// Parse only the first two ASC bytes. Unlike a decoder's full ASC parser, this accepts all + /// four object types representable by ADTS and rejects configurations needing a PCE. + pub fn from_asc_prefix(asc: &[u8]) -> std::result::Result { + let (Some(&a), Some(&b)) = (asc.first(), asc.get(1)) else { return Err(AdtsConfigError::Short) }; + let object_type = a >> 3; + let sf_index = ((a & 7) << 1) | (b >> 7); + let channel_config = (b >> 3) & 15; + if !(1..=4).contains(&object_type) || sf_index > 12 || !(1..=7).contains(&channel_config) { + return Err(AdtsConfigError::Unsupported { object_type, sf_index, channel_config }); + } + Ok(Self { object_type, sf_index, channel_config }) + } + /// Write a no-CRC ADTS header with variable-rate buffer fullness for one payload. + pub fn header(self, payload_len: usize) -> Result<[u8; 7]> { + AdtsHeader::write(self.object_type, self.sf_index, self.channel_config, payload_len, 0x7ff) + } +} + /// A parsed ADTS header. #[non_exhaustive] #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -519,6 +564,15 @@ mod tests { assert_eq!(AudioSpecificConfig::parse(&asc.to_bytes().unwrap()).unwrap(), asc); } + #[test] + fn adts_config_preserves_prefix_and_frame_limits() { + let config = AdtsConfig::from_asc_prefix(&[0x12, 0x10]).unwrap(); + assert_eq!(config.header(100).unwrap(), AdtsHeader::write(2, 4, 2, 100, 0x7ff).unwrap()); + assert!(config.header(8185).is_err()); + assert_eq!(AdtsConfig::from_asc_prefix(&[]), Err(AdtsConfigError::Short)); + assert!(matches!(AdtsConfig::from_asc_prefix(&[0x2a, 0x10]), Err(AdtsConfigError::Unsupported { object_type: 5, .. }))); + } + #[test] fn adts_headers_refuse_fields_they_cannot_hold() { for (object_type, sf_index, channel_config) in [(0, 4, 2), (5, 4, 2), (29, 4, 2), (2, 13, 2), (2, 15, 2), (2, 4, 8), (2, 4, 11), (2, 4, 12)] { diff --git a/crates/audio/src/aac/mod.rs b/crates/audio/src/aac/mod.rs index f423a4e22..fb79ae743 100644 --- a/crates/audio/src/aac/mod.rs +++ b/crates/audio/src/aac/mod.rs @@ -60,7 +60,7 @@ mod tns; #[cfg(feature = "aac-decode")] pub(crate) use config::split_adts_upto; -pub use config::{AdtsHeader, AudioSpecificConfig, ElementType, ProgramConfig, config_layout, split_adts}; +pub use config::{AdtsConfig, AdtsConfigError, AdtsHeader, AudioSpecificConfig, ElementType, ProgramConfig, config_layout, split_adts}; #[cfg(feature = "aac-decode")] pub use decoder::Decoder; #[cfg(feature = "aac-encode")] diff --git a/crates/audio/src/adpcm/ima.rs b/crates/audio/src/adpcm/ima.rs new file mode 100644 index 000000000..dcf6958f7 --- /dev/null +++ b/crates/audio/src/adpcm/ima.rs @@ -0,0 +1,247 @@ +//! IMA ADPCM in WAV blocks (format tag 0x0011). +//! +//! A block is, per channel, a 4-byte header (the first sample as `i16` and the step index as `u8`, +//! then a zero byte), then groups of 4 bytes per channel in channel order, each holding eight +//! 4-bit codes, low nibble first. A block of `block_align` bytes holds +//! `(block_align - 4 * channels) * 2 / channels + 1` samples per channel. A code is a sign bit and +//! three magnitude bits: the decoder adds `step/8` plus `step`, `step/2` and `step/4` for each set +//! magnitude bit from the top, then moves the step index by `[-1, -1, -1, -1, 2, 4, 6, 8]`. + +use super::{Error, Result, clip16, step_at}; + +const INDEX_ADJUST: [i32; 8] = [-1, -1, -1, -1, 2, 4, 6, 8]; + +/// The state of one channel's decoder. +#[derive(Clone, Copy)] +struct State { + predictor: i32, + index: i32, +} + +impl State { + /// The sample after code `nibble`. + fn step(&mut self, nibble: u8) -> i16 { + let step = step_at(self.index); + let mut diff = step >> 3; + if nibble & 1 != 0 { + diff += step >> 2; + } + if nibble & 2 != 0 { + diff += step >> 1; + } + if nibble & 4 != 0 { + diff += step; + } + if nibble & 8 != 0 { + diff = -diff; + } + self.predictor = clip16(self.predictor + diff); + self.index = (self.index + INDEX_ADJUST.get(usize::from(nibble & 7)).copied().unwrap_or(0)).clamp(0, 88); + self.predictor as i16 + } + + /// The code that brings the predictor closest to `sample`, applied to the state. + fn encode(&mut self, sample: i16) -> u8 { + let step = step_at(self.index); + let mut diff = i32::from(sample) - self.predictor; + let mut code = 0u8; + if diff < 0 { + code = 8; + diff = -diff; + } + let mut s = step; + for bit in [4u8, 2, 1] { + if diff >= s { + code |= bit; + diff -= s; + } + s >>= 1; + } + self.step(code); + code + } +} + +/// Samples per channel in a block of `block_align` bytes; `None` when the layout is impossible +/// (a block must hold the headers and whole groups of eight samples, and there are 1 to 8 +/// channels). +pub fn samples_per_block(block_align: usize, channels: usize) -> Option { + if !(1..=8).contains(&channels) { + return None; + } + let header = 4 * channels; + let body = block_align.checked_sub(header)?; + if body == 0 || !body.is_multiple_of(4 * channels) { + return None; + } + let per = (body / channels).checked_mul(2)?.checked_add(1)?; + // Callers size interleaved buffers from this value; the full count must fit too. + per.checked_mul(channels)?; + Some(per) +} + +/// Decode one block, appending its samples interleaved by channel to `out`. +pub fn decode_block(block: &[u8], channels: usize, out: &mut Vec) -> Result<()> { + let per = samples_per_block(block.len(), channels).ok_or(Error::Malformed("block size does not fit the channel count"))?; + let mut states = Vec::with_capacity(channels); + for ch in 0..channels { + let h = block.get(4 * ch..4 * ch + 4).ok_or(Error::Malformed("truncated block header"))?; + let index = i32::from(h[2]); + if index > 88 { + return Err(Error::Malformed("step index above 88")); + } + states.push(State { predictor: i32::from(i16::from_le_bytes([h[0], h[1]])), index }); + } + let start = out.len(); + out.resize(start + per * channels, 0); + let samples = out.get_mut(start..).ok_or(Error::Malformed("output"))?; + for (ch, s) in states.iter().enumerate() { + if let Some(o) = samples.get_mut(ch) { + *o = s.predictor as i16; + } + } + let body = block.get(4 * channels..).ok_or(Error::Malformed("truncated block"))?; + for (g, group) in body.chunks_exact(4 * channels).enumerate() { + for (ch, bytes) in group.as_chunks::<4>().0.iter().enumerate() { + let Some(state) = states.get_mut(ch) else { continue }; + for (k, b) in bytes.iter().enumerate() { + for (half, nibble) in [b & 0xF, b >> 4].into_iter().enumerate() { + let t = 1 + g * 8 + k * 2 + half; + if let Some(o) = samples.get_mut(t * channels + ch) { + *o = state.step(nibble); + } + } + } + } + } + Ok(()) +} + +/// Decode a stream of blocks of `block_align` bytes. A final partial block is decoded as far as it +/// holds whole groups. +pub fn decode(data: &[u8], channels: usize, block_align: usize) -> Result> { + samples_per_block(block_align, channels).ok_or(Error::Malformed("block size does not fit the channel count"))?; + let mut out = Vec::new(); + for block in data.chunks(block_align) { + if block.len() == block_align { + decode_block(block, channels, &mut out)?; + } else { + let (header, group) = (4 * channels, 4 * channels); + let whole = block.len().saturating_sub(header) / group * group; + if whole > 0 { + decode_block(block.get(..header + whole).unwrap_or(block), channels, &mut out)?; + } + } + } + Ok(out) +} + +/// The starting step index for a channel whose first samples are `x`: the index whose first +/// codes follow `x` most closely. +fn start_index(first: i16, x: &[i16]) -> i32 { + let mut best = (i64::MAX, 0); + for index in 0..=88 { + let mut st = State { predictor: i32::from(first), index }; + let mut err = 0i64; + for &s in x.iter().take(16) { + let code = st.encode(s); + let _ = code; + err += (i64::from(s) - i64::from(st.predictor)).pow(2); + } + if err < best.0 { + best = (err, index); + } + } + best.1 +} + +/// Encode one block from exactly `samples_per_block * channels` interleaved samples. +pub fn encode_block(samples: &[i16], channels: usize, block_align: usize) -> Result> { + let per = samples_per_block(block_align, channels).ok_or(Error::InvalidInput("block size does not fit the channel count"))?; + if samples.len() != per * channels { + return Err(Error::InvalidInput("a block needs exactly samples_per_block samples per channel")); + } + let mut block = vec![0u8; block_align]; + let mut states = Vec::with_capacity(channels); + for ch in 0..channels { + let col: Vec = samples.iter().skip(ch).step_by(channels).copied().collect(); + let first = col.first().copied().unwrap_or(0); + let st = State { predictor: i32::from(first), index: start_index(first, col.get(1..).unwrap_or(&[])) }; + if let Some(h) = block.get_mut(4 * ch..4 * ch + 4) { + h[..2].copy_from_slice(&first.to_le_bytes()); + h[2] = st.index as u8; + } + states.push(st); + } + let groups = (block_align - 4 * channels) / (4 * channels); + for g in 0..groups { + for ch in 0..channels { + let Some(state) = states.get_mut(ch) else { continue }; + for k in 0..4 { + let mut byte = 0u8; + for half in 0..2 { + let t = 1 + g * 8 + k * 2 + half; + let nibble = state.encode(samples.get(t * channels + ch).copied().unwrap_or(0)); + byte |= nibble << (4 * half); + } + if let Some(b) = block.get_mut(4 * channels + g * 4 * channels + ch * 4 + k) { + *b = byte; + } + } + } + } + Ok(block) +} + +/// Encode interleaved samples as blocks of `block_align` bytes. The last block is padded with +/// copies of the last sample, so a decoder returns up to one block more than was given. +pub fn encode(samples: &[i16], channels: usize, block_align: usize) -> Result> { + let per = samples_per_block(block_align, channels).ok_or(Error::InvalidInput("block size does not fit the channel count"))?; + if !samples.len().is_multiple_of(channels) { + return Err(Error::InvalidInput("the sample count is not a multiple of the channel count")); + } + let mut out = Vec::new(); + for chunk in samples.chunks(per * channels) { + if chunk.len() == per * channels { + out.extend(encode_block(chunk, channels, block_align)?); + } else { + let mut padded = chunk.to_vec(); + let last: Vec = chunk.get(chunk.len().saturating_sub(channels)..).unwrap_or(&[]).to_vec(); + while padded.len() < per * channels { + padded.extend(last.iter().copied().chain(std::iter::repeat(0)).take(channels)); + } + out.extend(encode_block(&padded, channels, block_align)?); + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layout() { + assert_eq!(samples_per_block(256, 1), Some(505)); + assert_eq!(samples_per_block(512, 2), Some(505)); + assert_eq!(samples_per_block(4, 1), None); + assert_eq!(samples_per_block(100, 0), None); + assert_eq!(samples_per_block(258, 2), None); + } + + #[test] + fn unrepresentable_interleaved_layout_is_rejected() { + let align = usize::MAX - 7; + assert_eq!(samples_per_block(align, 2), None); + assert!(encode(&[], 2, align).is_err()); + assert!(encode_block(&[], 2, align).is_err()); + } + + #[test] + fn silence_stays_silent() { + let block = encode_block(&vec![0; 505], 1, 256).unwrap(); + let mut out = Vec::new(); + decode_block(&block, 1, &mut out).unwrap(); + assert!(out.iter().all(|&s| s == 0)); + } +} diff --git a/crates/audio/src/adpcm/mod.rs b/crates/audio/src/adpcm/mod.rs new file mode 100644 index 000000000..da552d3cd --- /dev/null +++ b/crates/audio/src/adpcm/mod.rs @@ -0,0 +1,56 @@ +//! ADPCM: a decoder and an encoder for four families, each on whole blocks or streams of `i16` +//! samples interleaved by channel (feature `adpcm`). +//! +//! - [`ima`]: IMA / DVI ADPCM in WAV blocks (format tag 0x0011): 4 bits per sample, a 4-byte header +//! per channel and groups of eight samples per channel. +//! - [`ms`]: Microsoft ADPCM in WAV blocks (format tag 0x0002): 4 bits per sample, adaptive +//! two-tap prediction with the seven standard coefficient pairs. +//! - [`yamaha`]: Yamaha ADPCM (the YM2608 / AICA family): a raw stream of 4-bit codes. +//! - [`swf`]: the ADPCM of Flash (SWF) audio: 2 to 5 bits per sample, in blocks of 4096 samples. +//! +//! Written from the public descriptions of the algorithms: the IMA Digital Audio Focus and +//! Technical Working Groups' *Recommended Practices for Enhancing Digital Audio Compatibility* +//! (IMA ADPCM), Microsoft's *Multimedia Standards Update* (the WAVE format tags and the block +//! layout of Microsoft ADPCM), the SWF file format specification (the ADPCM section) and the +//! Yamaha ADPCM-B description. ffmpeg is only run as a black-box oracle in the tests. +//! +//! Decoders return errors, never panic, on damaged blocks. Encoders are greedy: they choose each +//! code to bring the decoder's output closest to the sample. + +pub mod ima; +pub mod ms; +pub mod swf; +pub mod yamaha; + +/// What went wrong decoding or encoding ADPCM. +#[non_exhaustive] +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum Error { + /// The data is damaged, truncated or does not fit the stated block layout. + #[error("malformed ADPCM: {0}")] + Malformed(&'static str), + /// The settings or samples given to an encoder cannot be written. + #[error("ADPCM cannot encode: {0}")] + InvalidInput(&'static str), +} + +/// Result with this module's [`Error`]. +pub type Result = std::result::Result; + +/// IMA ADPCM step sizes (the 89-entry table of the IMA recommended practices). +pub(crate) const STEP_TABLE: [i32; 89] = [ + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, + 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, + 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, + 22385, 24623, 27086, 29794, 32767, +]; + +/// Clamp to the 16-bit sample range. +pub(crate) fn clip16(v: i32) -> i32 { + v.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) +} + +/// The step size at `index` (clamped to the table). +pub(crate) fn step_at(index: i32) -> i32 { + STEP_TABLE.get(index.clamp(0, 88) as usize).copied().unwrap_or(7) +} diff --git a/crates/audio/src/adpcm/ms.rs b/crates/audio/src/adpcm/ms.rs new file mode 100644 index 000000000..057f93549 --- /dev/null +++ b/crates/audio/src/adpcm/ms.rs @@ -0,0 +1,244 @@ +//! Microsoft ADPCM in WAV blocks (format tag 0x0002). +//! +//! A block starts, for all channels in turn, with one predictor index (a byte, 0 to 6), then one +//! initial step (`delta`, `i16`), then each channel's second-last sample (`sample1`, `i16`) and +//! last sample (`sample2`, `i16`) before the block; the block's first two samples per channel are +//! `sample2` then `sample1`. The rest is 4-bit two's-complement codes, the first channel in the +//! high nibble. A block of `block_align` bytes holds `(block_align - 7 * channels) * 2 / channels +//! + 2` samples per channel. Each sample is predicted as `(sample1 * c1 + sample2 * c2) / 256` (rounding toward zero) +//! from the block's coefficient pair, plus `code * delta`; then `delta` becomes +//! `max(16, delta * a / 256)`, where `a` is the table entry for the code (`ADAPT`). + +use super::{Error, Result, clip16}; + +/// The seven coefficient pairs `(c1, c2)` every Microsoft ADPCM stream uses. +pub const COEFFICIENTS: [(i32, i32); 7] = [(256, 0), (512, -256), (0, 0), (192, 64), (240, 0), (460, -208), (392, -232)]; +/// How the step moves with the code's unsigned value (the index is the 4-bit pattern). +/// The largest step. The reference keeps it in 16 bits and no real stream gets near this bound; it +/// keeps every product in range however long a damaged block runs. +const MAX_DELTA: i32 = 1 << 24; +const ADAPT: [i32; 16] = [230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230]; + +#[derive(Clone, Copy)] +struct State { + c1: i32, + c2: i32, + delta: i32, + s1: i32, + s2: i32, +} + +impl State { + fn step(&mut self, nibble: u8) -> i16 { + let signed = i32::from(nibble) - if nibble & 8 != 0 { 16 } else { 0 }; + let predicted = (self.s1 * self.c1 + self.s2 * self.c2) / 256; + let sample = clip16(predicted + signed * self.delta); + self.s2 = self.s1; + self.s1 = sample; + let adapt = i64::from(ADAPT.get(usize::from(nibble)).copied().unwrap_or(256)); + let new_delta = (adapt * i64::from(self.delta)) >> 8; + self.delta = (new_delta.min(i64::from(MAX_DELTA)) as i32).max(16); + sample as i16 + } + + /// The code that brings the output closest to `sample`, applied to the state. + fn encode(&mut self, sample: i16) -> u8 { + let predicted = (self.s1 * self.c1 + self.s2 * self.c2) / 256; + let err = i32::from(sample) - predicted; + // round to the nearest multiple of delta + let q = if err >= 0 { (err + self.delta / 2) / self.delta } else { -((-err + self.delta / 2) / self.delta) }; + let code = (q.clamp(-8, 7) & 0xF) as u8; + self.step(code); + code + } +} + +/// Samples per channel in a block of `block_align` bytes; `None` for an impossible layout (1 or 2 +/// channels, and room for the header and at least one code byte). +pub fn samples_per_block(block_align: usize, channels: usize) -> Option { + if !(1..=2).contains(&channels) { + return None; + } + let body = block_align.checked_sub(7 * channels).filter(|&b| b > 0)?; + // codes pair up across channels + let per = (body.checked_mul(2)? / channels).checked_add(2)?; + // Include the header samples and all channels before callers size their buffers. + per.checked_mul(channels)?; + Some(per) +} + +/// Decode one block, appending its samples interleaved by channel to `out`. +pub fn decode_block(block: &[u8], channels: usize, out: &mut Vec) -> Result<()> { + let per = samples_per_block(block.len(), channels).ok_or(Error::Malformed("block size does not fit the channel count"))?; + let header = block.get(..7 * channels).ok_or(Error::Malformed("truncated block header"))?; + let mut states = Vec::with_capacity(channels); + let word = |i: usize| i32::from(i16::from_le_bytes([header.get(i).copied().unwrap_or(0), header.get(i + 1).copied().unwrap_or(0)])); + for ch in 0..channels { + let pred = usize::from(header.get(ch).copied().unwrap_or(0)); + let &(c1, c2) = COEFFICIENTS.get(pred).ok_or(Error::Malformed("predictor index above 6"))?; + states.push(State { c1, c2, delta: word(channels + 2 * ch), s1: word(3 * channels + 2 * ch), s2: word(5 * channels + 2 * ch) }); + } + let start = out.len(); + out.resize(start + per * channels, 0); + let samples = out.get_mut(start..).ok_or(Error::Malformed("output"))?; + for (ch, s) in states.iter().enumerate() { + if let Some(a) = samples.get_mut(ch) { + *a = s.s2 as i16; + } + if let Some(b) = samples.get_mut(channels + ch) { + *b = s.s1 as i16; + } + } + let codes = block.get(7 * channels..).ok_or(Error::Malformed("truncated block"))?; + let mut t = 2 * channels; + for byte in codes { + for nibble in [byte >> 4, byte & 0xF] { + let ch = t % channels; + if let (Some(o), Some(state)) = (samples.get_mut(t), states.get_mut(ch)) { + *o = state.step(nibble); + } + t += 1; + } + } + Ok(()) +} + +/// Decode a stream of blocks of `block_align` bytes. A final partial block is decoded in full if +/// it holds a header and a code byte. +pub fn decode(data: &[u8], channels: usize, block_align: usize) -> Result> { + samples_per_block(block_align, channels).ok_or(Error::Malformed("block size does not fit the channel count"))?; + let mut out = Vec::new(); + for block in data.chunks(block_align) { + if block.len() == block_align || samples_per_block(block.len(), channels).is_some() { + decode_block(block, channels, &mut out)?; + } + } + Ok(out) +} + +/// The squared error of encoding `col` (one channel) from state `st`. +fn trial(mut st: State, col: &[i16]) -> i64 { + let mut err = 0i64; + for &s in col { + st.encode(s); + err += (i64::from(s) - i64::from(st.s1)).pow(2); + } + err +} + +/// Encode one block from exactly `samples_per_block * channels` interleaved samples. Each channel +/// gets the coefficient pair and initial step that code it with the least error. +pub fn encode_block(samples: &[i16], channels: usize, block_align: usize) -> Result> { + let per = samples_per_block(block_align, channels).ok_or(Error::InvalidInput("block size does not fit the channel count"))?; + if samples.len() != per * channels { + return Err(Error::InvalidInput("a block needs exactly samples_per_block samples per channel")); + } + let mut block = vec![0u8; block_align]; + let mut states = Vec::with_capacity(channels); + for ch in 0..channels { + let col: Vec = samples.iter().skip(ch).step_by(channels).copied().collect(); + let (x0, x1) = (col.first().copied().unwrap_or(0), col.get(1).copied().unwrap_or(0)); + let rest = col.get(2..).unwrap_or(&[]); + let mut best: Option<(i64, usize, i32)> = None; + for (p, &(c1, c2)) in COEFFICIENTS.iter().enumerate() { + for delta in [16, 64, 256, 1024] { + let st = State { c1, c2, delta, s1: i32::from(x1), s2: i32::from(x0) }; + let e = trial(st, rest); + if best.is_none_or(|(b, _, _)| e < b) { + best = Some((e, p, delta)); + } + } + } + let (_, p, delta) = best.unwrap_or((0, 0, 16)); + let &(c1, c2) = COEFFICIENTS.get(p).unwrap_or(&(256, 0)); + states.push(State { c1, c2, delta, s1: i32::from(x1), s2: i32::from(x0) }); + let (d, a, b) = (delta as i16, x1, x0); + let put = |block: &mut Vec, at: usize, v: i16| { + if let Some(w) = block.get_mut(at..at + 2) { + w.copy_from_slice(&v.to_le_bytes()); + } + }; + if let Some(h) = block.get_mut(ch) { + *h = p as u8; + } + put(&mut block, channels + 2 * ch, d); + put(&mut block, 3 * channels + 2 * ch, a); + put(&mut block, 5 * channels + 2 * ch, b); + } + let mut t = 2 * channels; + for byte in block.iter_mut().skip(7 * channels) { + let mut b = 0u8; + for half in 0..2 { + let ch = t % channels; + let nibble = match states.get_mut(ch) { + Some(st) => st.encode(samples.get(t).copied().unwrap_or(0)), + None => 0, + }; + b |= nibble << (4 * (1 - half)); + t += 1; + } + *byte = b; + } + Ok(block) +} + +/// Encode interleaved samples as blocks of `block_align` bytes. The last block is padded with +/// copies of the last frame, so a decoder returns up to one block more than was given. +pub fn encode(samples: &[i16], channels: usize, block_align: usize) -> Result> { + let per = samples_per_block(block_align, channels).ok_or(Error::InvalidInput("block size does not fit the channel count"))?; + if !samples.len().is_multiple_of(channels) { + return Err(Error::InvalidInput("the sample count is not a multiple of the channel count")); + } + let mut out = Vec::new(); + for chunk in samples.chunks(per * channels) { + let mut padded = chunk.to_vec(); + let last: Vec = chunk.get(chunk.len().saturating_sub(channels)..).unwrap_or(&[]).to_vec(); + while padded.len() < per * channels { + padded.extend(last.iter().copied().chain(std::iter::repeat(0)).take(channels)); + } + out.extend(encode_block(&padded, channels, block_align)?); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layout() { + assert_eq!(samples_per_block(256, 1), Some(500)); + assert_eq!(samples_per_block(512, 2), Some(500)); + assert_eq!(samples_per_block(7, 1), None); + assert_eq!(samples_per_block(100, 3), None); + } + + #[test] + fn unrepresentable_layouts_are_rejected() { + for (align, channels) in [(usize::MAX / 2 + 7, 1), (usize::MAX / 2 + 14, 2)] { + assert_eq!(samples_per_block(align, channels), None); + assert!(encode(&[], channels, align).is_err()); + assert!(encode_block(&[], channels, align).is_err()); + } + } + + #[test] + fn a_long_run_of_large_codes_cannot_overflow() { + // a step that starts at its largest 16-bit value and grows with every large code + let mut block = vec![0x77u8; 7 + 2000]; + block[..7].copy_from_slice(&[0, 255, 127, 0, 0, 0, 0]); + for b in block.iter_mut().skip(7) { + *b = 0x88; + } + let mut out = Vec::new(); + decode_block(&block, 1, &mut out).unwrap(); + assert_eq!(out.len(), 2000 * 2 + 2); + } + + #[test] + fn bad_predictor_index_is_an_error() { + let mut block = vec![0u8; 64]; + block[0] = 7; + assert!(decode_block(&block, 1, &mut Vec::new()).is_err()); + } +} diff --git a/crates/audio/src/adpcm/swf.rs b/crates/audio/src/adpcm/swf.rs new file mode 100644 index 000000000..2fc780b1d --- /dev/null +++ b/crates/audio/src/adpcm/swf.rs @@ -0,0 +1,168 @@ +//! The ADPCM of Flash (SWF) audio, 2 to 5 bits per sample. +//! +//! The stream starts with two bits, the code size minus 2. It continues in blocks of 4096 samples +//! per channel: each block starts, for every channel, with the first sample (16 bits, signed) and +//! the step index (6 bits, 0 to 88), then 4095 codes per channel, interleaved by sample. All fields +//! are packed most significant bit first. A code is a sign bit and `bits - 1` magnitude bits; the +//! decoder adds `step >> (bits - 1)` plus `step >> k` for each magnitude bit set `k` places below +//! the top one, negated when the sign is set, and moves the step index by the adjustment table of +//! the code size (negative for small magnitudes, positive for large ones). The last block may +//! be shorter. + +use super::{Error, Result, clip16, step_at}; +use craft_media::bitstream::{BitReader, BitWriter}; + +/// Samples per channel in a full block. +pub const BLOCK_SAMPLES: usize = 4096; + +/// The index adjustment for each magnitude, per code size. +fn adjust(bits: u32) -> &'static [i32] { + match bits { + 2 => &[-1, 2], + 3 => &[-1, -1, 2, 4], + 4 => &[-1, -1, -1, -1, 2, 4, 6, 8], + _ => &[-1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16], + } +} + +#[derive(Clone, Copy)] +struct State { + predictor: i32, + index: i32, +} + +impl State { + fn apply(&mut self, code: u32, bits: u32) -> i16 { + let step = step_at(self.index); + let mag = code & ((1 << (bits - 1)) - 1); + let mut diff = step >> (bits - 1); + for k in 0..bits - 1 { + if mag & (1 << (bits - 2 - k)) != 0 { + diff += step >> k; + } + } + if code & (1 << (bits - 1)) != 0 { + diff = -diff; + } + self.predictor = clip16(self.predictor + diff); + self.index = (self.index + adjust(bits).get(mag as usize).copied().unwrap_or(0)).clamp(0, 88); + self.predictor as i16 + } + + fn encode(&mut self, sample: i16, bits: u32) -> u32 { + let step = step_at(self.index); + let mut diff = i32::from(sample) - self.predictor; + let mut code = 0u32; + if diff < 0 { + code = 1 << (bits - 1); + diff = -diff; + } + let mut s = step; + for k in 0..bits - 1 { + if diff >= s { + code |= 1 << (bits - 2 - k); + diff -= s; + } + s >>= 1; + } + self.apply(code, bits); + code + } +} + +/// Decode a stream. `channels` is 1 or 2; the code size comes from the stream's first two bits. +/// The result holds every sample up to the end of the data (a last block cut short decodes as +/// far as it goes). +pub fn decode(data: &[u8], channels: usize) -> Result> { + if !(1..=2).contains(&channels) { + return Err(Error::Malformed("Flash ADPCM has one or two channels")); + } + let mut r = BitReader::new(data); + let bits = r.read_bits(2).map_err(|_| Error::Malformed("empty stream"))? + 2; + let mut out = Vec::new(); + let header_bits = channels * 22; + while r.bits_left() >= header_bits { + let mut states = Vec::with_capacity(channels); + for _ in 0..channels { + let sample = r.read_bits(16).map_err(|_| Error::Malformed("truncated block"))? as u16 as i16; + let index = r.read_bits(6).map_err(|_| Error::Malformed("truncated block"))? as i32; + if index > 88 { + return Err(Error::Malformed("step index above 88")); + } + out.push(sample); + states.push(State { predictor: i32::from(sample), index }); + } + 'block: for _ in 1..BLOCK_SAMPLES { + if r.bits_left() < channels * (bits as usize) { + break 'block; + } + for st in states.iter_mut() { + match r.read_bits(bits) { + Ok(code) => out.push(st.apply(code, bits)), + Err(_) => break 'block, + } + } + } + } + Ok(out) +} + +/// Encode interleaved samples with `bits` (2 to 5) bits per sample. Blocks hold 4096 samples per +/// channel; the stream ends at a byte boundary. +pub fn encode(samples: &[i16], channels: usize, bits: u32) -> Result> { + if !(1..=2).contains(&channels) { + return Err(Error::InvalidInput("Flash ADPCM has one or two channels")); + } + if !(2..=5).contains(&bits) { + return Err(Error::InvalidInput("Flash ADPCM codes have 2 to 5 bits")); + } + if !samples.len().is_multiple_of(channels) { + return Err(Error::InvalidInput("the sample count is not a multiple of the channel count")); + } + let mut w = BitWriter::new(); + w.write_bits(bits - 2, 2); + for block in samples.chunks(BLOCK_SAMPLES * channels) { + let mut states = Vec::with_capacity(channels); + for ch in 0..channels { + let col: Vec = block.iter().skip(ch).step_by(channels).copied().collect(); + let first = col.first().copied().unwrap_or(0); + // the index whose first codes follow the signal most closely + let mut best = (i64::MAX, 0); + for index in 0..=63 { + let mut st = State { predictor: i32::from(first), index }; + let mut err = 0i64; + for &s in col.iter().skip(1).take(16) { + st.encode(s, bits); + err += (i64::from(s) - i64::from(st.predictor)).pow(2); + } + if err < best.0 { + best = (err, index); + } + } + w.write_bits(u32::from(first as u16), 16); + w.write_bits(best.1 as u32, 6); + states.push(State { predictor: i32::from(first), index: best.1 }); + } + for frame in block.chunks(channels).skip(1) { + for (st, &s) in states.iter_mut().zip(frame) { + w.write_bits(st.encode(s, bits), bits); + } + } + } + w.align_zero(); + Ok(w.finish()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn settings_are_checked() { + assert!(encode(&[0], 3, 4).is_err()); + assert!(encode(&[0], 1, 1).is_err()); + assert!(encode(&[0], 1, 6).is_err()); + assert!(decode(&[], 1).is_err()); + assert!(decode(&[0], 0).is_err()); + } +} diff --git a/crates/audio/src/adpcm/yamaha.rs b/crates/audio/src/adpcm/yamaha.rs new file mode 100644 index 000000000..22ea0e77f --- /dev/null +++ b/crates/audio/src/adpcm/yamaha.rs @@ -0,0 +1,113 @@ +//! Yamaha ADPCM (the ADPCM-B of the YM2608 and the AICA): a raw stream of 4-bit codes, no header. +//! +//! Each channel starts at predictor 0 and step 127. A code is a sign bit and three magnitude bits; +//! the sample moves by `step * [1, 3, 5, 7, 9, 11, 13, 15][magnitude] / 8` (negative when the sign +//! is set) and the step is multiplied by `[230, 230, 230, 230, 307, 409, 512, 614][magnitude] / 256`, +//! kept within 127 and 24576. One channel: the low nibble of a byte is the first sample. Two +//! channels: the low nibble is the left channel and the high nibble the right one of the same +//! frame. + +use super::{Error, Result, clip16}; + +const SCALE: [i32; 8] = [230, 230, 230, 230, 307, 409, 512, 614]; + +#[derive(Clone, Copy)] +struct State { + predictor: i32, + step: i32, +} + +impl State { + fn new() -> State { + State { predictor: 0, step: 127 } + } + + fn apply(&mut self, nibble: u8) -> i16 { + let m = usize::from(nibble & 7); + let diff = self.step * (2 * m as i32 + 1) / 8; + self.predictor = clip16(self.predictor + if nibble & 8 != 0 { -diff } else { diff }); + self.step = ((self.step * SCALE.get(m).copied().unwrap_or(256)) >> 8).clamp(127, 24_576); + self.predictor as i16 + } + + fn encode(&mut self, sample: i16) -> u8 { + let err = i32::from(sample) - self.predictor; + let m = (err.abs() * 8 / self.step / 2).clamp(0, 7); + // the magnitude whose reconstruction (2m + 1) * step / 8 is nearest + let mut best = (i32::MAX, 0u8); + for cand in [m - 1, m, m + 1] { + let c = cand.clamp(0, 7); + let recon = self.step * (2 * c + 1) / 8; + let e = (err.abs() - recon).abs(); + if e < best.0 { + best = (e, c as u8); + } + } + let nibble = best.1 | if err < 0 { 8 } else { 0 }; + self.apply(nibble); + nibble + } +} + +/// Decode a stream of `channels` (1 or 2) interleaved channels. +pub fn decode(data: &[u8], channels: usize) -> Result> { + if !(1..=2).contains(&channels) { + return Err(Error::Malformed("Yamaha ADPCM has one or two channels")); + } + let mut states = vec![State::new(); channels]; + let mut out = Vec::with_capacity(data.len() * 2); + let mut t = 0usize; + for byte in data { + for nibble in [byte & 0xF, byte >> 4] { + if let Some(st) = states.get_mut(t % channels) { + out.push(st.apply(nibble)); + } + t += 1; + } + } + Ok(out) +} + +/// Encode interleaved samples. With two channels the frame count must be whole bytes, which it +/// always is; with one channel an odd count is padded with a copy of the last sample. +pub fn encode(samples: &[i16], channels: usize) -> Result> { + if !(1..=2).contains(&channels) { + return Err(Error::InvalidInput("Yamaha ADPCM has one or two channels")); + } + if !samples.len().is_multiple_of(channels) { + return Err(Error::InvalidInput("the sample count is not a multiple of the channel count")); + } + let mut states = vec![State::new(); channels]; + let mut out = Vec::with_capacity(samples.len().div_ceil(2)); + let mut t = 0usize; + let mut padded = samples.to_vec(); + if padded.len() % 2 == 1 { + padded.push(padded.last().copied().unwrap_or(0)); + } + for pair in padded.chunks(2) { + let mut byte = 0u8; + for (half, &s) in pair.iter().enumerate() { + let code = match states.get_mut(t % channels) { + Some(st) => st.encode(s), + None => 0, + }; + byte |= code << (4 * half); + t += 1; + } + out.push(byte); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn channel_count_is_checked() { + assert!(decode(&[0], 0).is_err()); + assert!(decode(&[0], 3).is_err()); + assert!(encode(&[0], 3).is_err()); + assert!(encode(&[0, 0, 0], 2).is_err()); + } +} diff --git a/crates/audio/src/dsd/dsdiff.rs b/crates/audio/src/dsd/dsdiff.rs new file mode 100644 index 000000000..f9f12d04d --- /dev/null +++ b/crates/audio/src/dsd/dsdiff.rs @@ -0,0 +1,378 @@ +//! Philips DSDIFF (Direct Stream Digital Interchange File Format, `.dff`) parser and writer. +//! +//! DSDIFF files use an IFF-style big-endian chunk format starting with `FRM8` of type `DSD `: +//! - `FRM8` container chunk containing: +//! - `FVER`: format version (typically 1.5.0.0). +//! - `PROP`: properties chunk with subtype `SND `, containing: +//! - `FS `: sampling frequency (e.g. 2,822,400 Hz for DSD64). +//! - `CHNL`: channel count and 4-character channel ID codes (`SLFT`, `SRGT`, etc.). +//! - `CMPR`: compression type (`DSD ` for uncompressed, `DST ` for compressed). +//! - `DSD `: audio data chunk containing channel-interleaved 1-bit samples (MSB-first). +//! - Optional `DIIN`: disc and track information (title, artist). + +use super::{BitOrder, Error, Format, MAX_CHANNELS, MAX_DECODE_BYTES, MAX_SAMPLE_RATE, MIN_SAMPLE_RATE, Metadata, RawAudio}; + +/// Decodes 4-byte ASCII channel identifiers into human-readable channel names. +fn channel_id_to_name(id: &[u8; 4]) -> String { + match id { + b"SLFT" => "FrontLeft".to_string(), + b"SRGT" => "FrontRight".to_string(), + b"MLFT" => "Mono/Left".to_string(), + b"MRGT" => "Right".to_string(), + b"C " => "Center".to_string(), + b"LFE " => "LFE".to_string(), + b"LS " => "LeftSurround".to_string(), + b"RS " => "RightSurround".to_string(), + b"CO " => "CenterOverhead".to_string(), + b"LH " => "LeftHeight".to_string(), + b"RH " => "RightHeight".to_string(), + _ => { + if let Ok(s) = std::str::from_utf8(id) { + let trimmed = s.trim(); + if !trimmed.is_empty() { + return trimmed.to_string(); + } + } + format!("Channel {:02X}{:02X}{:02X}{:02X}", id[0], id[1], id[2], id[3]) + } + } +} + +/// The text of a `DITI` or `DIAR` chunk: a four-byte big-endian character count, then that many +/// bytes. `None` when the count is missing or longer than the chunk. +fn diin_text(sub_data: &[u8]) -> Option { + let count = usize::try_from(u32::from_be_bytes(sub_data.get(..4)?.try_into().ok()?)).ok()?; + let text = sub_data.get(4..)?.get(..count)?; + Some(String::from_utf8_lossy(text).trim().to_string()) +} + +/// The channel identifiers DSDIFF 1.5 defines for a channel count (stereo, 5 and 5.1 channels); +/// other counts use the generic `C001`, `C002`, ... identifiers. +fn channel_ids(num_channels: usize) -> Vec<[u8; 4]> { + let named: &[&[u8; 4]] = match num_channels { + 1 => &[b"SLFT"], + 2 => &[b"SLFT", b"SRGT"], + 5 => &[b"MLFT", b"MRGT", b"C ", b"LS ", b"RS "], + 6 => &[b"MLFT", b"MRGT", b"C ", b"LFE ", b"LS ", b"RS "], + _ => &[], + }; + if !named.is_empty() { + return named.iter().map(|id| **id).collect(); + } + (1..=num_channels) + .map(|n| { + let s = format!("C{n:03}"); + let mut id = [b' '; 4]; + id.copy_from_slice(&s.as_bytes()[..4]); + id + }) + .collect() +} + +/// Parses the metadata from a DSDIFF file. +pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Error> { + if bytes.len() < 16 { + return Err(Error::UnexpectedEof("DSDIFF file is too short")); + } + + if &bytes[0..4] != b"FRM8" { + return Err(Error::InvalidHeader("missing 'FRM8' magic chunk")); + } + let form_size = u64::from_be_bytes(bytes[4..12].try_into().map_err(|_| Error::UnexpectedEof("FRM8 size"))?); + if &bytes[12..16] != b"DSD " { + return Err(Error::InvalidHeader("invalid FRM8 form type (expected 'DSD ')")); + } + + let total_file_data = bytes.len().saturating_sub(12); + let form_size = usize::try_from(form_size).map_err(|_| Error::MemoryLimitExceeded)?; + if form_size > total_file_data { + return Err(Error::UnexpectedEof("FRM8 chunk extends beyond file size")); + } + + let mut pos = 16; + let end = 12 + form_size; + + let mut sample_rate = None; + let mut channel_names = Vec::new(); + let mut num_channels = None; + let mut is_compressed_dst = false; + let mut dsd_data_offset = None; + let mut dsd_data_len = None; + let mut title = None; + let mut artist = None; + + while pos + 12 <= end { + let chunk_id: [u8; 4] = bytes[pos..pos + 4].try_into().map_err(|_| Error::UnexpectedEof("chunk ID"))?; + let chunk_size = usize::try_from(u64::from_be_bytes(bytes[pos + 4..pos + 12].try_into().map_err(|_| Error::UnexpectedEof("chunk size"))?)) + .map_err(|_| Error::MemoryLimitExceeded)?; + pos += 12; + + if chunk_size > end.saturating_sub(pos) { + return Err(Error::UnexpectedEof("subchunk extends beyond container bounds")); + } + + let chunk_data = &bytes[pos..pos + chunk_size]; + let pad = chunk_size & 1; + pos = pos.saturating_add(chunk_size).saturating_add(pad); + + match &chunk_id { + b"PROP" => { + if chunk_data.len() < 4 { + continue; + } + if &chunk_data[0..4] != b"SND " { + continue; + } + let mut prop_pos = 4; + while prop_pos + 12 <= chunk_data.len() { + let sub_id: [u8; 4] = chunk_data[prop_pos..prop_pos + 4].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk ID"))?; + let sub_size = usize::try_from(u64::from_be_bytes( + chunk_data[prop_pos + 4..prop_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk size"))?, + )) + .map_err(|_| Error::MemoryLimitExceeded)?; + prop_pos += 12; + + if sub_size > chunk_data.len().saturating_sub(prop_pos) { + return Err(Error::UnexpectedEof("PROP subchunk extends beyond bounds")); + } + + let sub_data = &chunk_data[prop_pos..prop_pos + sub_size]; + let sub_pad = sub_size & 1; + prop_pos = prop_pos.saturating_add(sub_size).saturating_add(sub_pad); + + match &sub_id { + b"FS " => { + if sub_data.len() < 4 { + return Err(Error::UnexpectedEof("truncated FS chunk")); + } + if sample_rate.is_some() { + return Err(Error::InvalidHeader("duplicate FS chunk")); + } + let sr = u32::from_be_bytes([sub_data[0], sub_data[1], sub_data[2], sub_data[3]]); + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sr) { + return Err(Error::InvalidHeader("sampling frequency out of range")); + } + sample_rate = Some(sr); + } + b"CHNL" => { + if sub_data.len() < 2 { + return Err(Error::UnexpectedEof("truncated CHNL chunk")); + } + if num_channels.is_some() { + return Err(Error::InvalidHeader("duplicate CHNL chunk")); + } + let n = u16::from_be_bytes([sub_data[0], sub_data[1]]); + if n == 0 || n > MAX_CHANNELS as u16 { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + num_channels = Some(n); + channel_names.clear(); + let mut ch_pos = 2; + while ch_pos + 4 <= sub_data.len() && channel_names.len() < n as usize { + let id: [u8; 4] = [sub_data[ch_pos], sub_data[ch_pos + 1], sub_data[ch_pos + 2], sub_data[ch_pos + 3]]; + channel_names.push(channel_id_to_name(&id)); + ch_pos += 4; + } + } + b"CMPR" if sub_data.len() >= 4 => { + if &sub_data[0..4] == b"DST " { + is_compressed_dst = true; + } else if &sub_data[0..4] != b"DSD " { + return Err(Error::Unsupported("unknown DSDIFF compression type")); + } + } + _ => {} + } + } + } + b"DSD " => { + dsd_data_offset = Some(pos - chunk_size - pad); + dsd_data_len = Some(chunk_size); + } + b"DST " => { + is_compressed_dst = true; + } + b"DIIN" => { + // Parse optional disc info for title and artist. + let mut diin_pos = 0; + while diin_pos + 12 <= chunk_data.len() { + let sub_id = &chunk_data[diin_pos..diin_pos + 4]; + let sub_size = usize::try_from(u64::from_be_bytes( + chunk_data[diin_pos + 4..diin_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("DIIN subchunk size"))?, + )) + .map_err(|_| Error::MemoryLimitExceeded)?; + diin_pos += 12; + if sub_size > chunk_data.len().saturating_sub(diin_pos) { + break; + } + let sub_data = &chunk_data[diin_pos..diin_pos + sub_size]; + let sub_pad = sub_size & 1; + diin_pos = diin_pos.saturating_add(sub_size).saturating_add(sub_pad); + + if sub_id == b"DITI" && title.is_none() { + title = diin_text(sub_data); + } else if sub_id == b"DIAR" && artist.is_none() { + artist = diin_text(sub_data); + } + } + } + _ => {} + } + } + + if is_compressed_dst { + return Err(Error::Unsupported("DST compression in DSDIFF is not yet supported")); + } + + let sample_rate = sample_rate.ok_or(Error::InvalidHeader("missing sample rate ('FS ' chunk)"))?; + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidHeader("sampling frequency out of range")); + } + + let channels = num_channels.ok_or(Error::InvalidHeader("missing channel info ('CHNL' chunk)"))?; + if channels == 0 || channels > MAX_CHANNELS as u16 { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + + let data_offset = dsd_data_offset.ok_or(Error::InvalidHeader("missing audio data ('DSD ' chunk)"))?; + let data_len = dsd_data_len.ok_or(Error::InvalidHeader("missing audio data length"))?; + + let bytes_per_channel = data_len / (channels as usize); + let sample_count = (bytes_per_channel as u64).saturating_mul(8); + + if channel_names.len() < channels as usize { + for c in channel_names.len()..(channels as usize) { + channel_names.push(format!("Channel {}", c + 1)); + } + } + + let metadata = Metadata { format: Format::Dsdiff, sample_rate, channels, sample_count, channel_names, title, artist }; + + Ok((metadata, data_offset, data_len)) +} + +/// Parses a DSDIFF file into raw 1-bit planar channel streams. +pub fn parse_dsdiff(bytes: &[u8]) -> Result { + let (metadata, data_offset, data_len) = parse_dsdiff_header(bytes)?; + let channels = metadata.channels as usize; + let bytes_per_channel = data_len / channels; + + if bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES { + return Err(Error::MemoryLimitExceeded); + } + + let end_offset = data_offset + data_len; + if end_offset > bytes.len() { + return Err(Error::UnexpectedEof("DSD sound data extends beyond file bounds")); + } + let data_slice = &bytes[data_offset..end_offset]; + + let mut channel_bytes: Vec> = Vec::with_capacity(channels); + for _ in 0..channels { + let mut ch_vec = Vec::new(); + ch_vec.try_reserve_exact(bytes_per_channel).map_err(|_| Error::MemoryLimitExceeded)?; + channel_bytes.push(ch_vec); + } + + // De-interleave byte-by-byte: Ch0, Ch1, ... Ch(N-1), Ch0, Ch1 ... + for chunk in data_slice.chunks_exact(channels) { + for (c, &byte) in chunk.iter().enumerate() { + if let Some(ch_vec) = channel_bytes.get_mut(c) { + ch_vec.push(byte); + } + } + } + + Ok(RawAudio { metadata, bit_order: BitOrder::MsbFirst, channel_bytes }) +} + +/// Encodes 1-bit planar audio channels into a valid Philips DSDIFF (`.dff`) file. +pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result, Error> { + if channels.is_empty() || channels.len() > MAX_CHANNELS { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidData("sample rate out of bounds")); + } + + let num_channels = channels.len(); + let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; + let data_size = bytes_per_ch.checked_mul(num_channels).ok_or(Error::MemoryLimitExceeded)?; + // Fixed headers plus four bytes for each channel identifier. + // An odd-sized chunk payload is followed by a pad byte that its size field does not count. + let data_pad = data_size & 1; + let padded_size = data_size.checked_add(data_pad).ok_or(Error::MemoryLimitExceeded)?; + let file_size = super::encoded_size(padded_size, 110 + 4 * num_channels)?; + + // Build PROP subchunks: + // 1. 'FS ' (4 bytes + 12 chunk header) + let mut fs_chunk = Vec::with_capacity(16); + fs_chunk.extend_from_slice(b"FS "); + fs_chunk.extend_from_slice(&4u64.to_be_bytes()); + fs_chunk.extend_from_slice(&sample_rate.to_be_bytes()); + + // 2. 'CHNL' (2 + 4 * num_channels + 12 chunk header) + let chnl_data_len = 2 + 4 * num_channels; + let mut chnl_chunk = Vec::with_capacity(12 + chnl_data_len + 1); + chnl_chunk.extend_from_slice(b"CHNL"); + chnl_chunk.extend_from_slice(&(chnl_data_len as u64).to_be_bytes()); + chnl_chunk.extend_from_slice(&(num_channels as u16).to_be_bytes()); + for id in channel_ids(num_channels) { + chnl_chunk.extend_from_slice(&id); + } + if !chnl_data_len.is_multiple_of(2) { + chnl_chunk.push(0); + } + + // 3. 'CMPR' (4 + 1 + 3 + pad = 8 bytes + 12 chunk header) + let mut cmpr_chunk = Vec::with_capacity(20); + cmpr_chunk.extend_from_slice(b"CMPR"); + cmpr_chunk.extend_from_slice(&8u64.to_be_bytes()); + cmpr_chunk.extend_from_slice(b"DSD "); + cmpr_chunk.push(3); // name len + cmpr_chunk.extend_from_slice(b"DSD"); + + let prop_payload_len = 4 + fs_chunk.len() + chnl_chunk.len() + cmpr_chunk.len(); + let mut prop_chunk = Vec::with_capacity(12 + prop_payload_len); + prop_chunk.extend_from_slice(b"PROP"); + prop_chunk.extend_from_slice(&(prop_payload_len as u64).to_be_bytes()); + prop_chunk.extend_from_slice(b"SND "); + prop_chunk.extend_from_slice(&fs_chunk); + prop_chunk.extend_from_slice(&chnl_chunk); + prop_chunk.extend_from_slice(&cmpr_chunk); + + // FVER chunk (4 bytes payload + 12 chunk header) + let mut fver_chunk = Vec::with_capacity(16); + fver_chunk.extend_from_slice(b"FVER"); + fver_chunk.extend_from_slice(&4u64.to_be_bytes()); + fver_chunk.extend_from_slice(&0x01050000u32.to_be_bytes()); + + // DSD chunk (data_size payload + 12 chunk header) + let mut dsd_chunk_hdr = Vec::with_capacity(12); + dsd_chunk_hdr.extend_from_slice(b"DSD "); + dsd_chunk_hdr.extend_from_slice(&(data_size as u64).to_be_bytes()); + + let frm8_payload_len = file_size - 12; + let mut out = Vec::new(); + out.try_reserve_exact(file_size).map_err(|_| Error::MemoryLimitExceeded)?; + + out.extend_from_slice(b"FRM8"); + out.extend_from_slice(&(frm8_payload_len as u64).to_be_bytes()); + out.extend_from_slice(b"DSD "); + out.extend_from_slice(&fver_chunk); + out.extend_from_slice(&prop_chunk); + out.extend_from_slice(&dsd_chunk_hdr); + + // Interleave channels byte-by-byte. + for i in 0..bytes_per_ch { + for ch_data in channels { + let byte = ch_data.get(i).copied().unwrap_or(super::filter::SILENCE_MSBF); + out.push(byte); + } + } + if data_pad == 1 { + out.push(0); + } + + Ok(out) +} diff --git a/crates/audio/src/dsd/dsf.rs b/crates/audio/src/dsd/dsf.rs new file mode 100644 index 000000000..1fb36c18d --- /dev/null +++ b/crates/audio/src/dsd/dsf.rs @@ -0,0 +1,391 @@ +//! Sony DSF (Direct Stream Digital File) parser and writer. +//! +//! A DSF file consists of three contiguous little-endian chunks: +//! - `'DSD '` chunk (28 bytes): file identification, total size, and metadata offset. +//! - `'fmt '` chunk (52 bytes): sample rate, channel count, sample count, block size. +//! - `'data'` chunk (12 bytes + data): 1-bit audio organized into channel blocks. +//! - Optional ID3v2 metadata chunk located at `metadata_offset`. + +use super::{BitOrder, Error, Format, MAX_BLOCK_SIZE, MAX_CHANNELS, MAX_DECODE_BYTES, MAX_SAMPLE_RATE, MIN_SAMPLE_RATE, Metadata, RawAudio}; + +/// Channel configuration names for DSF channel types 1..=7. +fn dsf_channel_names(channel_type: u32, channel_count: u16) -> Vec { + match channel_type { + 1 => vec!["Mono".to_string()], + 2 => vec!["Left".to_string(), "Right".to_string()], + 3 => vec!["Left".to_string(), "Right".to_string(), "Center".to_string()], + 4 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "BackLeft".to_string(), "BackRight".to_string()], + 5 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "LFE".to_string()], + 6 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "BackLeft".to_string(), "BackRight".to_string()], + 7 => vec![ + "FrontLeft".to_string(), + "FrontRight".to_string(), + "Center".to_string(), + "LFE".to_string(), + "BackLeft".to_string(), + "BackRight".to_string(), + ], + _ => (0..channel_count).map(|c| format!("Channel {}", c + 1)).collect(), + } +} + +/// Attempts to parse basic ID3v2 title and artist tags if present at `offset`. +fn parse_id3v2(bytes: &[u8], offset: usize) -> (Option, Option) { + let Some(id3) = bytes.get(offset..) else { + return (None, None); + }; + if id3.len() < 10 || &id3[..3] != b"ID3" { + return (None, None); + } + + let mut title = None; + let mut artist = None; + + // ID3v2 size is 4 synchsafe bytes at offset 6. + let tag_size = ((id3[6] as usize & 0x7F) << 21) | ((id3[7] as usize & 0x7F) << 14) | ((id3[8] as usize & 0x7F) << 7) | (id3[9] as usize & 0x7F); + + let end = (10 + tag_size).min(id3.len()); + let mut pos = 10; + + // Scan ID3v2.3 / ID3v2.4 frames. + while pos + 10 <= end { + let frame_id = &id3[pos..pos + 4]; + if frame_id[0] == 0 { + break; + } + let raw = [id3[pos + 4], id3[pos + 5], id3[pos + 6], id3[pos + 7]]; + // ID3v2.4 frame sizes are synchsafe; v2.3 ones are plain big-endian. + let frame_size = if id3[3] >= 4 { + if raw.iter().any(|b| b & 0x80 != 0) { + break; + } + ((raw[0] as usize) << 21) | ((raw[1] as usize) << 14) | ((raw[2] as usize) << 7) | raw[3] as usize + } else { + u32::from_be_bytes(raw) as usize + }; + pos += 10; + if frame_size > end.saturating_sub(pos) { + break; + } + + let frame_data = &id3[pos..pos + frame_size]; + pos += frame_size; + + if frame_id == b"TIT2" && title.is_none() { + title = parse_text_frame(frame_data); + } else if frame_id == b"TPE1" && artist.is_none() { + artist = parse_text_frame(frame_data); + } + } + + (title, artist) +} + +fn parse_text_frame(data: &[u8]) -> Option { + if data.is_empty() { + return None; + } + let encoding = data[0]; + let content = &data[1..]; + let text = match encoding { + // ISO-8859-1: every byte is the code point of the same value. + 0 => content.iter().map(|&b| char::from(b)).collect::(), + 3 => String::from_utf8_lossy(content).into_owned(), + // UTF-16 with a byte order mark (which is removed); without one, assume big-endian. + 1 => { + let (big_endian, body) = match content { + [0xFE, 0xFF, rest @ ..] => (true, rest), + [0xFF, 0xFE, rest @ ..] => (false, rest), + _ => (true, content), + }; + utf16(body, big_endian) + } + // UTF-16BE without a byte order mark. + 2 => utf16(content, true), + _ => return None, + }; + let s = text.trim_end_matches('\0').trim().to_string(); + if s.is_empty() { None } else { Some(s) } +} + +fn utf16(bytes: &[u8], big_endian: bool) -> String { + let units: Vec = bytes + .as_chunks::<2>() + .0 + .iter() + .map(|c| if big_endian { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) }) + .collect(); + String::from_utf16_lossy(&units) +} + +/// Parses DSF file metadata, returning the metadata, audio data offset, and block size per channel. +pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> { + let (metadata, offset, _, block_size) = parse_dsf_header_bounded(bytes)?; + Ok((metadata, offset, block_size)) +} + +fn parse_dsf_header_bounded(bytes: &[u8]) -> Result<(Metadata, usize, usize, u32), Error> { + if bytes.len() < 28 + 52 + 12 { + return Err(Error::UnexpectedEof("DSF file header is truncated")); + } + + // 1. 'DSD ' chunk + if &bytes[..4] != b"DSD " { + return Err(Error::InvalidHeader("missing 'DSD ' magic header")); + } + let dsd_chunk_size = u64::from_le_bytes(bytes[4..12].try_into().map_err(|_| Error::UnexpectedEof("DSD chunk size"))?); + if dsd_chunk_size != 28 { + return Err(Error::InvalidHeader("invalid 'DSD ' chunk size (must be 28)")); + } + let file_size = u64::from_le_bytes(bytes[12..20].try_into().map_err(|_| Error::UnexpectedEof("file size"))?); + let metadata_offset = u64::from_le_bytes(bytes[20..28].try_into().map_err(|_| Error::UnexpectedEof("metadata offset"))?); + + if file_size > bytes.len() as u64 { + return Err(Error::UnexpectedEof("declared file size extends beyond buffer")); + } + let file_len = usize::try_from(file_size).map_err(|_| Error::MemoryLimitExceeded)?; + if file_len < 28 + 52 + 12 { + return Err(Error::InvalidHeader("declared file size is smaller than required headers")); + } + let file_bytes = &bytes[..file_len]; + + // 2. 'fmt ' chunk + let fmt_offset = 28; + if &file_bytes[fmt_offset..fmt_offset + 4] != b"fmt " { + return Err(Error::InvalidHeader("missing 'fmt ' chunk header")); + } + let fmt_chunk_size = + u64::from_le_bytes(file_bytes[fmt_offset + 4..fmt_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("fmt chunk size"))?); + if fmt_chunk_size < 52 { + return Err(Error::InvalidHeader("invalid 'fmt ' chunk size (must be at least 52)")); + } + let fmt_size = usize::try_from(fmt_chunk_size).map_err(|_| Error::MemoryLimitExceeded)?; + if fmt_size > file_bytes.len().saturating_sub(fmt_offset) { + return Err(Error::UnexpectedEof("fmt chunk extends beyond file bounds")); + } + + let format_version = + u32::from_le_bytes(file_bytes[fmt_offset + 12..fmt_offset + 16].try_into().map_err(|_| Error::UnexpectedEof("format version"))?); + if format_version != 1 { + return Err(Error::Unsupported("unsupported DSF format version (only version 1 is supported)")); + } + + let format_id = u32::from_le_bytes(file_bytes[fmt_offset + 16..fmt_offset + 20].try_into().map_err(|_| Error::UnexpectedEof("format id"))?); + if format_id != 0 { + return Err(Error::Unsupported("unsupported DSF format id (only raw DSD id=0 is supported)")); + } + + let channel_type = u32::from_le_bytes(file_bytes[fmt_offset + 20..fmt_offset + 24].try_into().map_err(|_| Error::UnexpectedEof("channel type"))?); + let channel_count = + u32::from_le_bytes(file_bytes[fmt_offset + 24..fmt_offset + 28].try_into().map_err(|_| Error::UnexpectedEof("channel count"))?); + if channel_count == 0 || channel_count > MAX_CHANNELS as u32 { + return Err(Error::Unsupported("DSF channel count must be between 1 and 8")); + } + let channels = channel_count as u16; + + let sample_rate = + u32::from_le_bytes(file_bytes[fmt_offset + 28..fmt_offset + 32].try_into().map_err(|_| Error::UnexpectedEof("sampling frequency"))?); + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidHeader("DSF sampling frequency out of valid range")); + } + + let bits_per_sample = + u32::from_le_bytes(file_bytes[fmt_offset + 32..fmt_offset + 36].try_into().map_err(|_| Error::UnexpectedEof("bits per sample"))?); + if bits_per_sample != 1 { + return Err(Error::Unsupported("DSF bits per sample must be 1")); + } + + let sample_count = u64::from_le_bytes(file_bytes[fmt_offset + 36..fmt_offset + 44].try_into().map_err(|_| Error::UnexpectedEof("sample count"))?); + + let block_size_per_channel = + u32::from_le_bytes(file_bytes[fmt_offset + 44..fmt_offset + 48].try_into().map_err(|_| Error::UnexpectedEof("block size per channel"))?); + if block_size_per_channel == 0 || block_size_per_channel > MAX_BLOCK_SIZE { + return Err(Error::InvalidHeader("DSF block size per channel is invalid or too large")); + } + + // 3. 'data' chunk + let data_offset = fmt_offset.saturating_add(fmt_size); + if data_offset.saturating_add(12) > file_bytes.len() { + return Err(Error::UnexpectedEof("missing 'data' chunk header")); + } + if &file_bytes[data_offset..data_offset + 4] != b"data" { + return Err(Error::InvalidHeader("missing 'data' chunk header")); + } + let data_chunk_size = + u64::from_le_bytes(file_bytes[data_offset + 4..data_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("data chunk size"))?); + if data_chunk_size < 12 { + return Err(Error::InvalidHeader("invalid 'data' chunk size (must be at least 12)")); + } + + let payload_offset = data_offset + 12; + let payload_size = usize::try_from(data_chunk_size - 12).map_err(|_| Error::MemoryLimitExceeded)?; + if payload_size > file_bytes.len().saturating_sub(payload_offset) { + return Err(Error::UnexpectedEof("data chunk payload extends beyond file bounds")); + } + let data_end = payload_offset.saturating_add(payload_size); + + // Parse ID3v2 metadata if pointer is valid. + let (title, artist) = if metadata_offset == 0 { + (None, None) + } else { + let meta_offset = usize::try_from(metadata_offset).map_err(|_| Error::MemoryLimitExceeded)?; + if meta_offset < data_end || meta_offset >= file_len { + return Err(Error::InvalidHeader("DSF metadata offset outside declared file bounds")); + } + parse_id3v2(file_bytes, meta_offset) + }; + + let channel_names = dsf_channel_names(channel_type, channels); + + let metadata = Metadata { format: Format::Dsf, sample_rate, channels, sample_count, channel_names, title, artist }; + + Ok((metadata, payload_offset, payload_size, block_size_per_channel)) +} + +/// Parses a DSF file into raw 1-bit planar channel streams. +pub fn parse_dsf(bytes: &[u8]) -> Result { + let (metadata, payload_offset, payload_size, block_size) = parse_dsf_header_bounded(bytes)?; + let block_size = block_size as usize; + let channels = metadata.channels as usize; + + let target_bytes_per_channel = usize::try_from(metadata.sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; + if target_bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES { + return Err(Error::MemoryLimitExceeded); + } + + let slice_size = channels.saturating_mul(block_size); + if slice_size == 0 { + return Err(Error::InvalidHeader("zero slice size")); + } + + // The header validated this range. Trailing ID3 or other bytes are not audio, + // even if sample_count asks for more samples than the data chunk contains. + let payload = &bytes[payload_offset..payload_offset + payload_size]; + let num_slices = payload.len() / slice_size; + + let mut channel_bytes: Vec> = Vec::with_capacity(channels); + for _ in 0..channels { + let mut ch_vec = Vec::new(); + ch_vec.try_reserve_exact(target_bytes_per_channel).map_err(|_| Error::MemoryLimitExceeded)?; + channel_bytes.push(ch_vec); + } + + for s in 0..num_slices { + let slice_base = s * slice_size; + for (c, ch_vec) in channel_bytes.iter_mut().enumerate() { + let ch_start = slice_base + c * block_size; + let ch_end = ch_start + block_size; + if let Some(block) = payload.get(ch_start..ch_end) { + let remaining = target_bytes_per_channel.saturating_sub(ch_vec.len()); + let take = block.len().min(remaining); + ch_vec.extend_from_slice(&block[..take]); + } + } + } + + // Handle any trailing partial slice. + let remainder = payload.len() % slice_size; + if remainder > 0 { + let slice_base = num_slices * slice_size; + for (c, ch_vec) in channel_bytes.iter_mut().enumerate() { + let ch_start = slice_base + c * block_size; + if ch_start < payload.len() { + let ch_end = (ch_start + block_size).min(payload.len()); + let block = &payload[ch_start..ch_end]; + let remaining = target_bytes_per_channel.saturating_sub(ch_vec.len()); + let take = block.len().min(remaining); + ch_vec.extend_from_slice(&block[..take]); + } + } + } + + // Pad with silence (0x69) if the file had fewer bytes than required by sample_count. + for ch_vec in &mut channel_bytes { + if ch_vec.len() < target_bytes_per_channel { + ch_vec.resize(target_bytes_per_channel, super::filter::SILENCE_LSBF); + } + } + + Ok(RawAudio { metadata, bit_order: BitOrder::LsbFirst, channel_bytes }) +} + +fn unsupported_channel_layout() -> Result { + Err(Error::Unsupported("DSF has no channel type for this channel count (1 to 6 are supported)")) +} + +/// Encodes 1-bit planar audio channels into a valid Sony DSF file. +pub fn write_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result, Error> { + if channels.is_empty() || channels.len() > MAX_CHANNELS { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidData("sample rate out of bounds")); + } + if block_size > MAX_BLOCK_SIZE { + return Err(Error::InvalidData("DSF block size exceeds maximum")); + } + let block_size = if block_size == 0 { 4096 } else { block_size as usize }; + + let num_channels = channels.len(); + let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; + let num_blocks = bytes_per_ch.div_ceil(block_size); + let payload_size = num_blocks.checked_mul(num_channels).and_then(|n| n.checked_mul(block_size)).ok_or(Error::MemoryLimitExceeded)?; + let file_size = super::encoded_size(payload_size, 92)?; + + let data_chunk_size = 12u64 + payload_size as u64; + + let mut out = Vec::new(); + out.try_reserve_exact(file_size).map_err(|_| Error::MemoryLimitExceeded)?; + + // 1. 'DSD ' chunk (28 bytes) + out.extend_from_slice(b"DSD "); + out.extend_from_slice(&28u64.to_le_bytes()); + out.extend_from_slice(&(file_size as u64).to_le_bytes()); + out.extend_from_slice(&0u64.to_le_bytes()); // metadata offset = 0 + + // 2. 'fmt ' chunk (52 bytes) + out.extend_from_slice(b"fmt "); + out.extend_from_slice(&52u64.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); // format_version = 1 + out.extend_from_slice(&0u32.to_le_bytes()); // format_id = 0 (raw DSD) + // DSF channel types: 1 mono, 2 stereo, 3 L R C, 4 quad, 6 five channels, 7 5.1. + let channel_type = match num_channels { + 1 => 1u32, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 6, + 6 => 7, + _ => unsupported_channel_layout()?, + }; + out.extend_from_slice(&channel_type.to_le_bytes()); + out.extend_from_slice(&(num_channels as u32).to_le_bytes()); + out.extend_from_slice(&sample_rate.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); // bits_per_sample = 1 + out.extend_from_slice(&sample_count.to_le_bytes()); + out.extend_from_slice(&(block_size as u32).to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); // reserved + + // 3. 'data' chunk + out.extend_from_slice(b"data"); + out.extend_from_slice(&data_chunk_size.to_le_bytes()); + + for b in 0..num_blocks { + let blk_start = b * block_size; + let blk_end = blk_start + block_size; + for ch_data in channels { + let available = if blk_start < ch_data.len() { + let end = blk_end.min(ch_data.len()); + &ch_data[blk_start..end] + } else { + &[] + }; + out.extend_from_slice(available); + if available.len() < block_size { + out.resize(out.len() + (block_size - available.len()), super::filter::SILENCE_LSBF); + } + } + } + + Ok(out) +} diff --git a/crates/audio/src/dsd/filter.rs b/crates/audio/src/dsd/filter.rs new file mode 100644 index 000000000..ec815afd1 --- /dev/null +++ b/crates/audio/src/dsd/filter.rs @@ -0,0 +1,288 @@ +//! DSD-to-PCM decimation filter. +//! +//! Direct Stream Digital (DSD) uses 1-bit Sigma-Delta modulation sampled at high rates +//! (2,822,400 Hz for DSD64, 5,644,800 Hz for DSD128, etc.). Decimation to multi-bit PCM +//! involves low-pass filtering to attenuate high-frequency quantization noise followed +//! by downsampling. +//! +//! This module provides a 96-tap symmetric FIR decimation filter that downsamples 1-bit DSD +//! to multi-bit PCM at 1/8th of the DSD sampling rate (e.g. 352,800 Hz for DSD64). Further +//! integer decimation (to 176.4 kHz, 88.2 kHz, or 44.1 kHz) is supported via subsequent +//! downsampling stages. + +use super::{BitOrder, Error, MAX_DECODE_BYTES}; + +/// 96-tap symmetric FIR decimation filter coefficients for decimation by 8. +/// +/// Output is normalized so that alternating silence bits (0x69 or 0xAA) decode near 0.0, +/// and full-scale runs of 1s or 0s decode near +1.0 and -1.0. +#[allow(clippy::excessive_precision)] +pub const TAPS_96: [f32; 96] = [ + 2.9802322388e-08_f32, + 1.1920928955e-07_f32, + 3.5762786865e-07_f32, + 7.4505805969e-07_f32, + 1.3113021851e-06_f32, + 1.9371509552e-06_f32, + 2.1755695343e-06_f32, + 1.2516975403e-06_f32, + -1.9967556000e-06_f32, + -9.1493129730e-06_f32, + -2.1725893021e-05_f32, + -4.0739774704e-05_f32, + -6.5773725510e-05_f32, + -9.3966722488e-05_f32, + -1.1900067329e-04_f32, + -1.3050436974e-04_f32, + -1.1405348778e-04_f32, + -5.2779912949e-05_f32, + 7.0035457611e-05_f32, + 2.6643276215e-04_f32, + 5.3817033768e-04_f32, + 8.7043642998e-04_f32, + 1.2266933918e-03_f32, + 1.5456080437e-03_f32, + 1.7420351505e-03_f32, + 1.7137229443e-03_f32, + 1.3538300991e-03_f32, + 5.7008862495e-04_f32, + -6.9221854210e-04_f32, + -2.4250447750e-03_f32, + -4.5351684093e-03_f32, + -6.8288743496e-03_f32, + -9.0079009533e-03_f32, + -1.0681360960e-02_f32, + -1.1394292116e-02_f32, + -1.0672420263e-02_f32, + -8.0802738667e-03_f32, + -3.2847225666e-03_f32, + 3.8830339909e-03_f32, + 1.3377487659e-02_f32, + 2.4909228086e-02_f32, + 3.7942945957e-02_f32, + 5.1726281643e-02_f32, + 6.5348774195e-02_f32, + 7.7825516462e-02_f32, + 8.8196486235e-02_f32, + 9.5628470182e-02_f32, + 9.9507331848e-02_f32, + 9.9507331848e-02_f32, + 9.5628470182e-02_f32, + 8.8196486235e-02_f32, + 7.7825516462e-02_f32, + 6.5348774195e-02_f32, + 5.1726281643e-02_f32, + 3.7942945957e-02_f32, + 2.4909228086e-02_f32, + 1.3377487659e-02_f32, + 3.8830339909e-03_f32, + -3.2847225666e-03_f32, + -8.0802738667e-03_f32, + -1.0672420263e-02_f32, + -1.1394292116e-02_f32, + -1.0681360960e-02_f32, + -9.0079009533e-03_f32, + -6.8288743496e-03_f32, + -4.5351684093e-03_f32, + -2.4250447750e-03_f32, + -6.9221854210e-04_f32, + 5.7008862495e-04_f32, + 1.3538300991e-03_f32, + 1.7137229443e-03_f32, + 1.7420351505e-03_f32, + 1.5456080437e-03_f32, + 1.2266933918e-03_f32, + 8.7043642998e-04_f32, + 5.3817033768e-04_f32, + 2.6643276215e-04_f32, + 7.0035457611e-05_f32, + -5.2779912949e-05_f32, + -1.1405348778e-04_f32, + -1.3050436974e-04_f32, + -1.1900067329e-04_f32, + -9.3966722488e-05_f32, + -6.5773725510e-05_f32, + -4.0739774704e-05_f32, + -2.1725893021e-05_f32, + -9.1493129730e-06_f32, + -1.9967556000e-06_f32, + 1.2516975403e-06_f32, + 2.1755695343e-06_f32, + 1.9371509552e-06_f32, + 1.3113021851e-06_f32, + 7.4505805969e-07_f32, + 3.5762786865e-07_f32, + 1.1920928955e-07_f32, + 2.9802322388e-08_f32, +]; + +/// The number of filter history bytes (96 taps / 8 bits per byte = 12 bytes). +pub const FILTER_BYTES: usize = 12; + +/// Standard DSD silence pattern byte for LSB-first ordering (Sony DSF). +pub const SILENCE_LSBF: u8 = 0x69; + +/// Standard DSD silence pattern byte for MSB-first ordering (Philips DSDIFF). +pub const SILENCE_MSBF: u8 = 0xAA; + +/// Precomputes lookup table entries for byte position `k` (0..12) and byte value `v` (0..256). +/// +/// In LSB-first order, bit `b` of input byte `k` corresponds to tap `k * 8 + b`. +#[inline] +fn byte_lut(k: usize, byte_val: u8) -> f32 { + let mut sum = 0.0_f32; + let base_tap = k * 8; + for b in 0..8 { + if ((byte_val >> b) & 1) != 0 + && let Some(tap) = TAPS_96.get(base_tap + b) + { + sum += 2.0 * *tap; + } + } + sum +} + +// Both the first-stage samples and the secondary output coexist during filtering. +pub(super) fn allocation_sizes(len: usize, factor: u32) -> Result<(usize, usize), Error> { + if !matches!(factor, 8 | 16 | 32 | 64) { + return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64")); + } + let stage = len.checked_mul(std::mem::size_of::()).ok_or(Error::MemoryLimitExceeded)?; + let output = (len / (factor / 8) as usize).checked_mul(std::mem::size_of::()).ok_or(Error::MemoryLimitExceeded)?; + let working = if factor == 8 { stage } else { stage.checked_add(output).ok_or(Error::MemoryLimitExceeded)? }; + if working > MAX_DECODE_BYTES { + return Err(Error::MemoryLimitExceeded); + } + Ok((working, output)) +} + +/// Unity-DC-gain low-pass taps for decimating by `ratio` (cutoff 0.45 / ratio cycles per sample). +fn decimation_taps(ratio: usize) -> Vec { + let n = 24 * ratio + 1; + let mid = (n / 2) as f64; + let fc = 0.45 / ratio as f64; + let mut taps: Vec = (0..n) + .map(|k| { + let x = k as f64 - mid; + let sinc = if x == 0.0 { 2.0 * fc } else { (2.0 * std::f64::consts::PI * fc * x).sin() / (std::f64::consts::PI * x) }; + let t = k as f64 / (n - 1) as f64; + let window = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * t).cos() + 0.08 * (4.0 * std::f64::consts::PI * t).cos(); + sinc * window + }) + .collect(); + let sum: f64 = taps.iter().sum(); + for t in &mut taps { + *t /= sum; + } + taps.into_iter().map(|t| t as f32).collect() +} + +/// Decimates 1-bit DSD audio bytes for a single channel to `f32` PCM. +/// +/// The default decimation factor is 8 (1 output float per input byte). +/// When `factor` is 16, 32, or 64, the 1/8 output is further downsampled +/// by 2, 4, or 8 respectively. +pub fn decimate_channel(channel_bytes: &[u8], bit_order: BitOrder, factor: u32) -> Result, Error> { + allocation_sizes(channel_bytes.len(), factor)?; + let num_bytes = channel_bytes.len(); + + // Build the 12 x 256 lookup table for fast convolution. + // 12 * 256 * 4 bytes = 12 KB, sits comfortably in L1 cache. + let mut lut = [[0.0_f32; 256]; FILTER_BYTES]; + for (k, lut_k) in lut.iter_mut().enumerate() { + for (v, cell) in lut_k.iter_mut().enumerate() { + *cell = byte_lut(k, v as u8); + } + } + + let mut stage1 = Vec::new(); + stage1.try_reserve_exact(num_bytes).map_err(|_| Error::MemoryLimitExceeded)?; + + // History buffer holds the most recent 12 bytes in LSB-first order. + // Pre-filled with silence (0x69). + let mut history = [SILENCE_LSBF; FILTER_BYTES]; + + for &raw_byte in channel_bytes { + let byte = match bit_order { + BitOrder::LsbFirst => raw_byte, + BitOrder::MsbFirst => raw_byte.reverse_bits(), + }; + + // Shift history left by 1 and push current byte to the end. + history.copy_within(1.., 0); + if let Some(last) = history.last_mut() { + *last = byte; + } + + let mut sample = -1.0_f32; + for (k, &hist_byte) in history.iter().enumerate() { + if let Some(lut_k) = lut.get(k) + && let Some(&contrib) = lut_k.get(hist_byte as usize) + { + sample += contrib; + } + } + + stage1.push(sample); + } + + if factor == 8 { + return Ok(stage1); + } + + // Secondary decimation by ratio = factor / 8 (2, 4, or 8). A plain average attenuates the band + // between the new Nyquist rate and the stage-1 rate too little (about -7.6 dB at 29.4 kHz for + // factor 64), so low-pass first: a Blackman-windowed sinc with its cutoff at 90% of the new + // Nyquist frequency, evaluated only at the kept samples. + let ratio = (factor / 8) as usize; + let out_len = stage1.len() / ratio; + let mut out = Vec::new(); + out.try_reserve_exact(out_len).map_err(|_| Error::MemoryLimitExceeded)?; + + let taps = decimation_taps(ratio); + let half = (taps.len() / 2) as isize; + let last = stage1.len() as isize - 1; + for i in 0..out_len { + let center = (i * ratio + ratio / 2) as isize; + let mut acc = 0.0_f32; + for (k, &w) in taps.iter().enumerate() { + let idx = (center + k as isize - half).clamp(0, last); + if let Some(&x) = stage1.get(idx as usize) { + acc += w * x; + } + } + out.push(acc); + } + + Ok(out) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod decimation_tests { + use super::*; + + /// A full-scale 29.4 kHz square wave in DSD64 (six bytes of ones, six of zeros) lies between + /// the output Nyquist frequency and the sampling rate of a 44.1 kHz result: it must be + /// attenuated well, not folded down at 0.42 of its amplitude. + #[test] + fn factor_64_attenuates_29_4_khz() { + let mut bytes = Vec::new(); + for _ in 0..2000 { + bytes.extend_from_slice(&[0xFF; 6]); + bytes.extend_from_slice(&[0x00; 6]); + } + let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap(); + let mid = &out[out.len() / 4..out.len() * 3 / 4]; + let peak = mid.iter().fold(0.0_f32, |m, v| m.max(v.abs())); + assert!(peak < 0.05, "peak {peak}"); + } + + #[test] + fn decimation_keeps_dc_level() { + let bytes = vec![0xFF; 4096]; + let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap(); + let mid = out[out.len() / 2]; + assert!((mid - 1.0).abs() < 0.05, "{mid}"); + } +} diff --git a/crates/audio/src/dsd/mod.rs b/crates/audio/src/dsd/mod.rs new file mode 100644 index 000000000..e782b50f0 --- /dev/null +++ b/crates/audio/src/dsd/mod.rs @@ -0,0 +1,275 @@ +//! Direct Stream Digital (DSD) audio: Sony DSF and Philips DSDIFF (`.dff`) readers and +//! DSD-to-PCM decimation. +//! +//! DSD stores 1-bit Pulse Density Modulation (PDM) sampled at high rates (e.g. 2,822,400 Hz +//! for DSD64, 5,644,800 Hz for DSD128, etc.). +//! +//! This module provides: +//! - File parsers for Sony DSF (`.dsf`) and Philips DSDIFF (`.dff`) containers. +//! - Raw 1-bit audio extraction with preservation of native bit ordering (LSB-first for DSF, +//! MSB-first for DSDIFF). +//! - Clean-room 96-tap symmetric FIR decimation filter converting 1-bit PDM to multi-bit PCM +//! (decimation by 8 to 352,800 Hz for DSD64, or downsampled to 176.4, 88.2, or 44.1 kHz). +//! - Reference encoders for generating synthetic DSF and DSDIFF files. + +pub mod dsdiff; +pub mod dsf; +pub mod filter; + +use crate::AudioBuffer; + +/// Maximum number of audio channels supported (1 to 8). +pub const MAX_CHANNELS: usize = 8; + +/// Minimum allowable DSD sample rate in Hz. +pub const MIN_SAMPLE_RATE: u32 = 44_100; + +/// Maximum allowable DSD sample rate in Hz (e.g. DSD1024 at 45.1584 MHz). +pub const MAX_SAMPLE_RATE: u32 = 45_158_400; + +/// Maximum safe block size for DSF channel blocks (16 MiB). +pub const MAX_BLOCK_SIZE: u32 = 16 * 1024 * 1024; + +/// Maximum audio-buffer allocation budget (256 MiB). +/// +/// Raw readers limit their channel bytes; PCM conversion separately limits the +/// simultaneously live PCM output and scratch buffers. Caller-owned raw input, +/// metadata, and the small filter lookup table are not included. +pub const MAX_DECODE_BYTES: usize = 256 * 1024 * 1024; + +/// Maximum encoded container size, including headers and block padding (256 MiB). +pub const MAX_ENCODE_BYTES: usize = 256 * 1024 * 1024; + +fn encoded_size(payload: usize, header: usize) -> Result { + payload.checked_add(header).filter(|&n| n <= MAX_ENCODE_BYTES).ok_or(Error::MemoryLimitExceeded) +} + +// Account for retained channel output plus the current filter's two live buffers. +fn pcm_budget(lengths: impl Iterator, factor: u32) -> Result<(), Error> { + let mut retained = 0usize; + for len in lengths { + let (working, output) = filter::allocation_sizes(len, factor)?; + if retained.checked_add(working).is_none_or(|n| n > MAX_DECODE_BYTES) { + return Err(Error::MemoryLimitExceeded); + } + retained = retained.checked_add(output).ok_or(Error::MemoryLimitExceeded)?; + } + Ok(()) +} + +/// Supported DSD container formats. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Format { + /// Sony DSF (Direct Stream Digital File) format. + Dsf, + /// Philips DSDIFF (Direct Stream Digital Interchange File Format, `.dff`). + Dsdiff, +} + +/// Bit ordering of 1-bit DSD audio samples within bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum BitOrder { + /// Least-significant bit first (LSB-first, as used in DSF). + /// Bit 0 is the earliest temporal sample; bit 7 is the latest. + LsbFirst, + /// Most-significant bit first (MSB-first, as used in DSDIFF). + /// Bit 7 is the earliest temporal sample; bit 0 is the latest. + MsbFirst, +} + +/// Stream properties and metadata parsed from a DSD container header. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Metadata { + /// Container format (DSF or DSDIFF). + pub format: Format, + /// DSD sampling frequency in Hz (e.g. 2,822,400 for DSD64). + pub sample_rate: u32, + /// Number of audio channels (1 to 8). + pub channels: u16, + /// Total number of 1-bit audio samples per channel. + pub sample_count: u64, + /// Channel identification labels (e.g. "SLFT", "SRGT", "Center"). + pub channel_names: Vec, + /// Optional track title if present in container metadata. + pub title: Option, + /// Optional artist name if present in container metadata. + pub artist: Option, +} + +/// Raw 1-bit DSD audio extracted from a file without decimation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawAudio { + /// Stream metadata from the file header. + pub metadata: Metadata, + /// Bit ordering of the bytes in `channel_bytes`. + pub bit_order: BitOrder, + /// Planar 1-bit audio bytes per channel. + pub channel_bytes: Vec>, +} + +impl RawAudio { + /// Converts all channel byte streams to the requested bit ordering in place. + pub fn convert_bit_order(&mut self, target: BitOrder) { + if self.bit_order == target { + return; + } + for ch in &mut self.channel_bytes { + for b in ch.iter_mut() { + *b = b.reverse_bits(); + } + } + self.bit_order = target; + } + + /// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples. + /// + /// The default decimation factor is 8 (e.g. 352,800 Hz for DSD64). + pub fn to_pcm(&self) -> Result { + self.to_pcm_with_factor(8) + } + + /// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples with the given factor (8, 16, 32, or 64). + pub fn to_pcm_with_factor(&self, factor: u32) -> Result { + // Validate before iterating: public RawAudio may contain no channels. + if !matches!(factor, 8 | 16 | 32 | 64) { + return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64")); + } + if self.channel_bytes.len() > MAX_CHANNELS { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + pcm_budget(self.channel_bytes.iter().map(Vec::len), factor)?; + let mut channels = Vec::with_capacity(self.channel_bytes.len()); + for ch_bytes in &self.channel_bytes { + let pcm = filter::decimate_channel(ch_bytes, self.bit_order, factor)?; + channels.push(pcm); + } + let sample_rate = self.metadata.sample_rate / factor; + Ok(DecodedAudio { metadata: self.metadata.clone(), sample_rate, channels }) + } +} + +/// Decoded multi-bit PCM audio produced by DSD-to-PCM decimation. +#[derive(Debug, Clone, PartialEq)] +pub struct DecodedAudio { + /// Stream metadata from the DSD file header. + pub metadata: Metadata, + /// PCM sample rate in Hz (e.g. 352,800 Hz for DSD64 decimated by 8). + pub sample_rate: u32, + /// Planar normalized PCM samples in `[-1.0, 1.0]`, one `Vec` per channel. + pub channels: Vec>, +} + +impl DecodedAudio { + /// Converts the decoded PCM audio into an [`AudioBuffer`]. + pub fn to_audio_buffer(&self) -> AudioBuffer { + AudioBuffer { sample_rate: self.sample_rate, channels: self.channels.clone() } + } +} + +/// Errors returned when parsing or decoding DSD audio. +#[non_exhaustive] +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum Error { + /// Input data ended prematurely while parsing a header or chunk. + #[error("unexpected end of file: {0}")] + UnexpectedEof(&'static str), + /// Invalid magic bytes or malformed chunk header. + #[error("invalid DSD header or chunk: {0}")] + InvalidHeader(&'static str), + /// An unsupported feature, compression, or channel configuration. + #[error("unsupported DSD feature: {0}")] + Unsupported(&'static str), + /// Audio data length or structure does not match the header specification. + #[error("invalid audio data: {0}")] + InvalidData(&'static str), + /// Header or data requested exceeds maximum safe allocation budget. + #[error("memory budget exceeded")] + MemoryLimitExceeded, +} + +/// Inspects the magic bytes of `bytes` and detects whether it is a DSF or DSDIFF file. +pub fn probe_format(bytes: &[u8]) -> Result { + if bytes.len() < 4 { + return Err(Error::UnexpectedEof("input is too short to determine DSD format")); + } + if &bytes[0..4] == b"DSD " { + Ok(Format::Dsf) + } else if bytes.len() >= 16 && &bytes[0..4] == b"FRM8" && &bytes[12..16] == b"DSD " { + Ok(Format::Dsdiff) + } else { + Err(Error::InvalidHeader("unknown or unsupported DSD container format")) + } +} + +/// Parses the metadata from a DSF or DSDIFF file without decoding audio samples. +pub fn read_metadata(bytes: &[u8]) -> Result { + match probe_format(bytes)? { + Format::Dsf => { + let (meta, _, _) = dsf::parse_dsf_header(bytes)?; + Ok(meta) + } + Format::Dsdiff => { + let (meta, _, _) = dsdiff::parse_dsdiff_header(bytes)?; + Ok(meta) + } + } +} + +/// Reads raw 1-bit planar audio streams from a DSF or DSDIFF file without decimation. +pub fn read_raw(bytes: &[u8]) -> Result { + match probe_format(bytes)? { + Format::Dsf => dsf::parse_dsf(bytes), + Format::Dsdiff => dsdiff::parse_dsdiff(bytes), + } +} + +/// Decodes a DSF or DSDIFF file to multi-bit planar `f32` PCM audio using decimation by 8. +/// +/// For DSD64 (2,822,400 Hz), the output sample rate is 352,800 Hz. +pub fn decode(bytes: &[u8]) -> Result { + decode_with_factor(bytes, 8) +} + +/// Decodes a DSF or DSDIFF file to multi-bit planar `f32` PCM audio with the specified decimation factor. +/// +/// Supported decimation factors are: +/// - 8: 1/8th of DSD rate (e.g. 352,800 Hz for DSD64). +/// - 16: 1/16th of DSD rate (e.g. 176,400 Hz for DSD64). +/// - 32: 1/32th of DSD rate (e.g. 88,200 Hz for DSD64). +/// - 64: 1/64th of DSD rate (e.g. 44,100 Hz for DSD64). +pub fn decode_with_factor(bytes: &[u8], factor: u32) -> Result { + let raw = read_raw(bytes)?; + raw.to_pcm_with_factor(factor) +} + +/// Encodes planar 1-bit audio channels into a Sony DSF file. +pub fn encode_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result, Error> { + dsf::write_dsf(sample_rate, channels, sample_count, block_size) +} + +/// Encodes planar 1-bit audio channels into a Philips DSDIFF file. +pub fn encode_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result, Error> { + dsdiff::write_dsdiff(sample_rate, channels, sample_count) +} + +#[cfg(test)] +mod budget_tests { + use super::*; + + #[test] + fn pcm_budget_counts_all_channels_and_live_scratch() { + let quarter = MAX_DECODE_BYTES / 4; + assert!(pcm_budget([quarter / 2, quarter / 2].into_iter(), 8).is_ok()); + assert_eq!(pcm_budget([quarter / 2, quarter / 2 + 1].into_iter(), 8), Err(Error::MemoryLimitExceeded)); + assert!(pcm_budget([quarter / 2].into_iter(), 16).is_ok()); + assert_eq!(pcm_budget([quarter].into_iter(), 16), Err(Error::MemoryLimitExceeded)); + assert_eq!(pcm_budget([usize::MAX].into_iter(), 8), Err(Error::MemoryLimitExceeded)); + } + + #[test] + fn encoded_budget_includes_headers_without_large_allocations() { + assert_eq!(encoded_size(MAX_ENCODE_BYTES - 92, 92), Ok(MAX_ENCODE_BYTES)); + assert_eq!(encoded_size(MAX_ENCODE_BYTES - 91, 92), Err(Error::MemoryLimitExceeded)); + assert_eq!(encoded_size(usize::MAX, 92), Err(Error::MemoryLimitExceeded)); + } +} diff --git a/crates/audio/src/essence_pcm.rs b/crates/audio/src/essence_pcm.rs new file mode 100644 index 000000000..dfb119b8b --- /dev/null +++ b/crates/audio/src/essence_pcm.rs @@ -0,0 +1,189 @@ +//! Compatibility WAVE and AIFF wrappers for embedded PCM essence in interchange files. +//! PCM inside the model is interleaved little-endian signed integers (8-bit unsigned for WAVE). + +pub use crate::{pcm_aiff_header as aiff_header, pcm_wav_file as wav_file, pcm_wav_header as wav_header}; + +/// PCM, channels, sample rate and bits of a WAVE file (integer PCM only). +pub fn parse_wav(b: &[u8]) -> Option<(Vec, u16, u32, u16)> { + if b.len() < 12 || &b[..4] != b"RIFF" || &b[8..12] != b"WAVE" { + return None; + } + let mut at = 12; + let mut fmt = None; + while at + 8 <= b.len() { + let id = &b[at..at + 4]; + let len = u32::from_le_bytes(b[at + 4..at + 8].try_into().ok()?) as usize; + let body = &b[at + 8..(at + 8).saturating_add(len).min(b.len())]; + if id == b"fmt " && body.len() >= 16 { + let tag = u16::from_le_bytes([body[0], body[1]]); + let ch = u16::from_le_bytes([body[2], body[3]]); + let sr = u32::from_le_bytes(body[4..8].try_into().ok()?); + let bits = u16::from_le_bytes([body[14], body[15]]); + if tag != 1 && tag != 0xFFFE { + return None; + } + if tag == 0xFFFE { + // The first two bytes of the sub-format GUID carry the real format code. + let sub = body.get(24..26)?; + if u16::from_le_bytes([sub[0], sub[1]]) != 1 { + return None; + } + } + fmt = Some((ch, sr, bits)); + } else if id == b"data" { + let (ch, sr, bits) = fmt?; + return Some((body.to_vec(), ch, sr, bits)); + } + at = at.checked_add(8usize.checked_add(len)?.checked_add(len & 1)?)?; + } + None +} + +/// A complete AIFF file (big-endian PCM) from little-endian PCM. +pub fn aiff_file(pcm: &[u8], channels: u16, sample_rate: u32, bits: u16) -> Vec { + let bps = bits.div_ceil(8) as usize; + let frames = pcm.len() / (bps * channels.max(1) as usize).max(1); + let mut v = aiff_header(frames as u32, channels, sample_rate, bits); + for s in pcm.chunks_exact(bps.max(1)) { + if bps == 1 { + v.push(s[0] ^ 0x80); // WAVE 8-bit is unsigned, AIFF signed + } else { + v.extend(s.iter().rev()); + } + } + if (v.len() - 8) & 1 == 1 { + v.push(0); + } + v +} + +/// PCM (converted to little-endian), channels, sample rate and bits of an AIFF / AIFF-C (`NONE` +/// / `twos` / `sowt`) file. +pub fn parse_aiff(b: &[u8]) -> Option<(Vec, u16, u32, u16)> { + if b.len() < 12 || &b[..4] != b"FORM" || !(&b[8..12] == b"AIFF" || &b[8..12] == b"AIFC") { + return None; + } + let aifc = &b[8..12] == b"AIFC"; + let mut at = 12; + let mut comm = None; + while at + 8 <= b.len() { + let id = &b[at..at + 4]; + let len = u32::from_be_bytes(b[at + 4..at + 8].try_into().ok()?) as usize; + let body = &b[at + 8..(at + 8).saturating_add(len).min(b.len())]; + if id == b"COMM" && body.len() >= 18 { + let ch = u16::from_be_bytes([body[0], body[1]]); + let bits = u16::from_be_bytes([body[6], body[7]]); + let sr = from_extended(body[8..18].try_into().ok()?).round() as u32; + // AIFF has no compression code (trailing COMM bytes mean nothing); AIFF-C must name one + // of the integer PCM codes, or the samples are not integer PCM at all + let little = if aifc { + match body.get(18..22)? { + b"NONE" | b"twos" => false, + b"sowt" => true, + _ => return None, + } + } else { + false + }; + comm = Some((ch, sr, bits, little)); + } else if id == b"SSND" && body.len() >= 8 { + let (ch, sr, bits, little) = comm?; + let off = u32::from_be_bytes(body[..4].try_into().ok()?) as usize; + let data = body.get(8usize.checked_add(off)?..)?; + let bps = bits.div_ceil(8) as usize; + let mut pcm = Vec::with_capacity(data.len()); + for s in data.chunks_exact(bps.max(1)) { + if bps == 1 { + pcm.push(s[0] ^ 0x80); + } else if little { + pcm.extend_from_slice(s); + } else { + pcm.extend(s.iter().rev()); + } + } + return Some((pcm, ch, sr, bits)); + } + at = at.checked_add(8usize.checked_add(len)?.checked_add(len & 1)?)?; + } + None +} + +fn from_extended(b: [u8; 10]) -> f64 { + let e = (u16::from_be_bytes([b[0], b[1]]) & 0x7FFF) as i32; + let m = u64::from_be_bytes(b[2..10].try_into().unwrap_or([0; 8])); + if e == 0 && m == 0 { + return 0.0; + } + m as f64 / (1u64 << 63) as f64 * 2f64.powi(e - 16383) +} + +#[cfg(test)] +mod tests { + /// A mutated EDL whose clip ran for days produced an OMF descriptor for more than 4 GiB of + /// PCM: the RIFF size field overflowed ("attempt to add with overflow"). + #[test] + fn huge_wav_header_saturates() { + let h = super::wav_header(u32::MAX, 2, u32::MAX, 24); + assert_eq!(&h[4..8], &u32::MAX.to_le_bytes()); + } + + use super::*; + + #[test] + fn accepts_truncated_essence_summaries() { + let mut wav = wav_file(&[1, 2, 3, 4], 1, 48_000, 16); + wav.truncate(46); + assert_eq!(parse_wav(&wav), Some((vec![1, 2], 1, 48_000, 16))); + let mut aiff = aiff_file(&[1, 2, 3, 4], 1, 48_000, 16); + aiff.truncate(56); + assert_eq!(parse_aiff(&aiff), Some((vec![1, 2], 1, 48_000, 16))); + } + + #[test] + fn wav_and_aiff_round_trip() { + let pcm: Vec = (0..48u8).collect(); // 8 stereo 24-bit frames + let w = wav_file(&pcm, 2, 48_000, 24); + assert_eq!(parse_wav(&w), Some((pcm.clone(), 2, 48_000, 24))); + let a = aiff_file(&pcm, 2, 44_100, 24); + assert_eq!(parse_aiff(&a), Some((pcm.clone(), 2, 44_100, 24))); + let p16: Vec = (0..32u8).collect(); + assert_eq!(parse_aiff(&aiff_file(&p16, 1, 96_000, 16)), Some((p16, 1, 96_000, 16))); + assert!(parse_wav(b"RIFF").is_none()); + assert!(parse_aiff(&a[..30]).is_none()); + for cut in 0..w.len() { + let _ = parse_wav(&w[..cut]); + let _ = parse_aiff(&a[..cut.min(a.len())]); + } + } + + #[test] + fn aifc_needs_an_integer_pcm_compression_code() { + let file = |kind: &[u8; 4], code: &[u8]| { + let mut comm = vec![0, 1, 0, 0, 0, 1, 0, 16]; + comm.extend_from_slice(&[0x40, 0x0E, 0xBB, 0x80, 0, 0, 0, 0, 0, 0]); + comm.extend_from_slice(code); + let mut body = kind.to_vec(); + body.extend_from_slice(b"COMM"); + body.extend_from_slice(&(comm.len() as u32).to_be_bytes()); + body.extend_from_slice(&comm); + if comm.len() & 1 == 1 { + body.push(0); + } + body.extend_from_slice(b"SSND"); + body.extend_from_slice(&10u32.to_be_bytes()); + body.extend_from_slice(&[0; 8]); + body.extend_from_slice(&[0x12, 0x34]); + let mut v = b"FORM".to_vec(); + v.extend_from_slice(&(body.len() as u32).to_be_bytes()); + v.extend_from_slice(&body); + v + }; + assert_eq!(parse_aiff(&file(b"AIFC", b"NONE")).map(|p| p.0), Some(vec![0x34, 0x12])); + assert_eq!(parse_aiff(&file(b"AIFC", b"twos")).map(|p| p.0), Some(vec![0x34, 0x12])); + assert_eq!(parse_aiff(&file(b"AIFC", b"sowt")).map(|p| p.0), Some(vec![0x12, 0x34])); + assert!(parse_aiff(&file(b"AIFC", b"fl32")).is_none(), "float samples are not integer PCM"); + assert!(parse_aiff(&file(b"AIFC", b"")).is_none(), "AIFF-C without a compression code"); + // plain AIFF ignores trailing COMM bytes + assert_eq!(parse_aiff(&file(b"AIFF", b"sowt")).map(|p| p.0), Some(vec![0x34, 0x12])); + } +} diff --git a/crates/audio/src/flac_decode.rs b/crates/audio/src/flac_decode.rs new file mode 100644 index 000000000..bb56e65c5 --- /dev/null +++ b/crates/audio/src/flac_decode.rs @@ -0,0 +1,603 @@ +//! A native FLAC decoder (RFC 9639): [`decode`] for whole `.flac` files and [`Decoder`] for single +//! frames (the packets of FLAC in MP4, Matroska or Ogg). +//! +//! Every frame is checked against its CRC-8 and CRC-16. Subframe types constant, verbatim, fixed +//! and LPC; Rice partitions with 4- and 5-bit parameters and escaped partitions; wasted bits; +//! left/side, side/right and mid/side stereo; fixed and variable block sizes; 4 to 32 bits per +//! sample. The STREAMINFO MD5 is not verified. +//! +//! Samples come back as `i32`, one `Vec` per channel, in the FLAC channel order. + +/// What went wrong decoding FLAC. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum DecodeError { + /// The data ends early. + #[error("truncated FLAC data")] + Truncated, + /// The data is not valid FLAC. + #[error("invalid FLAC data: {0}")] + Invalid(&'static str), + /// A frame or header failed its CRC. + #[error("FLAC CRC mismatch in {0}")] + Crc(&'static str), + /// Valid FLAC that is not decoded. + #[error("unsupported FLAC feature: {0}")] + Unsupported(&'static str), + /// The stream is longer than the sample limit. + #[error("FLAC stream exceeds the sample limit")] + TooLarge, +} + +/// `Result` of this module. +pub type Result = std::result::Result; + +/// The STREAMINFO metadata block (RFC 9639 section 8.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StreamInfo { + /// Smallest block size in samples. + pub min_block_size: u16, + /// Largest block size in samples. + pub max_block_size: u16, + /// Smallest frame in bytes, 0 if unknown. + pub min_frame_size: u32, + /// Largest frame in bytes, 0 if unknown. + pub max_frame_size: u32, + /// Sample rate in Hz. + pub sample_rate: u32, + /// Channel count, 1 to 8. + pub channels: u8, + /// Bits per sample, 4 to 32. + pub bits_per_sample: u8, + /// Samples per channel in the stream, 0 if unknown. + pub total_samples: u64, + /// MD5 of the unencoded audio, all zero if not set. + pub md5: [u8; 16], +} + +impl StreamInfo { + /// Parse the 34 bytes of a STREAMINFO block body. + pub fn parse(b: &[u8]) -> Result { + let b = b.get(..34).ok_or(DecodeError::Truncated)?; + let packed = u64::from_be_bytes([b[10], b[11], b[12], b[13], b[14], b[15], b[16], b[17]]); + let info = StreamInfo { + min_block_size: u16::from_be_bytes([b[0], b[1]]), + max_block_size: u16::from_be_bytes([b[2], b[3]]), + min_frame_size: u32::from_be_bytes([0, b[4], b[5], b[6]]), + max_frame_size: u32::from_be_bytes([0, b[7], b[8], b[9]]), + sample_rate: (packed >> 44) as u32, + channels: ((packed >> 41) & 7) as u8 + 1, + bits_per_sample: ((packed >> 36) & 31) as u8 + 1, + total_samples: packed & 0xF_FFFF_FFFF, + md5: b[18..34].try_into().map_err(|_| DecodeError::Truncated)?, + }; + if info.bits_per_sample < 4 { + return Err(DecodeError::Invalid("bits per sample below 4")); + } + if info.min_block_size != 0 + && (info.min_block_size < 16 && info.min_block_size != info.max_block_size || info.max_block_size < info.min_block_size) + { + return Err(DecodeError::Invalid("inconsistent block sizes")); + } + Ok(info) + } +} + +/// One decoded frame. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Frame { + /// Sample rate in Hz. + pub sample_rate: u32, + /// Bits per sample. + pub bits_per_sample: u8, + /// `true` when `number` is the first sample's index (variable block size), `false` when it is + /// the frame's index (fixed block size). + pub variable_block_size: bool, + /// The coded number of the frame header. + pub number: u64, + /// Samples per channel in the frame. + pub block_size: usize, + /// One `Vec` per channel, after undoing any stereo decorrelation. + pub channels: Vec>, + /// Bytes the frame took, including the header and CRC footer. + pub size: usize, +} + +// ---- checksums ---- + +fn crc8(data: &[u8]) -> u8 { + let mut crc = 0u8; + for &b in data { + crc ^= b; + for _ in 0..8 { + crc = if crc & 0x80 != 0 { crc << 1 ^ 0x07 } else { crc << 1 }; + } + } + crc +} + +fn crc16(data: &[u8]) -> u16 { + let mut crc = 0u16; + for &b in data { + crc ^= u16::from(b) << 8; + for _ in 0..8 { + crc = if crc & 0x8000 != 0 { crc << 1 ^ 0x8005 } else { crc << 1 }; + } + } + crc +} + +// ---- bits ---- + +struct Bits<'a> { + data: &'a [u8], + /// Position in bits. + pos: usize, +} + +impl<'a> Bits<'a> { + fn new(data: &'a [u8]) -> Self { + Bits { data, pos: 0 } + } + + fn left(&self) -> usize { + self.data.len() * 8 - self.pos + } + + fn bit(&mut self) -> Result { + let byte = *self.data.get(self.pos / 8).ok_or(DecodeError::Truncated)?; + let v = (byte >> (7 - self.pos % 8)) & 1; + self.pos += 1; + Ok(u32::from(v)) + } + + /// `n` bits (0 to 32) as an unsigned number. + fn bits(&mut self, n: u32) -> Result { + if n as usize > self.left() { + return Err(DecodeError::Truncated); + } + let mut v = 0u64; + let mut n = n as usize; + while n > 0 { + let byte = u64::from(self.data[self.pos / 8]); + let avail = 8 - self.pos % 8; + let take = avail.min(n); + v = v << take | (byte >> (avail - take)) & ((1 << take) - 1); + self.pos += take; + n -= take; + } + Ok(v) + } + + /// `n` bits (0 to 33) as a two's complement number. + fn signed(&mut self, n: u32) -> Result { + if n == 0 { + return Ok(0); + } + let v = self.bits(n)? as i64; + Ok(if v >> (n - 1) & 1 == 1 { v - (1 << n) } else { v }) + } + + /// Zero bits up to the next one bit (which is consumed). + fn unary(&mut self) -> Result { + let mut n = 0u64; + loop { + // Skip whole zero bytes when aligned. + if self.pos.is_multiple_of(8) { + while self.data.get(self.pos / 8) == Some(&0) { + self.pos += 8; + n += 8; + } + } + if self.bit()? == 1 { + return Ok(n); + } + n += 1; + } + } + + fn align(&mut self) { + self.pos = self.pos.div_ceil(8) * 8; + } +} + +// ---- frame ---- + +const BLOCK_SIZES: [usize; 16] = [0, 192, 576, 1152, 2304, 4608, 0, 0, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768]; + +/// A frame decoder. `info` supplies what a frame header leaves to the STREAMINFO. +#[derive(Debug, Clone, Copy, Default)] +pub struct Decoder { + info: Option, +} + +impl Decoder { + /// A decoder with the stream's STREAMINFO (needed for frames whose header defers the sample + /// rate or bit depth to it). + pub fn new(info: StreamInfo) -> Decoder { + Decoder { info: Some(info) } + } + + /// A decoder without STREAMINFO: frames that defer to it are an error. + pub fn without_streaminfo() -> Decoder { + Decoder { info: None } + } + + /// Decode the frame at the start of `data`. + pub fn decode_frame(&self, data: &[u8]) -> Result { + // StreamInfo has public fields: container callers can construct it without + // parse(), so validate before it can control shifts and sample reads. + if self.info.is_some_and(|i| !(4..=32).contains(&i.bits_per_sample) || !(1..=8).contains(&i.channels) || i.sample_rate == 0) { + return Err(DecodeError::Invalid("invalid decoder STREAMINFO")); + } + let mut r = Bits::new(data); + if r.bits(15)? != 0x7FFC { + return Err(DecodeError::Invalid("missing frame sync code")); + } + let variable = r.bit()? == 1; + let (bs_code, sr_code) = (r.bits(4)? as usize, r.bits(4)? as usize); + let (ch_code, bps_code) = (r.bits(4)? as usize, r.bits(3)? as usize); + if r.bit()? != 0 { + return Err(DecodeError::Invalid("reserved bit set")); + } + let number = coded_number(&mut r)?; + let block_size = match bs_code { + 0 => return Err(DecodeError::Invalid("reserved block size")), + 6 => r.bits(8)? as usize + 1, + 7 => r.bits(16)? as usize + 1, + c => BLOCK_SIZES[c], + }; + let sample_rate = match sr_code { + 0 => self.info.map(|i| i.sample_rate).ok_or(DecodeError::Invalid("sample rate only in STREAMINFO"))?, + 1 => 88_200, + 2 => 176_400, + 3 => 192_000, + 4 => 8_000, + 5 => 16_000, + 6 => 22_050, + 7 => 24_000, + 8 => 32_000, + 9 => 44_100, + 10 => 48_000, + 11 => 96_000, + 12 => r.bits(8)? as u32 * 1000, + 13 => r.bits(16)? as u32, + 14 => r.bits(16)? as u32 * 10, + _ => return Err(DecodeError::Invalid("forbidden sample rate code")), + }; + let header_len = r.pos.div_ceil(8); + let stored_crc = r.bits(8)? as u8; + if crc8(&data[..header_len]) != stored_crc { + return Err(DecodeError::Crc("a frame header")); + } + let bits = match bps_code { + 0 => self.info.map(|i| u32::from(i.bits_per_sample)).ok_or(DecodeError::Invalid("bit depth only in STREAMINFO"))?, + 1 => 8, + 2 => 12, + 4 => 16, + 5 => 20, + 6 => 24, + 7 => 32, + _ => return Err(DecodeError::Invalid("reserved bit depth")), + }; + let (channels, mode) = match ch_code { + 0..=7 => (ch_code + 1, Stereo::Independent), + 8 => (2, Stereo::LeftSide), + 9 => (2, Stereo::SideRight), + 10 => (2, Stereo::MidSide), + _ => return Err(DecodeError::Invalid("reserved channel assignment")), + }; + let mut out: Vec> = Vec::with_capacity(channels); + for c in 0..channels { + let extra = match (mode, c) { + (Stereo::LeftSide, 1) | (Stereo::SideRight, 0) | (Stereo::MidSide, 1) => 1, + _ => 0, + }; + out.push(subframe(&mut r, block_size, bits + extra)?); + } + r.align(); + let size = r.pos / 8; + let crc = r.bits(16)? as u16; + if crc16(&data[..size]) != crc { + return Err(DecodeError::Crc("a frame")); + } + let size = size + 2; + if mode != Stereo::Independent { + let (first, rest) = out.split_at_mut(1); + let (a, b) = (&mut first[0], &mut rest[0]); + for (x, y) in a.iter_mut().zip(b.iter_mut()) { + match mode { + Stereo::LeftSide => *y = x.wrapping_sub(*y), + Stereo::SideRight => *x = x.wrapping_add(*y), + _ => { + let m = x.wrapping_shl(1) | (*y & 1); + let side = *y; + *x = m.wrapping_add(side) >> 1; + *y = m.wrapping_sub(side) >> 1; + } + } + } + } + let mut chans = Vec::with_capacity(channels); + for c in out { + let v: Result> = c.into_iter().map(|s| checked_sample(s, bits)).collect(); + chans.push(v?); + } + Ok(Frame { sample_rate, bits_per_sample: bits as u8, variable_block_size: variable, number, block_size, channels: chans, size }) + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Stereo { + Independent, + LeftSide, + SideRight, + MidSide, +} + +/// The UTF-8-like coded number of a frame header (up to 36 bits, 7 bytes). +fn coded_number(r: &mut Bits) -> Result { + let first = r.bits(8)? as u8; + let extra = match first { + 0x00..=0x7F => return Ok(u64::from(first)), + 0xC0..=0xDF => 1, + 0xE0..=0xEF => 2, + 0xF0..=0xF7 => 3, + 0xF8..=0xFB => 4, + 0xFC..=0xFD => 5, + 0xFE => 6, + _ => return Err(DecodeError::Invalid("bad coded number")), + }; + let mut v = if extra == 6 { 0 } else { u64::from(first & (0x3F >> extra)) }; + for _ in 0..extra { + let b = r.bits(8)?; + if b & 0xC0 != 0x80 { + return Err(DecodeError::Invalid("bad coded number")); + } + v = v << 6 | (b & 0x3F); + } + Ok(v) +} + +/// One subframe: `bits` is the frame bit depth (plus 1 for a side channel). +fn subframe(r: &mut Bits, n: usize, bits: u32) -> Result> { + if r.bit()? != 0 { + return Err(DecodeError::Invalid("subframe header padding bit set")); + } + let kind = r.bits(6)? as u32; + let wasted = if r.bit()? == 1 { r.unary()? as u32 + 1 } else { 0 }; + if wasted >= bits { + return Err(DecodeError::Invalid("wasted bits leave no sample bits")); + } + let bps = bits - wasted; + let mut s = vec![0i64; n]; + match kind { + 0 => { + let v = r.signed(bps)?; + s.fill(v); + } + 1 => { + for v in s.iter_mut() { + *v = r.signed(bps)?; + } + } + 8..=12 => { + let order = (kind - 8) as usize; + warmup(r, &mut s, order, bps)?; + residual(r, &mut s, order)?; + for i in order..n { + let at = |k: usize| s[i - k]; + // Wrapping: hostile residuals can overflow; such samples fail the range check later. + let p = match order { + 0 => 0, + 1 => at(1), + 2 => at(1).wrapping_mul(2).wrapping_sub(at(2)), + 3 => at(1).wrapping_mul(3).wrapping_sub(at(2).wrapping_mul(3)).wrapping_add(at(3)), + _ => at(1).wrapping_mul(4).wrapping_sub(at(2).wrapping_mul(6)).wrapping_add(at(3).wrapping_mul(4)).wrapping_sub(at(4)), + }; + s[i] = s[i].wrapping_add(p); + } + } + 32..=63 => { + let order = (kind - 31) as usize; + warmup(r, &mut s, order, bps)?; + let precision = r.bits(4)? as u32 + 1; + if precision == 16 { + return Err(DecodeError::Invalid("forbidden coefficient precision")); + } + let shift = r.signed(5)?; + if shift < 0 { + return Err(DecodeError::Invalid("negative prediction shift")); + } + let mut coefs = [0i64; 32]; + for c in coefs.iter_mut().take(order) { + *c = r.signed(precision)?; + } + residual(r, &mut s, order)?; + for i in order..n { + let mut sum = 0i64; + for (k, &c) in coefs.iter().take(order).enumerate() { + sum = sum.wrapping_add(c.wrapping_mul(s[i - 1 - k])); + } + s[i] = s[i].wrapping_add(sum >> shift); + } + } + _ => return Err(DecodeError::Invalid("reserved subframe type")), + } + if wasted > 0 { + for v in s.iter_mut() { + *v = v.wrapping_shl(wasted); + } + } + Ok(s) +} + +fn warmup(r: &mut Bits, s: &mut [i64], order: usize, bps: u32) -> Result<()> { + if order > s.len() { + return Err(DecodeError::Invalid("predictor order above the block size")); + } + for v in s.iter_mut().take(order) { + *v = r.signed(bps)?; + } + Ok(()) +} + +/// The coded residual (RFC 9639 section 9.2.7), into `s[order..]`. +fn residual(r: &mut Bits, s: &mut [i64], order: usize) -> Result<()> { + let method = r.bits(2)?; + let (param_bits, escape) = match method { + 0 => (4, 15), + 1 => (5, 31), + _ => return Err(DecodeError::Invalid("reserved residual coding method")), + }; + let part_order = r.bits(4)? as u32; + let n = s.len(); + let parts = 1usize << part_order; + if !n.is_multiple_of(parts) { + return Err(DecodeError::Invalid("partition order does not divide the block size")); + } + let per = n >> part_order; + if per < order { + return Err(DecodeError::Invalid("partition shorter than the predictor order")); + } + let mut i = order; + for p in 0..parts { + let count = if p == 0 { per - order } else { per }; + let k = r.bits(param_bits)? as u32; + if k == escape { + let width = r.bits(5)? as u32; + for v in s[i..i + count].iter_mut() { + *v = r.signed(width)?; + } + } else { + for v in s[i..i + count].iter_mut() { + let q = r.unary()?; + if q > (1 << 32) { + return Err(DecodeError::Invalid("Rice quotient too large")); + } + let low = r.bits(k)?; + let folded = q << k | low; + *v = if folded & 1 == 0 { (folded >> 1) as i64 } else { -((folded >> 1) as i64) - 1 }; + } + } + i += count; + } + Ok(()) +} + +// ---- files ---- + +/// A decoded file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Decoded { + /// The STREAMINFO block. + pub info: StreamInfo, + /// One `Vec` of samples per channel. + pub channels: Vec>, +} + +/// Most sample values (samples x channels) [`decode`] will produce. +pub const DEFAULT_MAX_VALUES: u64 = 1 << 28; + +/// Decode a whole `.flac` file (an ID3v2 tag in front is skipped). +pub fn decode(bytes: &[u8]) -> Result { + decode_with_limit(bytes, DEFAULT_MAX_VALUES) +} + +/// [`decode`] with a limit on the sample values (samples x channels) produced. +pub fn decode_with_limit(bytes: &[u8], max_values: u64) -> Result { + let mut pos = 0usize; + if bytes.starts_with(b"ID3") { + let size = bytes.get(6..10).ok_or(DecodeError::Truncated)?; + if size.iter().any(|&b| b & 0x80 != 0) { + return Err(DecodeError::Invalid("bad ID3v2 size")); + } + pos = 10 + size.iter().fold(0usize, |a, &b| a << 7 | usize::from(b)); + } + if bytes.get(pos..pos + 4) != Some(b"fLaC") { + return Err(DecodeError::Invalid("missing fLaC marker")); + } + pos += 4; + let mut info: Option = None; + loop { + let head = bytes.get(pos..pos + 4).ok_or(DecodeError::Truncated)?; + let last = head[0] & 0x80 != 0; + let kind = head[0] & 0x7F; + let len = usize::from(head[1]) << 16 | usize::from(head[2]) << 8 | usize::from(head[3]); + let body = bytes.get(pos + 4..pos + 4 + len).ok_or(DecodeError::Truncated)?; + match (kind, &info) { + (0, None) => info = Some(StreamInfo::parse(body)?), + (0, Some(_)) => return Err(DecodeError::Invalid("a second STREAMINFO block")), + (_, None) => return Err(DecodeError::Invalid("STREAMINFO is not the first block")), + (127, _) => return Err(DecodeError::Invalid("forbidden metadata block type")), + _ => {} + } + pos += 4 + len; + if last { + break; + } + } + let info = info.ok_or(DecodeError::Invalid("no STREAMINFO"))?; + let dec = Decoder::new(info); + let mut channels: Vec> = vec![Vec::new(); usize::from(info.channels)]; + let mut total = 0u64; + while pos + 2 <= bytes.len() && bytes[pos] == 0xFF && bytes[pos + 1] & 0xFE == 0xF8 { + let frame = dec.decode_frame(&bytes[pos..])?; + if frame.channels.len() != channels.len() { + return Err(DecodeError::Invalid("the channel count changes inside the stream")); + } + // One file has one sample rate and depth. Otherwise callers would play + // samples under incompatible STREAMINFO metadata. + if frame.sample_rate != info.sample_rate || frame.bits_per_sample != info.bits_per_sample { + return Err(DecodeError::Invalid("frame format differs from STREAMINFO")); + } + total += frame.block_size as u64; + if total.saturating_mul(channels.len() as u64) > max_values { + return Err(DecodeError::TooLarge); + } + for (dst, src) in channels.iter_mut().zip(frame.channels) { + dst.extend_from_slice(&src); + } + pos += frame.size; + } + // Unknown total_samples must not turn a corrupt/truncated next frame into + // a successfully decoded shorter recording. + if pos != bytes.len() { + return Err(DecodeError::Invalid("trailing data or missing frame sync")); + } + if info.total_samples != 0 && total != info.total_samples { + return Err(DecodeError::Truncated); + } + Ok(Decoded { info, channels }) +} + +// Validate the advertised precision, not just the storage type. Malformed +// predictors may produce an i32 that is still invalid for 4–24-bit audio. +fn checked_sample(sample: i64, bits: u32) -> Result { + if !(4..=32).contains(&bits) { + return Err(DecodeError::Invalid("invalid sample bit depth")); + } + let bound = 1i64 << (bits - 1); + if !(-bound..bound).contains(&sample) { + return Err(DecodeError::Invalid("sample outside the bit depth")); + } + i32::try_from(sample).map_err(|_| DecodeError::Invalid("sample outside the bit depth")) +} + +#[cfg(test)] +mod sample_bounds_tests { + use super::checked_sample; + + #[test] + fn samples_must_fit_declared_precision() { + for bits in 4..=32 { + let bound = 1i64 << (bits - 1); + assert_eq!(checked_sample(-bound, bits).map(i64::from), Ok(-bound)); + assert_eq!(checked_sample(bound - 1, bits).map(i64::from), Ok(bound - 1)); + assert!(checked_sample(-bound - 1, bits).is_err()); + assert!(checked_sample(bound, bits).is_err()); + } + assert!(checked_sample(0, 0).is_err()); + assert!(checked_sample(0, 255).is_err()); + } +} diff --git a/crates/audio/src/g722.rs b/crates/audio/src/g722.rs new file mode 100644 index 000000000..030b87d14 --- /dev/null +++ b/crates/audio/src/g722.rs @@ -0,0 +1,693 @@ +//! ITU-T Recommendation G.722 wideband audio coding (64 kbit/s). +//! +//! Pure safe Rust clean-room implementation of the G.722 sub-band adaptive differential +//! pulse code modulation (SB-ADPCM) speech and audio codec. +//! +//! Input audio is 16 kHz 16-bit linear PCM. An analysis Quadrature Mirror Filter (QMF) splits +//! the 16 kHz audio into a lower sub-band (0–4 kHz) and a higher sub-band (4–8 kHz), each +//! sampled at 8 kHz. The lower sub-band is encoded at 48 kbit/s (6 bits/sample) and the higher +//! sub-band at 16 kbit/s (2 bits/sample), multiplexed into an 8-bit octet per 8 kHz cycle +//! (64 kbit/s total stream rate). +//! +//! On decoding, inverse adaptive quantizers reconstruct each sub-band signal, and a synthesis +//! QMF interpolates and combines them back to 16 kHz 16-bit linear PCM. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +/// Maximum allowed channels for multi-channel processing. +pub const MAX_CHANNELS: usize = 8; + +/// Maximum input byte buffer bound to prevent memory exhaustion on hostile inputs (64 MiB). +pub const MAX_INPUT_BYTES: usize = 64 * 1024 * 1024; + +/// Maximum input sample count bound (128 million samples). +pub const MAX_SAMPLES: usize = 128 * 1024 * 1024; + +/// Error conditions encountered during G.722 encoding or decoding. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum Error { + /// The channel count is invalid. + #[error("invalid channel count: {0} (must be 1..={MAX_CHANNELS})")] + InvalidChannels(usize), + + /// The input size exceeds safety bounds. + #[error("input exceeds maximum size bound")] + InputTooLarge, + + /// Encoding requires an even number of samples per channel (16 kHz sample pairs). + #[error("odd number of samples: {0} (G.722 encodes pairs of 16 kHz samples)")] + OddSampleCount(usize), + + /// System allocation failed when reserving buffer memory. + #[error("allocation failed")] + AllocationFailed, +} + +// --------------------------------------------------------------------------- +// Specification Tables from ITU-T Recommendation G.722 +// --------------------------------------------------------------------------- + +/// 24-tap QMF filter coefficients scaled by 2^13 (Table 11/G.722). +const H: [i16; 24] = [3, -11, -11, 53, 12, -156, 32, 362, -210, -805, 951, 3876, 3876, 951, -805, -210, 362, 32, -156, 12, 53, -11, -11, 3]; + +/// Lower sub-band 60-level inverse quantizer reconstruction table QQ6 (Table 14/G.722). +const QQ6: [i16; 31] = [ + 0, 17, 54, 91, 130, 170, 211, 254, 300, 347, 396, 447, 501, 558, 618, 682, 750, 822, 899, 982, 1072, 1170, 1279, 1399, 1535, 1689, 1873, 2088, + 2376, 2738, 3101, +]; + +/// Lower sub-band quantizer decision levels Q6 (Table 14/G.722). +const Q6: [i16; 30] = [ + 0, 35, 72, 110, 150, 190, 233, 276, 323, 370, 422, 473, 530, 587, 650, 714, 786, 858, 940, 1023, 1121, 1219, 1339, 1458, 1612, 1765, 1980, 2195, + 2557, 2919, +]; + +/// Lower sub-band 15-level inverse quantizer reconstruction table QQ4 (Table 14/G.722). +const QQ4: [i16; 8] = [0, 150, 323, 530, 786, 1121, 1612, 2557]; + +/// Lower sub-band logarithmic scale factor multipliers WL (Table 14/G.722). +const WL: [i16; 8] = [-60, -30, 58, 172, 334, 538, 1198, 3042]; + +/// Higher sub-band 4-level inverse quantizer reconstruction table QQ2 (Table 14/G.722). +const QQ2: [i16; 3] = [0, 202, 926]; + +/// Higher sub-band logarithmic scale factor multipliers WH (Table 14/G.722). +const WH: [i16; 3] = [0, -214, 798]; + +/// 32-entry inverse logarithmic scale table ILB (Table 15/G.722). +const ILB: [i32; 32] = [ + 2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383, 2435, 2489, 2543, 2599, 2656, 2714, 2774, 2834, 2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371, + 3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008, +]; + +/// Table 17/G.722: 4-bit codeword (RIL = IL >> 2) to (SIL, IL4). +const IL4_MAP: [(i16, usize); 16] = + [(0, 0), (-1, 7), (-1, 6), (-1, 5), (-1, 4), (-1, 3), (-1, 2), (-1, 1), (0, 7), (0, 6), (0, 5), (0, 4), (0, 3), (0, 2), (0, 1), (0, 0)]; + +/// Table 21/G.722: 2-bit codeword IH to (SIH, IH2). +const IH2_MAP: [(i16, usize); 4] = [(-1, 2), (-1, 1), (0, 2), (0, 1)]; + +#[inline] +fn mult(a: i16, b: i16) -> i16 { + (((a as i32) * (b as i32)) >> 15) as i16 +} + +#[inline] +fn scalel(nbpl: i32) -> i32 { + let wd1 = ((nbpl >> 6) & 31) as usize; + let wd2 = nbpl >> 11; + let shift = 8 - wd2; + let wd3 = if shift >= 0 { ILB[wd1] >> shift } else { ILB[wd1] << (-shift) }; + wd3 << 2 +} + +#[inline] +fn scaleh(nbph: i32) -> i32 { + let wd1 = ((nbph >> 6) & 31) as usize; + let wd2 = nbph >> 11; + let shift = 10 - wd2; + let wd3 = if shift >= 0 { ILB[wd1] >> shift } else { ILB[wd1] << (-shift) }; + wd3 << 2 +} + +// --------------------------------------------------------------------------- +// Sub-band ADPCM State (Pole/Zero Predictors & Adaptations) +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +struct BandState { + s: i16, + sp: i16, + sz: i16, + d: [i16; 7], + r: [i16; 3], + p: [i16; 3], + a: [i16; 3], + b: [i16; 7], + nb: i32, + det: i32, +} + +impl BandState { + fn new(is_lower: bool) -> Self { + Self { s: 0, sp: 0, sz: 0, d: [0; 7], r: [0; 3], p: [0; 3], a: [0; 3], b: [0; 7], nb: 0, det: if is_lower { 32 } else { 8 } } + } + + fn reset(&mut self, is_lower: bool) { + self.s = 0; + self.sp = 0; + self.sz = 0; + self.d = [0; 7]; + self.r = [0; 3]; + self.p = [0; 3]; + self.a = [0; 3]; + self.b = [0; 7]; + self.nb = 0; + self.det = if is_lower { 32 } else { 8 }; + } + + fn update_predictor(&mut self, d: i16, p_sig: i16, r_sig: i16) { + // UPZERO: update 6th order zero predictor coefficients + let wd1: i16 = if d != 0 { 128 } else { 0 }; + let sg0: i16 = if d < 0 { -1 } else { 0 }; + for i in 1..=6 { + let sgi = if self.d[i] < 0 { -1 } else { 0 }; + let wd2 = if sg0 == sgi { wd1 } else { wd1.saturating_neg() }; + let wd3 = mult(self.b[i], 32640); + self.b[i] = wd2.saturating_add(wd3); + } + + // UPPOL2: update 2nd pole coefficient + let sg0 = if p_sig < 0 { -1 } else { 0 }; + let sg1 = if self.p[1] < 0 { -1 } else { 0 }; + let sg2 = if self.p[2] < 0 { -1 } else { 0 }; + let wd1 = self.a[1].saturating_add(self.a[1]).saturating_add(self.a[1].saturating_add(self.a[1])); + let wd2 = if sg0 == sg1 { wd1.saturating_neg() } else { wd1 } >> 7; + let wd3: i16 = if sg0 == sg2 { 128 } else { -128 }; + let wd4 = wd2.saturating_add(wd3); + let wd5 = mult(self.a[2], 32512); + let apl2 = wd4.saturating_add(wd5).clamp(-12288, 12288); + + // UPPOL1: update 1st pole coefficient + let wd1: i16 = if sg0 == sg1 { 192 } else { -192 }; + let wd2 = mult(self.a[1], 32640); + let apl1 = wd1.saturating_add(wd2); + let wd3 = 15360 - apl2; + let apl1 = apl1.clamp(-wd3, wd3); + + self.a[1] = apl1; + self.a[2] = apl2; + + // Shift history delay lines + for i in (2..=6).rev() { + self.d[i] = self.d[i - 1]; + } + self.d[1] = d; + + self.p[2] = self.p[1]; + self.p[1] = p_sig; + + self.r[2] = self.r[1]; + self.r[1] = r_sig; + + // FILTEZ: compute zero section output + let mut sz: i16 = 0; + for i in (1..=6).rev() { + let part = mult(self.b[i], self.d[i].saturating_add(self.d[i])); + sz = sz.saturating_add(part); + } + self.sz = sz; + + // FILTEP: compute pole section output + let sp1 = mult(self.a[1], self.r[1].saturating_add(self.r[1])); + let sp2 = mult(self.a[2], self.r[2].saturating_add(self.r[2])); + self.sp = sp1.saturating_add(sp2); + + // PREDIC: compute full predictor output value + self.s = self.sp.saturating_add(self.sz); + } +} + +// --------------------------------------------------------------------------- +// Quadrature Mirror Filters (QMF) +// --------------------------------------------------------------------------- + +/// Analysis QMF (transmit filter bank): splits pairs of 16 kHz samples into lower and higher sub-bands. +#[derive(Debug, Clone, Default)] +pub struct QmfTx { + x: [i16; 24], +} + +impl QmfTx { + /// Create a new analysis QMF filter. + pub fn new() -> Self { + Self { x: [0; 24] } + } + + /// Reset filter history. + pub fn reset(&mut self) { + self.x = [0; 24]; + } + + /// Process a pair of 16 kHz input samples `(s0, s1)` into `(xl, xh)`. + pub fn filter(&mut self, s0: i16, s1: i16) -> (i16, i16) { + for i in (2..24).rev() { + self.x[i] = self.x[i - 2]; + } + self.x[0] = s1 >> 1; + self.x[1] = s0 >> 1; + + let mut xa: i32 = 0; + let mut xb: i32 = 0; + for i in 0..12 { + xa = xa.saturating_add((self.x[2 * i] as i32) * (H[2 * i] as i32)); + xb = xb.saturating_add((self.x[2 * i + 1] as i32) * (H[2 * i + 1] as i32)); + } + + let xl = ((xa.saturating_add(xb)) >> 13).clamp(-16384, 16383) as i16; + let xh = ((xa.saturating_sub(xb)) >> 13).clamp(-16384, 16383) as i16; + (xl, xh) + } +} + +/// Synthesis QMF (receive filter bank): synthesizes lower and higher sub-band signals into 16 kHz output. +#[derive(Debug, Clone, Default)] +pub struct QmfRx { + xd: [i16; 12], + xs: [i16; 12], +} + +impl QmfRx { + /// Create a new synthesis QMF filter. + pub fn new() -> Self { + Self { xd: [0; 12], xs: [0; 12] } + } + + /// Reset filter history. + pub fn reset(&mut self) { + self.xd = [0; 12]; + self.xs = [0; 12]; + } + + /// Reconstruct a pair of 16 kHz output samples from sub-band samples `(rl, rh)`. + pub fn filter(&mut self, rl: i16, rh: i16) -> (i16, i16) { + let xd_curr = rl.saturating_sub(rh); + let xs_curr = rl.saturating_add(rh); + + for i in (1..12).rev() { + self.xd[i] = self.xd[i - 1]; + self.xs[i] = self.xs[i - 1]; + } + self.xd[0] = xd_curr; + self.xs[0] = xs_curr; + + let mut wd_c: i32 = 0; + let mut wd_d: i32 = 0; + for i in 0..12 { + wd_c = wd_c.saturating_add((self.xd[i] as i32) * (H[2 * i] as i32)); + wd_d = wd_d.saturating_add((self.xs[i] as i32) * (H[2 * i + 1] as i32)); + } + + let xout1 = (wd_c >> 12).clamp(-16384, 16383); + let xout2 = (wd_d >> 12).clamp(-16384, 16383); + + let s0 = (xout1 << 1).clamp(-32768, 32767) as i16; + let s1 = (xout2 << 1).clamp(-32768, 32767) as i16; + (s0, s1) + } +} + +// --------------------------------------------------------------------------- +// G.722 Decoder & Encoder +// --------------------------------------------------------------------------- + +/// ITU-T G.722 64 kbit/s single-channel decoder. +#[derive(Debug, Clone)] +pub struct Decoder { + band_l: BandState, + band_h: BandState, + qmf: QmfRx, +} + +impl Default for Decoder { + fn default() -> Self { + Self::new() + } +} + +impl Decoder { + /// Create a new G.722 decoder initialized to standard reset state. + pub fn new() -> Self { + Self { band_l: BandState::new(true), band_h: BandState::new(false), qmf: QmfRx::new() } + } + + /// Reset decoder internal state. + pub fn reset(&mut self) { + self.band_l.reset(true); + self.band_h.reset(false); + self.qmf.reset(); + } + + /// Decode a single 8-bit octet into two 16 kHz 16-bit PCM samples. + pub fn decode_octet(&mut self, octet: u8) -> (i16, i16) { + let ih = ((octet >> 6) & 3) as usize; + let il = (octet & 0x3F) as usize; + + // INVQBL: 6-bit lower sub-band inverse quantization + let (sil6, il6) = table18_lookup(il); + let wd1 = (QQ6[il6] as i32) << 3; + let wd2 = if sil6 == 0 { wd1 } else { -wd1 }; + let dl = mult(self.band_l.det as i16, wd2 as i16); + let yl = self.band_l.s.saturating_add(dl); + let rl = yl.clamp(-16384, 16383); + + // INVQAL: lower sub-band predictor update (4-bit feedback path) + let ril = il >> 2; + let (sil4, il4) = IL4_MAP[ril & 0x0F]; + let wd1 = (QQ4[il4] as i32) << 3; + let wd2 = if sil4 == 0 { wd1 } else { -wd1 }; + let dlt = mult(self.band_l.det as i16, wd2 as i16); + let plt = dlt.saturating_add(self.band_l.sz); + let rlt = self.band_l.s.saturating_add(dlt); + + // Lower sub-band scale factor adaptation (LOGSCL) + let wd_scale = mult(self.band_l.nb as i16, 32512); + let nbpl = (wd_scale as i32 + WL[il4] as i32).clamp(0, 18432); + self.band_l.nb = nbpl; + self.band_l.det = scalel(nbpl); + self.band_l.update_predictor(dlt, plt, rlt); + + // INVQAH: higher sub-band inverse quantization + let (sih_dec, ih2) = IH2_MAP[ih & 0x03]; + let wd1 = (QQ2[ih2] as i32) << 3; + let wd2 = if sih_dec == 0 { wd1 } else { -wd1 }; + let dh = mult(self.band_h.det as i16, wd2 as i16); + let yh = self.band_h.s.saturating_add(dh); + let rh = yh.clamp(-16384, 16383); + + // Higher sub-band scale factor adaptation (LOGSCH) + let wd_scale = mult(self.band_h.nb as i16, 32512); + let nbph = (wd_scale as i32 + WH[ih2] as i32).clamp(0, 22528); + self.band_h.nb = nbph; + self.band_h.det = scaleh(nbph); + let ph = dh.saturating_add(self.band_h.sz); + self.band_h.update_predictor(dh, ph, yh); + + // Synthesis QMF + self.qmf.filter(rl, rh) + } + + /// Decode G.722 octets into 16 kHz 16-bit linear PCM samples, appending to `dst`. + pub fn decode(&mut self, src: &[u8], dst: &mut Vec) -> Result<(), Error> { + if src.len() > MAX_INPUT_BYTES { + return Err(Error::InputTooLarge); + } + let needed_samples = src.len().saturating_mul(2); + if needed_samples > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } + dst.try_reserve(needed_samples).map_err(|_| Error::AllocationFailed)?; + for &octet in src { + let (s0, s1) = self.decode_octet(octet); + dst.push(s0); + dst.push(s1); + } + Ok(()) + } +} + +/// ITU-T G.722 64 kbit/s single-channel encoder. +#[derive(Debug, Clone)] +pub struct Encoder { + qmf: QmfTx, + band_l: BandState, + band_h: BandState, +} + +impl Default for Encoder { + fn default() -> Self { + Self::new() + } +} + +impl Encoder { + /// Create a new G.722 encoder initialized to standard reset state. + pub fn new() -> Self { + Self { qmf: QmfTx::new(), band_l: BandState::new(true), band_h: BandState::new(false) } + } + + /// Reset encoder internal state. + pub fn reset(&mut self) { + self.qmf.reset(); + self.band_l.reset(true); + self.band_h.reset(false); + } + + /// Encode a pair of 16 kHz 16-bit PCM samples into one 8-bit G.722 octet. + pub fn encode_sample_pair(&mut self, s0: i16, s1: i16) -> u8 { + // Analysis QMF + let (xl, xh) = self.qmf.filter(s0, s1); + + // Lower sub-band quantizer (QUANTL) + let el = xl.saturating_sub(self.band_l.s); + let sil = if el < 0 { -1 } else { 0 }; + let wd = if sil == 0 { el } else { 32767 - (el & 32767) }; + let mut mil: usize = 30; + for (k, &thresh_q) in Q6.iter().enumerate().skip(1) { + let thresh = (((thresh_q as i32) << 3) * self.band_l.det) >> 15; + if (wd as i32) < thresh { + mil = k; + break; + } + } + + // Table 16 conversion to IL + let il: u8 = if sil == 0 { + (62 - mil) as u8 + } else if mil == 1 { + 63 + } else if mil == 2 { + 62 + } else { + (34 - mil) as u8 + }; + + // Lower sub-band feedback and predictor update (INVQAL) + let ril = (il >> 2) as usize; + let (sil4, il4) = IL4_MAP[ril & 0x0F]; + let wd1 = (QQ4[il4] as i32) << 3; + let wd2 = if sil4 == 0 { wd1 } else { -wd1 }; + let dlt = mult(self.band_l.det as i16, wd2 as i16); + let plt = dlt.saturating_add(self.band_l.sz); + let rlt = self.band_l.s.saturating_add(dlt); + + // Lower sub-band scale factor adaptation (LOGSCL) + let wd_scale = mult(self.band_l.nb as i16, 32512); + let nbpl = (wd_scale as i32 + WL[il4] as i32).clamp(0, 18432); + self.band_l.nb = nbpl; + self.band_l.det = scalel(nbpl); + self.band_l.update_predictor(dlt, plt, rlt); + + // Higher sub-band quantizer (QUANTH) + let eh = xh.saturating_sub(self.band_h.s); + let sih = if eh < 0 { -1 } else { 0 }; + let wd = if sih == 0 { eh } else { 32767 - (eh & 32767) }; + let thresh = ((564 << 3) * self.band_h.det) >> 15; + let mih = if (wd as i32) < thresh { 1 } else { 2 }; + + // Table 20 conversion to IH + let ih: u8 = if sih == -1 { + if mih == 2 { 0 } else { 1 } + } else if mih == 1 { + 3 + } else { + 2 + }; + + // Higher sub-band feedback and predictor update (INVQAH) + let (sih_dec, ih2) = IH2_MAP[ih as usize]; + let wd1 = (QQ2[ih2] as i32) << 3; + let wd2 = if sih_dec == 0 { wd1 } else { -wd1 }; + let dh = mult(self.band_h.det as i16, wd2 as i16); + let yh = self.band_h.s.saturating_add(dh); + + // Higher sub-band scale factor adaptation (LOGSCH) + let wd_scale = mult(self.band_h.nb as i16, 32512); + let nbph = (wd_scale as i32 + WH[ih2] as i32).clamp(0, 22528); + self.band_h.nb = nbph; + self.band_h.det = scaleh(nbph); + let ph = dh.saturating_add(self.band_h.sz); + self.band_h.update_predictor(dh, ph, yh); + + // Multiplexer (MUX) + (ih << 6) | (il & 0x3F) + } + + /// Encode 16 kHz 16-bit linear PCM samples into G.722 octets, appending to `dst`. + pub fn encode(&mut self, src: &[i16], dst: &mut Vec) -> Result<(), Error> { + if !src.len().is_multiple_of(2) { + return Err(Error::OddSampleCount(src.len())); + } + if src.len() > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } + let needed_octets = src.len() / 2; + dst.try_reserve(needed_octets).map_err(|_| Error::AllocationFailed)?; + for &[s0, s1] in src.as_chunks::<2>().0 { + let octet = self.encode_sample_pair(s0, s1); + dst.push(octet); + } + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +#[inline] +fn table18_lookup(il: usize) -> (i16, usize) { + let il = il & 0x3F; + if (4..=31).contains(&il) { + (-1, 34 - il) + } else if il == 62 { + (-1, 2) + } else if il == 63 { + (-1, 1) + } else if (32..=61).contains(&il) { + (0, 62 - il) + } else { + // Transmission error fallbacks (0..=3) + (-1, 1) + } +} + +// --------------------------------------------------------------------------- +// Public Top-Level Functions +// --------------------------------------------------------------------------- + +/// Decode a mono 64 kbit/s G.722 stream into 16 kHz 16-bit linear PCM samples. +pub fn decode(bytes: &[u8]) -> Result, Error> { + let mut decoder = Decoder::new(); + let mut out = Vec::new(); + decoder.decode(bytes, &mut out)?; + Ok(out) +} + +/// Encode mono 16 kHz 16-bit linear PCM samples into a 64 kbit/s G.722 stream. +pub fn encode(samples: &[i16]) -> Result, Error> { + let mut encoder = Encoder::new(); + let mut out = Vec::new(); + encoder.encode(samples, &mut out)?; + Ok(out) +} + +/// Decode an interleaved multi-channel G.722 stream into interleaved 16 kHz 16-bit PCM samples. +pub fn decode_interleaved(bytes: &[u8], channels: usize) -> Result, Error> { + if channels == 0 || channels > MAX_CHANNELS { + return Err(Error::InvalidChannels(channels)); + } + if channels == 1 { + return decode(bytes); + } + if bytes.len() > MAX_INPUT_BYTES { + return Err(Error::InputTooLarge); + } + let frames = bytes.len() / channels; + let mut decoders: Vec = Vec::with_capacity(channels); + for _ in 0..channels { + decoders.push(Decoder::new()); + } + let total_samples = frames.saturating_mul(channels).saturating_mul(2); + let mut out = Vec::new(); + out.try_reserve(total_samples).map_err(|_| Error::AllocationFailed)?; + + // Each frame has `channels` bytes. Decode each byte with its channel's decoder, + // producing sample 0 for each channel, then sample 1 for each channel. + for chunk in bytes.chunks_exact(channels) { + let mut pairs = [(0i16, 0i16); MAX_CHANNELS]; + for (ch, &b) in chunk.iter().enumerate() { + pairs[ch] = decoders[ch].decode_octet(b); + } + for pair in pairs.iter().take(channels) { + out.push(pair.0); + } + for pair in pairs.iter().take(channels) { + out.push(pair.1); + } + } + Ok(out) +} + +/// Encode interleaved 16 kHz 16-bit PCM samples into an interleaved multi-channel G.722 stream. +pub fn encode_interleaved(samples: &[i16], channels: usize) -> Result, Error> { + if channels == 0 || channels > MAX_CHANNELS { + return Err(Error::InvalidChannels(channels)); + } + if channels == 1 { + return encode(samples); + } + if samples.len() > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } + let frame_len = channels.saturating_mul(2); + if !samples.len().is_multiple_of(frame_len) { + return Err(Error::OddSampleCount(samples.len())); + } + let frames = samples.len() / frame_len; + let mut encoders: Vec = Vec::with_capacity(channels); + for _ in 0..channels { + encoders.push(Encoder::new()); + } + let total_bytes = frames.saturating_mul(channels); + let mut out = Vec::new(); + out.try_reserve(total_bytes).map_err(|_| Error::AllocationFailed)?; + + for chunk in samples.chunks_exact(frame_len) { + for ch in 0..channels { + let s0 = chunk[ch]; + let s1 = chunk[ch + channels]; + out.push(encoders[ch].encode_sample_pair(s0, s1)); + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reject_invalid_channels() { + assert_eq!(decode_interleaved(&[0; 4], 0), Err(Error::InvalidChannels(0))); + assert_eq!(decode_interleaved(&[0; 4], 9), Err(Error::InvalidChannels(9))); + assert_eq!(encode_interleaved(&[0; 4], 0), Err(Error::InvalidChannels(0))); + assert_eq!(encode_interleaved(&[0; 4], 9), Err(Error::InvalidChannels(9))); + } + + #[test] + fn reject_odd_sample_count() { + assert_eq!(encode(&[0; 3]), Err(Error::OddSampleCount(3))); + assert_eq!(encode_interleaved(&[0; 5], 2), Err(Error::OddSampleCount(5))); + } + + #[test] + fn roundtrip_silence() { + let input = vec![0i16; 320]; + let encoded = encode(&input).expect("encode silence"); + assert_eq!(encoded.len(), 160); + let decoded = decode(&encoded).expect("decode silence"); + assert_eq!(decoded.len(), 320); + for &s in &decoded[40..] { + assert!(s.abs() <= 6, "silence sample too large: {s}"); + } + } + + #[test] + fn multichannel_stereo_roundtrip() { + let mut stereo_pcm = Vec::new(); + for i in 0..400 { + stereo_pcm.push((i * 10) as i16); + stereo_pcm.push((-i * 10) as i16); + } + let enc = encode_interleaved(&stereo_pcm, 2).expect("encode stereo"); + assert_eq!(enc.len(), 400); + let dec = decode_interleaved(&enc, 2).expect("decode stereo"); + assert_eq!(dec.len(), 800); + } + + #[test] + fn hostile_input_does_not_panic() { + let garbage = [0xFF, 0x00, 0x55, 0xAA, 0x12, 0x34, 0x7F, 0x80]; + let dec = decode(&garbage).expect("decode garbage"); + assert_eq!(dec.len(), 16); + } + + #[test] + fn uppol2_overflow_does_not_panic() { + let mut state = BandState::new(true); + state.a[1] = -8192; + state.p = [0, 0, 0]; + state.update_predictor(0, 0, 0); + } +} diff --git a/crates/audio/src/g726.rs b/crates/audio/src/g726.rs new file mode 100644 index 000000000..6ac02359d --- /dev/null +++ b/crates/audio/src/g726.rs @@ -0,0 +1,996 @@ +//! ITU-T Recommendation G.726 ADPCM speech codec (16, 24, 32, 40 kbit/s). +//! +//! Clean-room implementation based on ITU-T Recommendation G.726 (12/1990) +//! "40, 32, 24, 16 kbit/s Adaptive Differential Pulse Code Modulation (ADPCM)". +//! +//! Provides encoding from 8 kHz 16-bit linear PCM to G.726 bitstreams, and decoding +//! from G.726 bitstreams to 8 kHz 16-bit linear PCM. +//! +//! Supports both standard big-endian bit packing (network order / RFC 3551) and +//! little-endian bit packing (RIFF WAV / AVID format tag 0x0045 / 0x0014). + +const MAX_CHANNELS: usize = 8; +const MAX_INPUT_BYTES: usize = 64 * 1024 * 1024; +const MAX_SAMPLES: usize = 64 * 1024 * 1024; + +/// Bit rate for G.726 ADPCM. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BitRate { + /// 16 kbit/s (2 bits per sample). + Rate16k, + /// 24 kbit/s (3 bits per sample). + Rate24k, + /// 32 kbit/s (4 bits per sample). + Rate32k, + /// 40 kbit/s (5 bits per sample). + Rate40k, +} + +impl BitRate { + /// Number of bits per code (sample). + #[inline] + #[must_use] + pub const fn code_size(self) -> usize { + match self { + Self::Rate16k => 2, + Self::Rate24k => 3, + Self::Rate32k => 4, + Self::Rate40k => 5, + } + } + + /// Bit rate in bits per second. + #[inline] + #[must_use] + pub const fn bit_rate_bps(self) -> u32 { + match self { + Self::Rate16k => 16_000, + Self::Rate24k => 24_000, + Self::Rate32k => 32_000, + Self::Rate40k => 40_000, + } + } +} + +/// Bit packing order within bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum BitPacking { + /// Big-endian packing: MSB to LSB (standard RFC 3551 / network order). + #[default] + BigEndian, + /// Little-endian packing: LSB to MSB (WAV / RIFF order). + LittleEndian, +} + +/// Errors returned by G.726 operations. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// Channel count must be between 1 and 8. + #[error("unsupported channel count: {0} (must be 1..=8)")] + InvalidChannels(usize), + /// Input exceeds safe maximum memory bound. + #[error("input exceeds safe maximum processing limit")] + InputTooLarge, + /// Output buffer allocation failed. + #[error("memory allocation failed")] + AllocationFailed, +} + +// --------------------------------------------------------------------------- +// G.726 Tables +// --------------------------------------------------------------------------- + +// Table 11..14 (I -> DQS, DQLN) +static OUT_16: [(u8, u16); 4] = [(0, 116), (0, 365), (1, 365), (1, 116)]; + +static OUT_24: [(u8, u16); 8] = [(0, 2048), (0, 135), (0, 273), (0, 373), (1, 373), (1, 273), (1, 135), (1, 2048)]; + +static OUT_32: [(u8, u16); 16] = [ + (0, 2048), + (0, 4), + (0, 135), + (0, 213), + (0, 273), + (0, 323), + (0, 373), + (0, 425), + (1, 425), + (1, 373), + (1, 323), + (1, 273), + (1, 213), + (1, 135), + (1, 4), + (1, 2048), +]; + +static OUT_40: [(u8, u16); 32] = [ + (0, 2048), + (0, 4030), + (0, 28), + (0, 104), + (0, 169), + (0, 224), + (0, 274), + (0, 318), + (0, 358), + (0, 395), + (0, 429), + (0, 459), + (0, 488), + (0, 514), + (0, 539), + (0, 566), + (1, 566), + (1, 539), + (1, 514), + (1, 488), + (1, 459), + (1, 429), + (1, 395), + (1, 358), + (1, 318), + (1, 274), + (1, 224), + (1, 169), + (1, 104), + (1, 28), + (1, 4030), + (1, 2048), +]; + +// FUNCTW: scale factor multipliers WI +static WI_16: [u16; 2] = [4074, 439]; +static WI_24: [u16; 4] = [4092, 30, 137, 582]; +static WI_32: [u16; 8] = [4084, 18, 41, 64, 112, 198, 355, 1122]; +static WI_40: [u16; 16] = [14, 14, 24, 39, 40, 41, 58, 100, 141, 179, 219, 280, 358, 440, 529, 696]; + +#[inline] +fn get_wi(rate: BitRate, code: u8) -> u16 { + match rate { + BitRate::Rate16k => { + let im = if (code >> 1) == 0 { (code & 1) as usize } else { ((3 - code) & 1) as usize }; + WI_16[im] + } + BitRate::Rate24k => { + let im = if (code >> 2) == 0 { (code & 3) as usize } else { ((7 - code) & 3) as usize }; + WI_24[im] + } + BitRate::Rate32k => { + let im = if (code >> 3) == 0 { (code & 7) as usize } else { ((15 - code) & 7) as usize }; + WI_32[im] + } + BitRate::Rate40k => { + let im = if (code >> 4) == 0 { (code & 15) as usize } else { ((31 - code) & 15) as usize }; + WI_40[im] + } + } +} + +#[inline] +fn get_fi(rate: BitRate, code: u8) -> u8 { + match rate { + BitRate::Rate16k => { + let im = if (code >> 1) == 0 { code & 1 } else { (3 - code) & 1 }; + if im == 1 { 7 } else { 0 } + } + BitRate::Rate24k => { + let im = if (code >> 2) == 0 { code & 3 } else { (7 - code) & 3 }; + match im { + 0 => 0, + 1 => 1, + 2 => 2, + _ => 7, + } + } + BitRate::Rate32k => { + let im = if (code >> 3) == 0 { code & 7 } else { (15 - code) & 7 }; + if im <= 2 { + 0 + } else if im <= 5 { + 1 + } else if im == 6 { + 3 + } else { + 7 + } + } + BitRate::Rate40k => { + let im = if (code >> 4) == 0 { code & 15 } else { (31 - code) & 15 }; + if im <= 4 { + 0 + } else if im <= 9 { + 1 + } else { + match im { + 10 => 2, + 11 => 3, + 12 => 4, + 13 => 5, + _ => 6, + } + } + } + } +} + +// Quantizer decision intervals (lo, hi, positive_code, negative_code) +static THRESH_16: [(i32, i32, u8, u8); 1] = [(261, 2047, 1, 2)]; + +static THRESH_24: [(i32, i32, u8, u8); 3] = [(331, 2047, 3, 4), (218, 330, 2, 5), (8, 217, 1, 6)]; + +static THRESH_32: [(i32, i32, u8, u8); 8] = [ + (400, 2047, 7, 8), + (349, 399, 6, 9), + (300, 348, 5, 10), + (246, 299, 4, 11), + (178, 245, 3, 12), + (80, 177, 2, 13), + (0, 79, 1, 14), + (3972, 4095, 1, 14), +]; + +static THRESH_40: [(i32, i32, u8, u8); 16] = [ + (553, 2047, 15, 16), + (528, 552, 14, 17), + (502, 527, 13, 18), + (475, 501, 12, 19), + (445, 474, 11, 20), + (413, 444, 10, 21), + (378, 412, 9, 22), + (339, 377, 8, 23), + (298, 338, 7, 24), + (250, 297, 6, 25), + (198, 249, 5, 26), + (139, 197, 4, 27), + (68, 138, 3, 28), + (0, 67, 2, 29), + (4080, 4095, 2, 29), + (3974, 4079, 1, 30), +]; + +#[inline] +fn quantize_16(dln: i32, ds: u8) -> u8 { + for &(lo, hi, pos, neg) in &THRESH_16 { + if (lo..=hi).contains(&dln) { + return if ds == 0 { pos } else { neg }; + } + } + if ds == 0 { 0 } else { 3 } +} + +#[inline] +fn quantize_24(dln: i32, ds: u8) -> u8 { + for &(lo, hi, pos, neg) in &THRESH_24 { + if (lo..=hi).contains(&dln) { + return if ds == 0 { pos } else { neg }; + } + } + 7 +} + +#[inline] +fn quantize_32(dln: i32, ds: u8) -> u8 { + for &(lo, hi, pos, neg) in &THRESH_32 { + if (lo..=hi).contains(&dln) { + return if ds == 0 { pos } else { neg }; + } + } + 15 +} + +#[inline] +fn quantize_40(dln: i32, ds: u8) -> u8 { + for &(lo, hi, pos, neg) in &THRESH_40 { + if (lo..=hi).contains(&dln) { + return if ds == 0 { pos } else { neg }; + } + } + 31 +} + +// --------------------------------------------------------------------------- +// G.726 Core State +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +struct Core { + rate: BitRate, + is_40k: bool, + a: [u16; 2], + b: [u16; 6], + dms: i16, + dml: i16, + ap: i16, + yu: i16, + yl: i32, + sr: [u16; 2], + dq: [u16; 6], + pk: [u8; 2], + td: i16, +} + +impl Core { + fn new(rate: BitRate) -> Self { + let is_40k = matches!(rate, BitRate::Rate40k); + let mut core = + Self { rate, is_40k, a: [0; 2], b: [0; 6], dms: 0, dml: 0, ap: 0, yu: 544, yl: 34816, sr: [32, 32], dq: [32; 6], pk: [0; 2], td: 0 }; + core.reset(); + core + } + + fn reset(&mut self) { + self.a = [0; 2]; + self.b = [0; 6]; + self.dms = 0; + self.dml = 0; + self.ap = 0; + self.yu = 544; + self.yl = 34816; + self.sr = [32, 32]; + self.dq = [32; 6]; + self.pk = [0; 2]; + self.td = 0; + } + + #[inline] + fn fmult(an: u16, srn: u16) -> u16 { + let an_s = (an >> 15) & 1; + let an_mag = if an_s == 0 { (an >> 2) & 0x1FFF } else { (16384_u32.wrapping_sub((an >> 2) as u32) & 0x1FFF) as u16 }; + let an_exp = if an_mag > 0 { (16 - an_mag.leading_zeros()).min(13) as u16 } else { 0 }; + let an_mant = if an_mag == 0 { 1 << 5 } else { (((an_mag as u32) << 6) >> an_exp) as u16 & 0x3F }; + + let srn_s = (srn >> 10) & 1; + let srn_exp = (srn >> 6) & 15; + let srn_mant = srn & 63; + + let wan_s = srn_s ^ an_s; + let wan_exp = srn_exp + an_exp; + let wan_mant = (((srn_mant as u32 * an_mant as u32) + 48) >> 4) as u16; + + let wan_mag = + if wan_exp <= 26 { ((wan_mant as u32) << 7) >> (26 - wan_exp) } else { (((wan_mant as u32) << 7) << (wan_exp - 26)) & 0x7FFF } as u16; + + if wan_s == 0 { wan_mag } else { (65536_u32.wrapping_sub(wan_mag as u32) & 0xFFFF) as u16 } + } + + #[inline] + fn quantize(&self, dln: i32, ds: u8) -> u8 { + match self.rate { + BitRate::Rate16k => quantize_16(dln, ds), + BitRate::Rate24k => quantize_24(dln, ds), + BitRate::Rate32k => quantize_32(dln, ds), + BitRate::Rate40k => quantize_40(dln, ds), + } + } + + #[inline] + fn table_lookup(&self, code: u8) -> (u8, u16) { + match self.rate { + BitRate::Rate16k => OUT_16[(code & 3) as usize], + BitRate::Rate24k => OUT_24[(code & 7) as usize], + BitRate::Rate32k => OUT_32[(code & 15) as usize], + BitRate::Rate40k => OUT_40[(code & 31) as usize], + } + } + + #[inline] + fn compute_accum(&self) -> (i16, i16) { + let wa0 = Self::fmult(self.a[0], self.sr[0]); + let wa1 = Self::fmult(self.a[1], self.sr[1]); + let mut sezi: u32 = 0; + for i in 0..6 { + sezi = (sezi + Self::fmult(self.b[i], self.dq[i]) as u32) & 0xFFFF; + } + let sei = (sezi + wa1 as u32 + wa0 as u32) & 0xFFFF; + let sez = (sezi as i16) >> 1; + let se = (sei as i16) >> 1; + (sez, se) + } + + #[inline] + fn compute_mix(&self) -> i32 { + let al = if self.ap >= 256 { 64 } else { self.ap >> 2 } as i32; + let dif = (self.yu as i32 + 16384 - (self.yl >> 6)) & 16383; + let difs = (dif >> 13) & 1; + let difm = if difs == 0 { dif } else { (16384 - dif) & 8191 }; + let prodm = (difm * al) >> 6; + let prod = if difs == 0 { prodm } else { (16384 - prodm) & 8191 }; + ((self.yl >> 6) + prod) & 8191 + } + + #[inline] + fn quantize_sample(&self, sample: i16, se: i16, y: i32) -> u8 { + let sl = (sample >> 2) as i32; + let sl_ext = if sl >= 0 { sl } else { 65536 + sl }; + let se_ext = if se >= 0 { se as i32 } else { 65536 + se as i32 }; + let d = ((sl_ext + 65536 - se_ext) & 0xFFFF) as u16; + + let ds = ((d >> 15) & 1) as u8; + let dqm = if ds == 0 { d } else { (65536_u32.wrapping_sub(d as u32) & 0x7FFF) as u16 }; + let exp = if dqm > 1 { (15 - dqm.leading_zeros()).min(14) } else { 0 }; + let mant = (((dqm as u32) << 7) >> exp) & 127; + let dl = ((exp << 7) + mant) as u16; + let dln = (dl as i32 + 4096 - (y >> 2)) & 4095; + self.quantize(dln, ds) + } + + #[inline] + fn step(&mut self, sample: i16, is_encoder: bool, code_in: u8) -> (u8, i16) { + let (sez, se) = self.compute_accum(); + let y = self.compute_mix(); + + let code = if is_encoder { self.quantize_sample(sample, se, y) } else { code_in }; + + // 4. RECONST & ADDA & ANTILOG + let (dqs, dqln) = self.table_lookup(code); + let dql = (dqln as i32 + (y >> 2)) & 4095; + let dex = (dql >> 7) & 15; + let dmn = dql & 127; + let dqt = 128 + dmn; + let dqmag = if (dql >> 11) == 0 { ((dqt << 7) >> (14 - dex)) as u16 } else { 0 }; + let dq = if self.is_40k { ((dqs as u16) << 15) | (dqmag & 0x7FFF) } else { ((dqs as u16) << 14) | (dqmag & 0x3FFF) }; + + // 5. ADDB & ADDC + let dqi = if dqs == 0 { + dq as u32 + } else if self.is_40k { + 65536_u32.wrapping_sub((dq & 0x7FFF) as u32) & 0xFFFF + } else { + 65536_u32.wrapping_sub((dq & 0x3FFF) as u32) & 0xFFFF + }; + let sei_ext = if se >= 0 { se as u32 } else { (65536 + se as i32) as u32 }; + let sr = ((dqi + sei_ext) & 0xFFFF) as u16; + + let sezi_ext = if sez >= 0 { sez as u32 } else { (65536 + sez as i32) as u32 }; + let dqsez = ((dqi + sezi_ext) & 0xFFFF) as u16; + let pk0 = ((dqsez >> 15) & 1) as u8; + let sigpk = if dqsez == 0 { 1 } else { 0 }; + + // 6. FLOATA & FLOATB + let dq_mag = if self.is_40k { dq & 0x7FFF } else { dq & 0x3FFF }; + let (dq_exp, dq_mant) = if dq_mag == 0 { + (0, 32) + } else { + let max_exp = if self.is_40k { 15 } else { 14 }; + let exp = (16 - dq_mag.leading_zeros()).min(max_exp); + let mant = (((dq_mag as u32) << 6) >> exp) as u16; + (exp as u16, mant) + }; + let dq0 = ((dqs as u16) << 10) | (dq_exp << 6) | (dq_mant & 63); + + let sr_s = ((sr >> 15) & 1) as u8; + let sr_mag = if sr_s == 0 { sr } else { (65536_u32.wrapping_sub(sr as u32) & 0x7FFF) as u16 }; + let (sr_exp, sr_mant) = if sr_mag == 0 { + (0, 32) + } else { + let exp = (16 - sr_mag.leading_zeros()).min(15); + let mant = (((sr_mag as u32) << 6) >> exp) as u16; + (exp as u16, mant) + }; + let sr0 = ((sr_s as u16) << 10) | (sr_exp << 6) | (sr_mant & 63); + + self.update_adaptation_and_predictors(code, y, pk0, sigpk, dqs, dq_mag); + + self.sr = [sr0, self.sr[0]]; + self.dq = [dq0, self.dq[0], self.dq[1], self.dq[2], self.dq[3], self.dq[4]]; + self.pk = [pk0, self.pk[0]]; + + let sr_signed = if sr < 32768 { sr as i32 } else { sr as i32 - 65536 }; + let out_pcm = (sr_signed << 2).clamp(-32768, 32767) as i16; + (code, out_pcm) + } + + #[inline] + fn adapt_scale(&mut self, code: u8, y: i32) { + let wi = get_wi(self.rate, code); + let dif = (((wi as i32) << 5) + 131072 - y) & 131071; + let difs = (dif >> 16) & 1; + let difsx = if difs == 0 { dif >> 5 } else { (dif >> 5) + 4096 }; + let yut = (y + difsx) & 8191; + let yup = yut.clamp(544, 5120); + + let dif = (yup + ((1048576 - self.yl) >> 6)) & 16383; + let difs = (dif >> 13) & 1; + let difsx = if difs == 0 { dif } else { dif + 507904 }; + self.yu = yup as i16; + self.yl = (self.yl + difsx) & 524287; + } + + #[inline] + fn adapt_speed(&mut self, code: u8, y: i32, dq_mag: u16) -> (i16, i16, u8) { + let fi = get_fi(self.rate, code); + let dif = (((fi as i32) << 9) + 8192 - self.dms as i32) & 8191; + let difs = (dif >> 12) & 1; + let difsx = if difs == 0 { dif >> 5 } else { (dif >> 5) + 3840 }; + let dmsp = ((difsx + self.dms as i32) & 4095) as i16; + + let dif = (((fi as i32) << 11) + 32768 - self.dml as i32) & 32767; + let difs = (dif >> 14) & 1; + let difsx = if difs == 0 { dif >> 7 } else { (dif >> 7) + 16128 }; + let dmlp = ((difsx + self.dml as i32) & 16383) as i16; + + let dif = (((dmsp as i32) << 2) + 32768 - dmlp as i32) & 32767; + let difs = (dif >> 14) & 1; + let difm = if difs == 0 { dif } else { (32768 - dif) & 16383 }; + let dthr = (dmlp as i32) >> 3; + + let tdp = if (32768..53760).contains(&self.a[1]) { 1 } else { 0 }; + let ax = if y >= 1536 && tdp == 0 && difm < dthr { 0 } else { 1 }; + + let dif = ((ax << 9) + 2048 - self.ap as i32) & 2047; + let difs = (dif >> 10) & 1; + let difsx = if difs == 0 { dif >> 4 } else { (dif >> 4) + 1920 }; + let app = ((difsx + self.ap as i32) & 1023) as i16; + + let ylint = (self.yl >> 15) as u32; + let ylfrac = ((self.yl >> 10) & 31) as u32; + let thr1 = (32 + ylfrac) << ylint; + let thr2 = if self.is_40k && ylint > 9 { + 31 << 10 + } else if !self.is_40k && ylint > 8 { + 31 << 9 + } else { + thr1 + }; + let dqthr = (thr2 + (thr2 >> 1)) >> 1; + let tr = if (dq_mag as u32) > dqthr && self.td == 1 { 1 } else { 0 }; + let apr = if tr == 1 { 256 } else { app }; + + self.dms = dmsp; + self.dml = dmlp; + self.ap = apr; + self.td = if tr == 1 { 0 } else { tdp }; + + (apr, tdp, tr) + } + + #[inline] + fn update_predictors(&mut self, pk0: u8, sigpk: u8, dqs: u8, dq_mag: u16, tr: u8) { + let pks = pk0 ^ self.pk[0]; + let uga1 = if sigpk == 1 { + 0 + } else if pks == 0 { + 192 + } else { + 65344 + }; + let a1s = (self.a[0] >> 15) & 1; + let ula1 = if a1s == 0 { + (65536_u32.wrapping_sub((self.a[0] >> 8) as u32) & 0xFFFF) as u16 + } else { + (65536_u32.wrapping_sub(((self.a[0] >> 8) + 65280) as u32) & 0xFFFF) as u16 + }; + let ua1 = (uga1 as u32 + ula1 as u32) & 0xFFFF; + let a1t = ((self.a[0] as u32 + ua1) & 0xFFFF) as u16; + + let pks1 = pk0 ^ self.pk[0]; + let pks2 = pk0 ^ self.pk[1]; + let uga2a = if pks2 == 0 { 16384_u32 } else { 114688_u32 }; + let a1_u = self.a[0]; + let fa1 = if a1s == 0 { + if a1_u <= 8191 { (a1_u as u32) << 2 } else { 8191 << 2 } + } else if a1_u >= 57345 { + ((a1_u as u32) << 2) & 131071 + } else { + 24577 << 2 + }; + let fa = if pks1 == 1 { fa1 } else { (131072_u32.wrapping_sub(fa1)) & 131071 }; + let uga2b = (uga2a + fa) & 131071; + let uga2s = (uga2b >> 16) & 1; + let uga2 = if sigpk == 1 { + 0 + } else if uga2s == 0 { + uga2b >> 7 + } else { + (uga2b >> 7) + 64512 + } as u16; + let a2s = (self.a[1] >> 15) & 1; + let ula2 = if a2s == 0 { + (65536_u32.wrapping_sub((self.a[1] >> 7) as u32) & 0xFFFF) as u16 + } else { + (65536_u32.wrapping_sub(((self.a[1] >> 7) + 65024) as u32) & 0xFFFF) as u16 + }; + let ua2 = (uga2 as u32 + ula2 as u32) & 0xFFFF; + let a2t = ((self.a[1] as u32 + ua2) & 0xFFFF) as u16; + + let a2p = if (32768..=53248).contains(&a2t) { + 53248 + } else if (12288..=32767).contains(&a2t) { + 12288 + } else { + a2t + }; + + let ome = 15360_u32; + let a1ul = ((ome + 65536 - a2p as u32) & 0xFFFF) as u16; + let a1ll = ((a2p as u32 + 65536 - ome) & 0xFFFF) as u16; + let a1p = if a1t >= 32768 && a1t <= a1ll { + a1ll + } else if a1t >= a1ul && a1t <= 32767 { + a1ul + } else { + a1t + }; + + let a1r = if tr == 1 { 0 } else { a1p }; + let a2r = if tr == 1 { 0 } else { a2p }; + + let mut new_b = [0u16; 6]; + for (i, slot) in new_b.iter_mut().enumerate() { + let un = (dqs ^ ((self.dq[i] >> 10) as u8)) & 1; + let ugbn = if dq_mag == 0 { + 0 + } else if un == 0 { + 128 + } else { + 65408 + }; + let bns = (self.b[i] >> 15) & 1; + let ulbn = if self.is_40k { + if bns == 0 { + (65536_u32.wrapping_sub((self.b[i] >> 9) as u32) & 0xFFFF) as u16 + } else { + (65536_u32.wrapping_sub(((self.b[i] >> 9) + 65408) as u32) & 0xFFFF) as u16 + } + } else if bns == 0 { + (65536_u32.wrapping_sub((self.b[i] >> 8) as u32) & 0xFFFF) as u16 + } else { + (65536_u32.wrapping_sub(((self.b[i] >> 8) + 65280) as u32) & 0xFFFF) as u16 + }; + let ubn = (ugbn as u32 + ulbn as u32) & 0xFFFF; + let bnp = ((self.b[i] as u32 + ubn) & 0xFFFF) as u16; + *slot = if tr == 1 { 0 } else { bnp }; + } + + self.a[0] = a1r; + self.a[1] = a2r; + self.b = new_b; + } + + #[inline] + fn update_adaptation_and_predictors(&mut self, code: u8, y: i32, pk0: u8, sigpk: u8, dqs: u8, dq_mag: u16) { + self.adapt_scale(code, y); + let (_, _, tr) = self.adapt_speed(code, y, dq_mag); + self.update_predictors(pk0, sigpk, dqs, dq_mag, tr); + } +} + +// --------------------------------------------------------------------------- +// Decoder & Encoder structs +// --------------------------------------------------------------------------- + +/// G.726 ADPCM decoder. +#[derive(Debug, Clone)] +pub struct Decoder { + core: Core, + packing: BitPacking, + bit_buf: u32, + num_bits: usize, +} + +impl Decoder { + /// Create a new G.726 decoder at the specified bit rate and bit packing. + #[must_use] + pub fn new(rate: BitRate, packing: BitPacking) -> Self { + Self { core: Core::new(rate), packing, bit_buf: 0, num_bits: 0 } + } + + /// Reset decoder internal predictor state. + pub fn reset(&mut self) { + self.core.reset(); + self.bit_buf = 0; + self.num_bits = 0; + } + + /// Decode a single quantized ADPCM code into an 8 kHz 16-bit linear PCM sample. + /// Bits above the configured code width are ignored, as in packed-stream decoding. + #[inline] + pub fn decode_sample(&mut self, code: u8) -> i16 { + // Adaptation must see the same bounded codeword as the reconstruction table; + // otherwise unused high bits can underflow its unsigned inverse-code arithmetic. + let code = code & ((1u8 << self.core.rate.code_size()) - 1); + self.core.step(0, false, code).1 + } + + /// Decode G.726 bitstream bytes into 8 kHz 16-bit linear PCM samples, appending to `dst`. + pub fn decode(&mut self, src: &[u8], dst: &mut Vec) -> Result<(), Error> { + if src.len() > MAX_INPUT_BYTES { + return Err(Error::InputTooLarge); + } + let cs = self.core.rate.code_size(); + let est_samples = (src.len() * 8) / cs; + dst.try_reserve(est_samples).map_err(|_| Error::AllocationFailed)?; + + match self.packing { + BitPacking::BigEndian => { + for &b in src { + self.bit_buf = ((self.bit_buf & ((1 << self.num_bits) - 1)) << 8) | (b as u32); + self.num_bits += 8; + while self.num_bits >= cs { + let code = ((self.bit_buf >> (self.num_bits - cs)) & ((1 << cs) - 1)) as u8; + self.num_bits -= cs; + let s = self.decode_sample(code); + dst.push(s); + } + self.bit_buf &= (1 << self.num_bits) - 1; + } + } + BitPacking::LittleEndian => { + for &b in src { + self.bit_buf |= (b as u32) << self.num_bits; + self.num_bits += 8; + while self.num_bits >= cs { + let code = (self.bit_buf & ((1 << cs) - 1)) as u8; + self.bit_buf >>= cs; + self.num_bits -= cs; + let s = self.decode_sample(code); + dst.push(s); + } + } + } + } + Ok(()) + } +} + +/// G.726 ADPCM encoder. +#[derive(Debug, Clone)] +pub struct Encoder { + core: Core, + packing: BitPacking, + bit_buf: u32, + num_bits: usize, +} + +impl Encoder { + /// Create a new G.726 encoder at the specified bit rate and bit packing. + #[must_use] + pub fn new(rate: BitRate, packing: BitPacking) -> Self { + Self { core: Core::new(rate), packing, bit_buf: 0, num_bits: 0 } + } + + /// Reset encoder internal predictor state. + pub fn reset(&mut self) { + self.core.reset(); + self.bit_buf = 0; + self.num_bits = 0; + } + + /// Encode a single 8 kHz 16-bit linear PCM sample into an ADPCM code word. + #[inline] + pub fn encode_sample(&mut self, sample: i16) -> u8 { + self.core.step(sample, true, 0).0 + } + + /// Encode 8 kHz 16-bit linear PCM samples into G.726 bitstream bytes, appending to `dst`. + pub fn encode(&mut self, src: &[i16], dst: &mut Vec) -> Result<(), Error> { + if src.len() > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } + let cs = self.core.rate.code_size(); + let est_bytes = (src.len() * cs).div_ceil(8); + dst.try_reserve(est_bytes).map_err(|_| Error::AllocationFailed)?; + + match self.packing { + BitPacking::BigEndian => { + for &s in src { + let code = self.encode_sample(s); + self.bit_buf = ((self.bit_buf & ((1 << self.num_bits) - 1)) << cs) | ((code as u32) & ((1 << cs) - 1)); + self.num_bits += cs; + while self.num_bits >= 8 { + dst.push(((self.bit_buf >> (self.num_bits - 8)) & 0xFF) as u8); + self.num_bits -= 8; + } + self.bit_buf &= (1 << self.num_bits) - 1; + } + } + BitPacking::LittleEndian => { + for &s in src { + let code = self.encode_sample(s); + self.bit_buf |= (code as u32) << self.num_bits; + self.num_bits += cs; + while self.num_bits >= 8 { + dst.push((self.bit_buf & 0xFF) as u8); + self.bit_buf >>= 8; + self.num_bits -= 8; + } + } + } + } + Ok(()) + } + + /// Flush any remaining buffered bits into `dst`, padding with zeroes. + pub fn flush(&mut self, dst: &mut Vec) -> Result<(), Error> { + if self.num_bits > 0 { + dst.try_reserve(1).map_err(|_| Error::AllocationFailed)?; + match self.packing { + BitPacking::BigEndian => { + let b = ((self.bit_buf << (8 - self.num_bits)) & 0xFF) as u8; + dst.push(b); + } + BitPacking::LittleEndian => { + let b = (self.bit_buf & 0xFF) as u8; + dst.push(b); + } + } + self.bit_buf = 0; + self.num_bits = 0; + } + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Public Top-Level Functions +// --------------------------------------------------------------------------- + +/// Decode a mono G.726 bitstream into 8 kHz 16-bit linear PCM samples. +pub fn decode(bytes: &[u8], rate: BitRate, packing: BitPacking) -> Result, Error> { + let mut decoder = Decoder::new(rate, packing); + let mut out = Vec::new(); + decoder.decode(bytes, &mut out)?; + Ok(out) +} + +/// Encode mono 8 kHz 16-bit linear PCM samples into a G.726 bitstream. +pub fn encode(samples: &[i16], rate: BitRate, packing: BitPacking) -> Result, Error> { + let mut encoder = Encoder::new(rate, packing); + let mut out = Vec::new(); + encoder.encode(samples, &mut out)?; + encoder.flush(&mut out)?; + Ok(out) +} + +/// Decode an interleaved multi-channel G.726 stream into interleaved 8 kHz 16-bit PCM samples. +pub fn decode_interleaved(bytes: &[u8], channels: usize, rate: BitRate, packing: BitPacking) -> Result, Error> { + if channels == 0 || channels > MAX_CHANNELS { + return Err(Error::InvalidChannels(channels)); + } + if channels == 1 { + return decode(bytes, rate, packing); + } + if bytes.len() > MAX_INPUT_BYTES { + return Err(Error::InputTooLarge); + } + + let mut decoders: Vec = Vec::with_capacity(channels); + for _ in 0..channels { + decoders.push(Decoder::new(rate, packing)); + } + + let cs = rate.code_size(); + let est_samples = (bytes.len() * 8) / cs; + let mut out = Vec::new(); + out.try_reserve(est_samples).map_err(|_| Error::AllocationFailed)?; + + let mut ch_outs: Vec> = Vec::with_capacity(channels); + for _ in 0..channels { + ch_outs.push(Vec::new()); + } + + for (i, &b) in bytes.iter().enumerate() { + let ch = i % channels; + decoders[ch].decode(&[b], &mut ch_outs[ch])?; + } + + let min_len = ch_outs.iter().map(Vec::len).min().unwrap_or(0); + for i in 0..min_len { + for ch_out in ch_outs.iter().take(channels) { + out.push(ch_out[i]); + } + } + + Ok(out) +} + +/// Encode interleaved 8 kHz 16-bit PCM samples into an interleaved multi-channel G.726 stream. +pub fn encode_interleaved(samples: &[i16], channels: usize, rate: BitRate, packing: BitPacking) -> Result, Error> { + if channels == 0 || channels > MAX_CHANNELS { + return Err(Error::InvalidChannels(channels)); + } + if channels == 1 { + return encode(samples, rate, packing); + } + if samples.len() > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } + + let mut encoders: Vec = Vec::with_capacity(channels); + for _ in 0..channels { + encoders.push(Encoder::new(rate, packing)); + } + + let cs = rate.code_size(); + let est_bytes = (samples.len() * cs).div_ceil(8); + let mut out = Vec::new(); + out.try_reserve(est_bytes).map_err(|_| Error::AllocationFailed)?; + + let mut ch_samples: Vec> = Vec::with_capacity(channels); + for _ in 0..channels { + ch_samples.push(Vec::new()); + } + + for (i, &s) in samples.iter().enumerate() { + let ch = i % channels; + ch_samples[ch].push(s); + } + + let mut ch_bytes: Vec> = Vec::with_capacity(channels); + for ch in 0..channels { + let mut b = Vec::new(); + encoders[ch].encode(&ch_samples[ch], &mut b)?; + encoders[ch].flush(&mut b)?; + ch_bytes.push(b); + } + + let min_bytes = ch_bytes.iter().map(Vec::len).min().unwrap_or(0); + for i in 0..min_bytes { + for ch_b in ch_bytes.iter().take(channels) { + out.push(ch_b[i]); + } + } + + Ok(out) +} + +// --------------------------------------------------------------------------- +// Unit tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sample_api_ignores_unused_codeword_bits() { + for rate in [BitRate::Rate16k, BitRate::Rate24k, BitRate::Rate32k, BitRate::Rate40k] { + let mask = (1u8 << rate.code_size()) - 1; + let mut actual = Decoder::new(rate, BitPacking::BigEndian); + let mut expected = Decoder::new(rate, BitPacking::BigEndian); + for code in 0..=u8::MAX { + assert_eq!(actual.decode_sample(code), expected.decode_sample(code & mask)); + } + // High bits must not leave a different predictor state for later valid codes. + for code in 0..=mask { + assert_eq!(actual.decode_sample(code), expected.decode_sample(code)); + } + } + } + + #[test] + fn reject_invalid_channels() { + assert!(decode_interleaved(&[], 0, BitRate::Rate32k, BitPacking::BigEndian).is_err()); + assert!(decode_interleaved(&[], 9, BitRate::Rate32k, BitPacking::BigEndian).is_err()); + assert!(encode_interleaved(&[], 0, BitRate::Rate32k, BitPacking::BigEndian).is_err()); + assert!(encode_interleaved(&[], 9, BitRate::Rate32k, BitPacking::BigEndian).is_err()); + } + + #[test] + fn roundtrip_silence_all_rates() { + let pcm = vec![0i16; 64]; + for rate in [BitRate::Rate16k, BitRate::Rate24k, BitRate::Rate32k, BitRate::Rate40k] { + for packing in [BitPacking::BigEndian, BitPacking::LittleEndian] { + let encoded = encode(&pcm, rate, packing).expect("encode silence"); + let decoded = decode(&encoded, rate, packing).expect("decode silence"); + assert_eq!(decoded.len(), pcm.len()); + for &s in &decoded { + assert!(s.abs() <= 16, "silence sample too large: {s}"); + } + } + } + } + + #[test] + fn hostile_input_does_not_panic() { + let mut decoder = Decoder::new(BitRate::Rate32k, BitPacking::BigEndian); + let mut out = Vec::new(); + let hostile = vec![0xFF; 1024]; + let _ = decoder.decode(&hostile, &mut out); + + let mut decoder = Decoder::new(BitRate::Rate16k, BitPacking::LittleEndian); + let mut out = Vec::new(); + let _ = decoder.decode(&[0x00, 0xAA, 0x55, 0x12, 0x34], &mut out); + } +} diff --git a/crates/audio/src/gsm.rs b/crates/audio/src/gsm.rs new file mode 100644 index 000000000..450922c29 --- /dev/null +++ b/crates/audio/src/gsm.rs @@ -0,0 +1,1038 @@ +//! GSM 06.10 full-rate speech (RPE-LTP): a decoder (feature `gsm-decode`) and an encoder (feature +//! `gsm-encode`), 8 kHz mono, 13 kbit/s. +//! +//! Written from the public ETSI specification (GSM 06.10 / 3GPP TS 46.010, clause 5: the bit-exact +//! fixed-point description of the coder and decoder, and its tables). A frame is 160 samples +//! (20 ms) coded as 76 parameters in 260 bits: eight log-area ratios for the short-term filter, +//! then four sub-frames of 40 samples, each with a long-term lag and gain, an RPE grid position, +//! a block amplitude and thirteen 3-bit pulses. +//! +//! The arithmetic is the specification's own 16-bit saturating arithmetic, so the output is bit +//! exact. Samples are `i16`; the coder uses the upper 13 bits of its input and the decoder's +//! output has its three low bits clear, as the specification says. +//! +//! Two packings of the 260 bits are supported ([`Packing`]): +//! +//! - [`Packing::Raw`]: 33 bytes per frame, the signature nibble `0xD` and then the parameters +//! most significant bit first (the packing of RFC 3551 and of `.gsm` files). +//! - [`Packing::Wav49`]: 65 bytes per pair of frames, the parameters least significant bit first +//! (the packing of the WAV format tag `0x31`, "GSM 6.10"). +//! +//! Any 260 bits are a decodable frame, so decoding never fails on content, only on length. +//! Each stream starts from the specification's initial state. + +// Index loops follow the specification's pseudo-code, which numbers the arrays the same way. +#![allow(clippy::needless_range_loop)] +// The two halves share the arithmetic, tables and synthesis helpers; with only one feature on, some +// of them are unused. +#![cfg_attr(not(all(feature = "gsm-decode", feature = "gsm-encode")), allow(dead_code))] + +use std::fmt; + +/// Samples in a frame. +pub const FRAME_SAMPLES: usize = 160; +/// Samples in a sub-frame. +pub const SUBFRAME_SAMPLES: usize = 40; +/// Bytes of a frame in the [`Packing::Raw`] packing. +pub const RAW_FRAME_BYTES: usize = 33; +/// Bytes of a pair of frames in the [`Packing::Wav49`] packing. +pub const WAV49_BLOCK_BYTES: usize = 65; +/// The sampling rate, in Hz. +pub const SAMPLE_RATE: u32 = 8000; + +/// How the 260 bits of a frame are laid out in bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Packing { + /// 33 bytes per frame: `0xD` then the parameters, most significant bit first. + Raw, + /// 65 bytes per two frames: the parameters least significant bit first, with no signature. + Wav49, +} + +impl Packing { + /// Bytes of one block: a frame for [`Packing::Raw`], two frames for [`Packing::Wav49`]. + #[must_use] + pub const fn block_bytes(self) -> usize { + match self { + Self::Raw => RAW_FRAME_BYTES, + Self::Wav49 => WAV49_BLOCK_BYTES, + } + } + + /// Samples of one block. + #[must_use] + pub const fn block_samples(self) -> usize { + match self { + Self::Raw => FRAME_SAMPLES, + Self::Wav49 => 2 * FRAME_SAMPLES, + } + } +} + +/// What went wrong reading GSM data. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// The data is not a whole number of blocks. + Truncated { + /// The bytes in each block. + block: usize, + /// The bytes given. + len: usize, + }, + /// A raw frame does not start with the signature nibble `0xD`. + BadSignature { + /// The byte offset of the frame. + offset: usize, + }, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Truncated { block, len } => write!(f, "GSM data of {len} bytes is not a whole number of {block}-byte blocks"), + Self::BadSignature { offset } => write!(f, "GSM frame at byte {offset} does not start with the signature 0xD"), + } + } +} + +impl std::error::Error for Error {} + +// ------------------------------------------------------------------ the specification's arithmetic + +const MIN16: i32 = -32768; +const MAX16: i32 = 32767; + +fn sat16(x: i32) -> i32 { + x.clamp(MIN16, MAX16) +} +fn add(a: i32, b: i32) -> i32 { + sat16(a + b) +} +fn sub(a: i32, b: i32) -> i32 { + sat16(a - b) +} +fn mult(a: i32, b: i32) -> i32 { + if a == MIN16 && b == MIN16 { MAX16 } else { (a * b) >> 15 } +} +fn mult_r(a: i32, b: i32) -> i32 { + if a == MIN16 && b == MIN16 { MAX16 } else { (a * b + 16384) >> 15 } +} +fn abs16(a: i32) -> i32 { + if a == MIN16 { MAX16 } else { a.abs() } +} +fn l_add(a: i32, b: i32) -> i32 { + a.saturating_add(b) +} +fn l_sub(a: i32, b: i32) -> i32 { + a.saturating_sub(b) +} +fn l_mult(a: i32, b: i32) -> i32 { + let p = (i64::from(a) * i64::from(b)) << 1; + p.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32 +} +/// A 16-bit variable assigned from a wider value: the low 16 bits, signed. +fn w16(x: i32) -> i32 { + i32::from(x as i16) +} +/// The specification's `<<`: a negative count shifts right. +fn asl(x: i32, n: i32) -> i32 { + if n >= 0 { x.wrapping_shl(n.min(31) as u32) } else { asr(x, -n) } +} +/// The specification's `>>`: a negative count shifts left. +fn asr(x: i32, n: i32) -> i32 { + if n >= 0 { x >> n.min(31) } else { asl(x, -n) } +} +/// Left shifts that normalize a 32-bit value into `[2^30, 2^31)` (or its negative counterpart). +fn norm(x: i32) -> i32 { + if x == 0 { + return 0; + } + let y = if x < 0 { !x } else { x }; + if y == 0 { 31 } else { y.leading_zeros() as i32 - 1 } +} +/// Fractional division of `num` by `denum`, `0 < num <= denum`, as the specification gives it. +fn div(num: i32, denum: i32) -> i32 { + let (mut l_num, mut q) = (num, 0); + for _ in 0..15 { + q <<= 1; + l_num = l_num.wrapping_shl(1); + if l_num >= denum { + l_num = l_num.wrapping_sub(denum); + q += 1; + } + } + q +} + +// ------------------------------------------------------------------------------ the tables + +/// Table 5.1: `A`, `B`, `MIC`, `MAC` of the log-area ratio quantizers. +const A: [i32; 8] = [20480, 20480, 20480, 20480, 13964, 15360, 8534, 9036]; +const B: [i32; 8] = [0, 0, 2048, -2560, 94, -1792, -341, -1144]; +const MIC: [i32; 8] = [-32, -32, -16, -16, -8, -8, -4, -4]; +const MAC: [i32; 8] = [31, 31, 15, 15, 7, 7, 3, 3]; +/// Table 5.2: `1 / A`. +const INVA: [i32; 8] = [13107, 13107, 13107, 13107, 19223, 17476, 31454, 29708]; +/// Table 5.3a: decision levels of the long-term gain quantizer. +const DLB: [i32; 4] = [6554, 16384, 26214, 32767]; +/// Table 5.3b: its quantization levels. +const QLB: [i32; 4] = [3277, 11469, 21299, 32767]; +/// Table 5.4: the weighting filter. +const H: [i32; 11] = [-134, -374, 0, 2054, 5741, 8192, 5741, 2054, 0, -374, -134]; +/// Table 5.5: normalized inverse mantissa. +const NRFAC: [i32; 8] = [29128, 26215, 23832, 21846, 20165, 18725, 17476, 16384]; +/// Table 5.6: normalized direct mantissa. +const FAC: [i32; 8] = [18431, 20479, 22527, 24575, 26623, 28671, 30719, 32767]; + +// -------------------------------------------------------------------------- the parameters + +/// The parameters of one 40-sample sub-frame. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SubFrame { + /// Long-term lag, 7 bits (40 to 120 from a coder). + pub lag: u8, + /// Long-term gain index, 2 bits. + pub gain: u8, + /// RPE grid position, 2 bits. + pub grid: u8, + /// Block amplitude, 6 bits. + pub xmax: u8, + /// The 13 RPE pulses, 3 bits each. + pub pulses: [u8; 13], +} + +/// The 76 parameters of one frame. A decoder uses only the low bits each field is allowed. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Frame { + /// The eight log-area ratios, 6, 6, 5, 5, 4, 4, 3 and 3 bits, offset to be non-negative. + pub lar: [u8; 8], + /// The four sub-frames. + pub sub: [SubFrame; 4], +} + +const LAR_BITS: [u32; 8] = [6, 6, 5, 5, 4, 4, 3, 3]; +const SUB_FIELDS: usize = 4 + 13; +const PARAMS: usize = 8 + 4 * SUB_FIELDS; + +fn field_bits(i: usize) -> u32 { + if i < 8 { + return LAR_BITS.get(i).copied().unwrap_or(0); + } + match (i - 8) % SUB_FIELDS { + 0 => 7, + 1 | 2 => 2, + 3 => 6, + _ => 3, + } +} + +impl Frame { + fn values(&self) -> [u8; PARAMS] { + let mut v = [0u8; PARAMS]; + v[..8].copy_from_slice(&self.lar); + for (j, s) in self.sub.iter().enumerate() { + let at = 8 + j * SUB_FIELDS; + v[at] = s.lag; + v[at + 1] = s.gain; + v[at + 2] = s.grid; + v[at + 3] = s.xmax; + v[at + 4..at + SUB_FIELDS].copy_from_slice(&s.pulses); + } + v + } + + fn from_values(v: &[u8; PARAMS]) -> Self { + let mut f = Self::default(); + f.lar.copy_from_slice(&v[..8]); + for (j, s) in f.sub.iter_mut().enumerate() { + let at = 8 + j * SUB_FIELDS; + s.lag = v[at]; + s.gain = v[at + 1]; + s.grid = v[at + 2]; + s.xmax = v[at + 3]; + s.pulses.copy_from_slice(&v[at + 4..at + SUB_FIELDS]); + } + f + } + + /// The frame in the [`Packing::Raw`] layout. + #[must_use] + pub fn to_raw(&self) -> [u8; RAW_FRAME_BYTES] { + let mut out = [0u8; RAW_FRAME_BYTES]; + out[0] = 0xD0; + let mut pos = 4usize; + for (i, &v) in self.values().iter().enumerate() { + let w = field_bits(i); + for b in (0..w).rev() { + if (u32::from(v) >> b) & 1 == 1 { + out[pos / 8] |= 0x80 >> (pos % 8); + } + pos += 1; + } + } + out + } + + /// A frame from the [`Packing::Raw`] layout; fails when the signature nibble is not `0xD`. + pub fn from_raw(bytes: &[u8; RAW_FRAME_BYTES]) -> Result { + if bytes[0] >> 4 != 0xD { + return Err(Error::BadSignature { offset: 0 }); + } + let mut v = [0u8; PARAMS]; + let mut pos = 4usize; + for (i, slot) in v.iter_mut().enumerate() { + let mut x = 0u8; + for _ in 0..field_bits(i) { + x = (x << 1) | ((bytes[pos / 8] >> (7 - pos % 8)) & 1); + pos += 1; + } + *slot = x; + } + Ok(Self::from_values(&v)) + } + + /// Two frames in the [`Packing::Wav49`] layout. + #[must_use] + pub fn pair_to_wav49(a: &Self, b: &Self) -> [u8; WAV49_BLOCK_BYTES] { + let mut out = [0u8; WAV49_BLOCK_BYTES]; + let mut pos = 0usize; + for f in [a, b] { + for (i, &v) in f.values().iter().enumerate() { + for bit in 0..field_bits(i) { + if (u32::from(v) >> bit) & 1 == 1 { + out[pos / 8] |= 1 << (pos % 8); + } + pos += 1; + } + } + } + out + } + + /// Two frames from the [`Packing::Wav49`] layout. + #[must_use] + pub fn pair_from_wav49(bytes: &[u8; WAV49_BLOCK_BYTES]) -> [Self; 2] { + let mut pos = 0usize; + let mut frames = [Self::default(); 2]; + for f in &mut frames { + let mut v = [0u8; PARAMS]; + for (i, slot) in v.iter_mut().enumerate() { + let mut x = 0u8; + for bit in 0..field_bits(i) { + x |= ((bytes[pos / 8] >> (pos % 8)) & 1) << bit; + pos += 1; + } + *slot = x; + } + *f = Self::from_values(&v); + } + frames + } +} + +// ------------------------------------------------------------------- shared synthesis pieces + +/// Clause 5.2.8: the decoded log-area ratios `LARpp` of a frame's coded ones. +fn decode_lar(lar: &[u8; 8]) -> [i32; 8] { + let mut out = [0i32; 8]; + for i in 0..8 { + let c = i32::from(lar[i] & ((1u8 << LAR_BITS[i]) - 1)); + let t1 = w16(add(c, MIC[i]) << 10); + let t2 = w16(B[i] << 1); + let t1 = sub(t1, t2); + let t1 = mult_r(INVA[i], t1); + out[i] = add(t1, t1); + } + out +} + +/// Clause 5.2.9.1: the interpolated log-area ratios of segment `seg` (0 to 3). +fn interpolate(prev: &[i32; 8], cur: &[i32; 8], seg: usize) -> [i32; 8] { + let mut out = [0i32; 8]; + for i in 0..8 { + out[i] = match seg { + 0 => add(add(prev[i] >> 2, cur[i] >> 2), prev[i] >> 1), + 1 => add(prev[i] >> 1, cur[i] >> 1), + 2 => add(add(prev[i] >> 2, cur[i] >> 2), cur[i] >> 1), + _ => cur[i], + }; + } + out +} + +/// Clause 5.2.9.2: reflection coefficients from log-area ratios. +fn reflection(larp: &[i32; 8]) -> [i32; 8] { + let mut rp = [0i32; 8]; + for i in 0..8 { + let a = abs16(larp[i]); + let t = if a < 11059 { + w16(a << 1) + } else if a < 20070 { + add(a, 11059) + } else { + add(a >> 2, 26112) + }; + rp[i] = if larp[i] < 0 { sub(0, t) } else { t }; + } + rp +} + +/// The sample ranges the four sets of interpolated coefficients cover. +const SEGMENTS: [(usize, usize); 4] = [(0, 12), (13, 26), (27, 39), (40, 159)]; + +/// The exponent and mantissa of a block amplitude (clause 5.2.15). +fn exp_mant(xmaxc: i32) -> (i32, i32) { + let mut exp = 0; + if xmaxc > 15 { + exp = (xmaxc >> 3) - 1; + } + let mut mant = xmaxc - (exp << 3); + if mant == 0 { + exp = -4; + mant = 15; + } else { + let mut itest = false; + for _ in 0..3 { + if mant > 7 { + itest = true; + } + if !itest { + mant = (mant << 1) + 1; + exp -= 1; + } + } + } + (exp, mant - 8) +} + +/// Clauses 5.2.16 and 5.2.17: the 40 samples of the long-term residual from a sub-frame's RPE data. +fn rpe_decode(s: &SubFrame) -> [i32; SUBFRAME_SAMPLES] { + let (exp, mant) = exp_mant(i32::from(s.xmax & 0x3F)); + let temp1 = FAC[mant as usize & 7]; + let temp2 = 6 - exp; + let temp3 = asl(1, temp2 - 1); + let mut ep = [0i32; SUBFRAME_SAMPLES]; + let grid = usize::from(s.grid & 3); + for (i, &p) in s.pulses.iter().enumerate() { + let t = sub(i32::from(p & 7) << 1, 7); + let t = w16(t << 12); + let t = mult_r(temp1, t); + let t = add(t, temp3); + let at = grid + 3 * i; + if at < SUBFRAME_SAMPLES { + ep[at] = asr(t, temp2); + } + } + ep +} + +/// The long-term lag, gain and reconstructed-residual history shared by coder and decoder. +#[derive(Clone)] +struct Synth { + /// The reconstructed short-term residual: `dp[-120..-1]`, oldest first. + dp: [i32; 120], + nrp: i32, + /// The short-term synthesis (or analysis) lattice state. + v: [i32; 9], + prev_lar: [i32; 8], +} + +impl Synth { + fn new() -> Self { + Self { dp: [0; 120], nrp: 40, v: [0; 9], prev_lar: [0; 8] } + } + + /// Clauses 5.3.1 and 5.3.2 for one sub-frame: the reconstructed residual, which is also pushed + /// into the history. + fn long_term(&mut self, s: &SubFrame) -> [i32; SUBFRAME_SAMPLES] { + let erp = rpe_decode(s); + let mut nr = i32::from(s.lag & 0x7F); + if !(40..=120).contains(&nr) { + nr = self.nrp; + } + self.nrp = nr; + let brp = QLB[usize::from(s.gain & 3)]; + let mut drp = [0i32; SUBFRAME_SAMPLES]; + for k in 0..SUBFRAME_SAMPLES { + // dp[k - nr] with k - nr in -120..=-1 is the history; later samples are this sub-frame's own. + let idx = 120 + k as i32 - nr; + let past = if idx < 120 { self.dp[idx as usize] } else { drp[(idx - 120) as usize] }; + drp[k] = add(erp[k], mult_r(brp, past)); + } + self.dp.copy_within(40.., 0); + self.dp[80..].copy_from_slice(&drp); + drp + } +} + +// ------------------------------------------------------------------------------ the decoder + +#[cfg(feature = "gsm-decode")] +/// A GSM 06.10 decoder. It keeps the filter and long-term state between frames. +#[derive(Clone)] +pub struct Decoder { + synth: Synth, + msr: i32, +} + +#[cfg(feature = "gsm-decode")] +impl Default for Decoder { + fn default() -> Self { + Self::new() + } +} + +#[cfg(feature = "gsm-decode")] +impl Decoder { + /// A decoder in the specification's initial state. + #[must_use] + pub fn new() -> Self { + Self { synth: Synth::new(), msr: 0 } + } + + /// Decode one frame into 160 samples (clause 5.3). + pub fn decode_frame(&mut self, frame: &Frame) -> [i16; FRAME_SAMPLES] { + let cur = decode_lar(&frame.lar); + let mut wt = [0i32; FRAME_SAMPLES]; + for (j, s) in frame.sub.iter().enumerate() { + let drp = self.synth.long_term(s); + wt[j * SUBFRAME_SAMPLES..(j + 1) * SUBFRAME_SAMPLES].copy_from_slice(&drp); + } + let mut sr = [0i32; FRAME_SAMPLES]; + for (seg, &(k0, k1)) in SEGMENTS.iter().enumerate() { + let rrp = reflection(&interpolate(&self.synth.prev_lar, &cur, seg)); + for k in k0..=k1 { + let mut sri = wt[k]; + for i in 1..=8 { + sri = sub(sri, mult_r(rrp[8 - i], self.synth.v[8 - i])); + self.synth.v[9 - i] = add(self.synth.v[8 - i], mult_r(rrp[8 - i], sri)); + } + sr[k] = sri; + self.synth.v[0] = sri; + } + } + self.synth.prev_lar = cur; + let mut out = [0i16; FRAME_SAMPLES]; + for k in 0..FRAME_SAMPLES { + self.msr = add(sr[k], mult_r(self.msr, 28180)); + let up = add(self.msr, self.msr); + out[k] = ((up >> 3) << 3) as i16; + } + out + } +} + +// ------------------------------------------------------------------------------ the encoder + +#[cfg(feature = "gsm-encode")] +/// A GSM 06.10 encoder. It keeps the filter and long-term state between frames. +#[derive(Clone)] +pub struct Encoder { + synth: Synth, + z1: i32, + l_z2: i32, + mp: i32, + /// The short-term analysis filter state. + u: [i32; 8], +} + +#[cfg(feature = "gsm-encode")] +impl Default for Encoder { + fn default() -> Self { + Self::new() + } +} + +#[cfg(feature = "gsm-encode")] +impl Encoder { + /// An encoder in the specification's initial state. + #[must_use] + pub fn new() -> Self { + Self { synth: Synth::new(), z1: 0, l_z2: 0, mp: 0, u: [0; 8] } + } + + /// Clauses 5.2.0 to 5.2.3: scaling, offset compensation and pre-emphasis. + fn preprocess(&mut self, input: &[i16; FRAME_SAMPLES]) -> [i32; FRAME_SAMPLES] { + let mut s = [0i32; FRAME_SAMPLES]; + for k in 0..FRAME_SAMPLES { + let so = (i32::from(input[k]) >> 3) << 2; + let s1 = sub(so, self.z1); + self.z1 = so; + let mut l_s2 = s1 << 15; + let msp = self.l_z2 >> 15; + let lsp = l_sub(self.l_z2, msp << 15); + let temp = mult_r(lsp, 32735); + l_s2 = l_add(l_s2, temp); + self.l_z2 = l_add(l_mult(msp, 32735) >> 1, l_s2); + let sof = w16(l_add(self.l_z2, 16384) >> 15); + s[k] = add(sof, mult_r(self.mp, -28180)); + self.mp = sof; + } + s + } + + /// Clauses 5.2.4 to 5.2.7: the coded log-area ratios of the frame. + fn analyse(s: &[i32; FRAME_SAMPLES]) -> [u8; 8] { + // Autocorrelation, with the signal scaled so the sums cannot overflow. + let smax = s.iter().map(|&x| abs16(x)).max().unwrap_or(0); + let scalauto = if smax == 0 { 0 } else { 4 - norm(smax << 16) }; + let mut sc = *s; + if scalauto > 0 { + let temp = 16384 >> (scalauto - 1); + for x in &mut sc { + *x = mult_r(*x, temp); + } + } + let mut l_acf = [0i32; 9]; + for (k, acf) in l_acf.iter_mut().enumerate() { + for i in k..FRAME_SAMPLES { + *acf = l_add(*acf, l_mult(sc[i], sc[i - k])); + } + } + // Schur recursion for the reflection coefficients. + let mut r = [0i32; 9]; + if l_acf[0] != 0 { + let t = norm(l_acf[0]); + let mut acf = [0i32; 9]; + for k in 0..9 { + acf[k] = w16(l_acf[k].wrapping_shl(t as u32) >> 16); + } + let mut kk = [0i32; 9]; + for i in 1..=7 { + kk[9 - i] = acf[i]; + } + let mut p = acf; + for n in 1..=8 { + if p[0] < abs16(p[1]) { + break; + } + r[n] = div(abs16(p[1]), p[0]); + if p[1] > 0 { + r[n] = sub(0, r[n]); + } + if n == 8 { + break; + } + p[0] = add(p[0], mult_r(p[1], r[n])); + for m in 1..=8 - n { + p[m] = add(p[m + 1], mult_r(kk[9 - m], r[n])); + kk[9 - m] = add(kk[9 - m], mult_r(p[m + 1], r[n])); + } + } + } + // Log-area ratios, quantized and offset to be non-negative. + let mut lar = [0u8; 8]; + for i in 0..8 { + let mut t = abs16(r[i + 1]); + t = if t < 22118 { + t >> 1 + } else if t < 31130 { + sub(t, 11059) + } else { + w16(sub(t, 26112) << 2) + }; + let l = if r[i + 1] < 0 { sub(0, t) } else { t }; + let mut c = add(add(mult(A[i], l), B[i]), 256) >> 9; + c = c.clamp(MIC[i], MAC[i]); + lar[i] = (c - MIC[i]) as u8; + } + lar + } + + /// Encode 160 samples into one frame (clause 5.2). + pub fn encode_frame(&mut self, input: &[i16; FRAME_SAMPLES]) -> Frame { + let s = self.preprocess(input); + let mut frame = Frame { lar: Self::analyse(&s), ..Frame::default() }; + + // Short-term analysis filtering with the quantized coefficients. + let cur = decode_lar(&frame.lar); + let mut d = [0i32; FRAME_SAMPLES]; + for (seg, &(k0, k1)) in SEGMENTS.iter().enumerate() { + let rp = reflection(&interpolate(&self.synth.prev_lar, &cur, seg)); + for k in k0..=k1 { + let mut di = s[k]; + let mut sav = di; + for i in 0..8 { + let temp = add(self.u[i], mult_r(rp[i], di)); + di = add(di, mult_r(rp[i], self.u[i])); + self.u[i] = sav; + sav = temp; + } + d[k] = di; + } + } + self.synth.prev_lar = cur; + + for (j, sub_frame) in frame.sub.iter_mut().enumerate() { + let mut dj = [0i32; SUBFRAME_SAMPLES]; + dj.copy_from_slice(&d[j * SUBFRAME_SAMPLES..(j + 1) * SUBFRAME_SAMPLES]); + *sub_frame = self.code_subframe(&dj); + } + frame + } + + /// Clauses 5.2.11 to 5.2.18 for one sub-frame. + fn code_subframe(&mut self, d: &[i32; SUBFRAME_SAMPLES]) -> SubFrame { + let dp = self.synth.dp; + let hist = |k: usize, lambda: i32| dp[(120 + k as i32 - lambda) as usize]; + + // Long-term lag: the maximum cross-correlation with the reconstructed residual. + let dmax = d.iter().map(|&x| abs16(x)).max().unwrap_or(0); + let mut temp = 0; + let mut scal = 0; + if dmax != 0 { + temp = norm(dmax << 16); + } + if temp <= 6 { + scal = 6 - temp; + } + let mut wt = [0i32; SUBFRAME_SAMPLES]; + for k in 0..SUBFRAME_SAMPLES { + wt[k] = d[k] >> scal; + } + let mut l_max = 0i32; + let mut nc = 40i32; + for lambda in 40..=120 { + let mut l_result = 0i32; + for k in 0..SUBFRAME_SAMPLES { + l_result = l_add(l_result, l_mult(wt[k], hist(k, lambda))); + } + if l_result > l_max { + nc = lambda; + l_max = l_result; + } + } + l_max >>= 6 - scal; + + // Long-term gain. + for k in 0..SUBFRAME_SAMPLES { + wt[k] = hist(k, nc) >> 3; + } + let mut l_power = 0i32; + for k in 0..SUBFRAME_SAMPLES { + l_power = l_add(l_power, l_mult(wt[k], wt[k])); + } + let bc = if l_max <= 0 { + 0 + } else if l_max >= l_power { + 3 + } else { + let t = norm(l_power); + let r = w16(l_max.wrapping_shl(t as u32) >> 16); + let s = w16(l_power.wrapping_shl(t as u32) >> 16); + (0..3).find(|&b| r <= mult(s, DLB[b])).unwrap_or(3) + }; + + // Long-term analysis filtering. + let bp = QLB[bc]; + let mut dpp = [0i32; SUBFRAME_SAMPLES]; + let mut e = [0i32; SUBFRAME_SAMPLES]; + for k in 0..SUBFRAME_SAMPLES { + dpp[k] = mult_r(bp, hist(k, nc)); + e[k] = sub(d[k], dpp[k]); + } + + // Weighting filter, RPE grid selection. + let mut w = [0i32; 50]; + w[5..45].copy_from_slice(&e); + let mut x = [0i32; SUBFRAME_SAMPLES]; + for k in 0..SUBFRAME_SAMPLES { + let mut l_result = 8192i32; + for i in 0..11 { + l_result = l_add(l_result, l_mult(w[k + i], H[i])); + } + l_result = l_add(l_result, l_result); + l_result = l_add(l_result, l_result); + x[k] = l_result >> 16; + } + let mut em = 0i32; + let mut mc = 0usize; + for m in 0..4 { + let mut l_result = 0i32; + for i in 0..13 { + let t = x[m + 3 * i] >> 2; + l_result = l_add(l_result, l_mult(t, t)); + } + if l_result > em { + mc = m; + em = l_result; + } + } + let mut xm = [0i32; 13]; + for i in 0..13 { + xm[i] = x[mc + 3 * i]; + } + + // APCM quantization. + let xmax = xm.iter().map(|&v| abs16(v)).max().unwrap_or(0); + let mut exp = 0; + let mut t = xmax >> 9; + let mut itest = false; + for _ in 0..=5 { + if t <= 0 { + itest = true; + } + t >>= 1; + if !itest { + exp += 1; + } + } + let xmaxc = add(xmax >> (exp + 5), exp << 3); + let (exp, mant) = exp_mant(xmaxc); + let temp1 = 6 - exp; + let temp2 = NRFAC[mant as usize & 7]; + let mut pulses = [0u8; 13]; + for i in 0..13 { + let t = w16(asl(xm[i], temp1)); + let t = mult(t, temp2); + pulses[i] = (add(t >> 12, 4)).clamp(0, 7) as u8; + } + let coded = SubFrame { lag: nc as u8, gain: bc as u8, grid: mc as u8, xmax: xmaxc.clamp(0, 63) as u8, pulses }; + + // Reconstruct, exactly as the decoder will, to keep the history in step. + let ep = rpe_decode(&coded); + self.synth.dp.copy_within(40.., 0); + for k in 0..SUBFRAME_SAMPLES { + self.synth.dp[80 + k] = add(ep[k], dpp[k]); + } + coded + } +} + +// --------------------------------------------------------------------------------- streams + +#[cfg(feature = "gsm-decode")] +/// Decode a stream of whole blocks into 8 kHz samples. A [`Packing::Raw`] stream is checked for the +/// signature nibble of every frame. +pub fn decode(data: &[u8], packing: Packing) -> Result, Error> { + let block = packing.block_bytes(); + if !data.len().is_multiple_of(block) { + return Err(Error::Truncated { block, len: data.len() }); + } + let mut dec = Decoder::new(); + let mut out = Vec::with_capacity(data.len() / block * packing.block_samples()); + for (n, chunk) in data.chunks_exact(block).enumerate() { + match packing { + Packing::Raw => { + let mut b = [0u8; RAW_FRAME_BYTES]; + b.copy_from_slice(chunk); + let frame = Frame::from_raw(&b).map_err(|_| Error::BadSignature { offset: n * block })?; + out.extend_from_slice(&dec.decode_frame(&frame)); + } + Packing::Wav49 => { + let mut b = [0u8; WAV49_BLOCK_BYTES]; + b.copy_from_slice(chunk); + for frame in Frame::pair_from_wav49(&b) { + out.extend_from_slice(&dec.decode_frame(&frame)); + } + } + } + } + Ok(out) +} + +#[cfg(feature = "gsm-encode")] +/// Encode 8 kHz samples. The last block is padded with silence to a whole block, so the output +/// decodes to `samples.len()` rounded up to a block, with the first `samples.len()` as the signal. +#[must_use] +pub fn encode(samples: &[i16], packing: Packing) -> Vec { + let per_block = packing.block_samples(); + let mut enc = Encoder::new(); + let mut out = Vec::with_capacity(samples.len().div_ceil(per_block) * packing.block_bytes()); + for chunk in samples.chunks(per_block) { + let mut padded = [0i16; 2 * FRAME_SAMPLES]; + padded[..chunk.len()].copy_from_slice(chunk); + let mut frame = |at: usize| { + let mut input = [0i16; FRAME_SAMPLES]; + input.copy_from_slice(&padded[at..at + FRAME_SAMPLES]); + enc.encode_frame(&input) + }; + match packing { + Packing::Raw => out.extend_from_slice(&frame(0).to_raw()), + Packing::Wav49 => { + let a = frame(0); + let b = frame(FRAME_SAMPLES); + out.extend_from_slice(&Frame::pair_to_wav49(&a, &b)); + } + } + } + out +} + +#[cfg(all(test, feature = "gsm-decode", feature = "gsm-encode"))] +mod tests { + use super::*; + + fn xorshift(seed: &mut u32) -> u32 { + *seed ^= *seed << 13; + *seed ^= *seed >> 17; + *seed ^= *seed << 5; + *seed + } + + fn speechlike(n: usize) -> Vec { + let mut seed = 0x1234_5678u32; + (0..n) + .map(|i| { + let t = i as f64 / 8000.0; + let f0 = 120.0 + 30.0 * (t * 3.0).sin(); + let v = (t * f0 * std::f64::consts::TAU).sin() * 6000.0 + + (t * 3.0 * f0 * std::f64::consts::TAU).sin() * 2500.0 + + f64::from(xorshift(&mut seed) % 400) + - 200.0; + (v * (0.6 + 0.4 * (t * 5.0).sin())) as i16 + }) + .collect() + } + + #[test] + fn arithmetic_matches_the_specification() { + assert_eq!(add(32767, 1), 32767); + assert_eq!(sub(-32768, 1), -32768); + assert_eq!(mult(-32768, -32768), 32767); + assert_eq!(mult_r(-32768, -32768), 32767); + assert_eq!(mult_r(16384, 16384), 8192); + assert_eq!(abs16(-32768), 32767); + assert_eq!(div(5, 5), 32767); + assert_eq!(div(1, 2), 16384); + assert_eq!(norm(1), 30); + assert_eq!(norm(0x4000_0000), 0); + assert_eq!(norm(-1), 31); + assert_eq!(norm(i32::MIN), 0); + assert_eq!(asl(1, -1), 0); + assert_eq!(asr(-8, 1), -4); + assert_eq!(l_mult(-32768, -32768), i32::MAX); + } + + #[test] + fn raw_packing_round_trips_every_field() { + let mut seed = 99u32; + for _ in 0..200 { + let mut v = [0u8; PARAMS]; + for (i, x) in v.iter_mut().enumerate() { + *x = (xorshift(&mut seed) & ((1 << field_bits(i)) - 1)) as u8; + } + let frame = Frame::from_values(&v); + let raw = frame.to_raw(); + assert_eq!(raw[0] >> 4, 0xD); + assert_eq!(Frame::from_raw(&raw), Ok(frame)); + let pair = Frame::pair_to_wav49(&frame, &Frame::default()); + assert_eq!(Frame::pair_from_wav49(&pair), [frame, Frame::default()]); + let pair = Frame::pair_to_wav49(&Frame::default(), &frame); + assert_eq!(Frame::pair_from_wav49(&pair)[1], frame); + } + assert_eq!((0..PARAMS).map(field_bits).sum::(), 260); + } + + #[test] + fn a_raw_frame_needs_its_signature() { + let mut raw = Frame::default().to_raw(); + raw[0] = 0x30; + assert_eq!(Frame::from_raw(&raw), Err(Error::BadSignature { offset: 0 })); + assert_eq!(decode(&raw, Packing::Raw), Err(Error::BadSignature { offset: 0 })); + } + + #[test] + fn partial_blocks_are_rejected() { + assert_eq!(decode(&[0xD0; 32], Packing::Raw), Err(Error::Truncated { block: 33, len: 32 })); + assert_eq!(decode(&[0; 66], Packing::Wav49), Err(Error::Truncated { block: 65, len: 66 })); + assert_eq!(decode(&[], Packing::Raw), Ok(vec![])); + } + + #[test] + fn silence_stays_near_silence() { + let pcm = vec![0i16; 160 * 4]; + for packing in [Packing::Raw, Packing::Wav49] { + let bytes = encode(&pcm, packing); + let out = decode(&bytes, packing).expect("decode"); + assert_eq!(out.len(), pcm.len()); + // The quantizers have no exact zero, so silence comes back as a faint residue. + assert!(out.iter().all(|&s| s.abs() <= 32), "{packing:?}: {:?}", out.iter().map(|s| s.abs()).max()); + } + } + + #[test] + fn output_has_three_clear_low_bits() { + let out = decode(&encode(&speechlike(1600), Packing::Raw), Packing::Raw).expect("decode"); + assert!(out.iter().all(|&s| s & 7 == 0)); + } + + #[test] + fn speech_survives_the_round_trip() { + let pcm = speechlike(8000); + for packing in [Packing::Raw, Packing::Wav49] { + let out = decode(&encode(&pcm, packing), packing).expect("decode"); + assert_eq!(out.len(), pcm.len()); + let (mut sig, mut err) = (0f64, 0f64); + for i in 400..pcm.len() { + let (a, b) = (f64::from(pcm[i]), f64::from(out[i])); + sig += a * a; + err += (a - b) * (a - b); + } + let snr = 10.0 * (sig / err).log10(); + assert!(snr > 8.0, "{packing:?}: SNR {snr:.1} dB"); + } + } + + #[test] + fn encoding_is_deterministic_and_packings_agree() { + let pcm = speechlike(1600); + assert_eq!(encode(&pcm, Packing::Raw), encode(&pcm, Packing::Raw)); + let raw = decode(&encode(&pcm, Packing::Raw), Packing::Raw).expect("raw"); + let wav = decode(&encode(&pcm, Packing::Wav49), Packing::Wav49).expect("wav49"); + assert_eq!(raw, wav); + } + + #[test] + fn short_input_is_padded_to_a_block() { + assert_eq!(encode(&[], Packing::Raw), Vec::::new()); + assert_eq!(encode(&[100; 1], Packing::Raw).len(), 33); + assert_eq!(encode(&[100; 161], Packing::Raw).len(), 66); + assert_eq!(encode(&[100; 1], Packing::Wav49).len(), 65); + assert_eq!(encode(&[100; 321], Packing::Wav49).len(), 130); + } + + #[test] + fn any_bits_decode_without_panicking() { + let mut seed = 7u32; + for _ in 0..300 { + let mut v = [0u8; PARAMS]; + for x in &mut v { + // Fields wider than their width and lags outside 40..=120 must be tolerated. + *x = xorshift(&mut seed) as u8; + } + let frame = Frame::from_values(&v); + let mut dec = Decoder::new(); + for _ in 0..3 { + let _ = dec.decode_frame(&frame); + } + } + } + + #[test] + fn extreme_input_encodes_without_panicking() { + for pattern in [i16::MAX, i16::MIN] { + let pcm = vec![pattern; 1600]; + let out = decode(&encode(&pcm, Packing::Raw), Packing::Raw).expect("decode"); + assert_eq!(out.len(), 1600); + } + let alternating: Vec = (0..3200).map(|i| if i % 2 == 0 { i16::MAX } else { i16::MIN }).collect(); + let _ = encode(&alternating, Packing::Wav49); + let mut seed = 5u32; + let noise: Vec = (0..3200).map(|_| xorshift(&mut seed) as i16).collect(); + let _ = encode(&noise, Packing::Raw); + } + + #[test] + fn a_decoder_keeps_state_between_frames() { + let bytes = encode(&speechlike(1600), Packing::Raw); + let whole = decode(&bytes, Packing::Raw).expect("whole"); + let mut dec = Decoder::new(); + let mut piecewise = Vec::new(); + for b in bytes.as_chunks::<33>().0 { + piecewise.extend_from_slice(&dec.decode_frame(&Frame::from_raw(b).expect("frame"))); + } + assert_eq!(whole, piecewise); + } +} diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 1c6c73dcf..fcaf2897e 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -2,7 +2,7 @@ #![warn(missing_docs)] // The docs link items of every feature; built with fewer features, those links have no target. // CI and docs.rs build the docs with all features, where every link must resolve. -#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks")), allow(rustdoc::broken_intra_doc_links))] +#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks", feature = "dsd")), allow(rustdoc::broken_intra_doc_links))] //! Audio file I/O and codecs for the Craft apps. Input and output are byte slices or a //! [`craft_media::ByteSource`] (no filesystem access of its own); builds for //! `wasm32-unknown-unknown`. @@ -13,6 +13,9 @@ //! demuxers and [`TrackDecoder`]; everything else (FLAC, Vorbis, CAF, ADPCM, A-law, µ-law) through //! `symphonia`, which is to be replaced by native decoders. Feature `decode-native` is the //! same without symphonia. +//! - [`vorbis::decoder`] (feature `vorbis-decode`): the pure-Rust Vorbis I decoder, packets and Ogg files. +//! - [`encode_ogg_vorbis`] and [`vorbis::encoder`] (feature `vorbis-encode`): Ogg Vorbis files +//! and Vorbis packets from a pure-Rust encoder, 1 to 8 channels, quality -1 to 10, with tags. //! - [`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 @@ -26,8 +29,12 @@ //! - [`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`, and -//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`), [`mp3`] -//! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-encode`: the packet encoder). +//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`] +//! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder; +//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), [`adpcm`] +//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`dsd`] (`dsd`: DSF and DSDIFF files to PCM), +//! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech), [`vmd`] (`vmd-decode`: +//! Sierra VMD sound). //! //! The shared types below build with no features. @@ -35,9 +42,19 @@ pub mod aac; #[cfg(any(feature = "ac3-decode", feature = "ac3-encode", feature = "eac3-encode"))] pub mod ac3; +#[cfg(feature = "adpcm")] +pub mod adpcm; #[cfg(any(feature = "alac-decode", feature = "alac-encode"))] pub mod alac; mod buffer; +#[cfg(feature = "dsd")] +pub mod dsd; +#[cfg(feature = "g722")] +pub mod g722; +#[cfg(feature = "g726")] +pub mod g726; +#[cfg(any(feature = "gsm-decode", feature = "gsm-encode"))] +pub mod gsm; mod layout; #[cfg(any(feature = "mp3-encode", feature = "mp3-decode"))] pub mod mp3; @@ -49,12 +66,22 @@ pub mod opus; mod pcm; #[cfg(feature = "peaks")] pub mod peaks; +#[cfg(any(feature = "qoa-decode", feature = "qoa-encode"))] +pub mod qoa; #[cfg(feature = "decode-native")] mod read; +#[cfg(feature = "sbc")] +pub mod sbc; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] mod track; +#[cfg(feature = "vmd-decode")] +pub mod vmd; +#[cfg(any(feature = "vorbis-decode", feature = "vorbis-encode"))] +pub mod vorbis; #[cfg(any(feature = "decode-native", feature = "pcm-encode"))] mod wav; +/// Bounded WAV/RF64 cue, adtl and XMP marker metadata, without audio decoding. +pub mod wav_markers; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -62,10 +89,23 @@ mod wav; feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", - feature = "eac3-encode" + feature = "eac3-encode", + feature = "vorbis-encode" ))] mod write; +/// PCM WAVE and AIFF wrappers for interchange essence. +#[cfg(feature = "pcm-encode")] +pub mod essence_pcm; +/// Streaming WAVE and AIFF headers and sample packing. +pub mod pcm_export; +/// Interleaved PCM packet decoding. +pub mod pcm_interleaved; +/// Range-backed PCM WAVE access and a 16-bit PCM writer. +pub mod wav_range; +#[cfg(feature = "vorbis-encode")] +pub use write::{OGG_BITRATES, OggVorbisOptions, encode_ogg, encode_ogg_vorbis, quality_for_bitrate}; + /// 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 /// at the end. [`FileEncoder`] and [`encode`] write whole `.flac` files from `f32` instead. @@ -85,10 +125,15 @@ mod write; /// assert!(file.len() < 48_000 * 2 * 2 / 2); // well under half of 16-bit PCM /// # Ok::<(), craft_audio::flac::Error>(()) /// ``` -#[cfg(feature = "flac-encode")] +#[cfg(any(feature = "flac-encode", feature = "flac-decode"))] pub mod flac { + #[cfg(feature = "flac-decode")] + pub use crate::flac_decode::{DEFAULT_MAX_VALUES, DecodeError, Decoded, Decoder, Frame, StreamInfo, decode, decode_with_limit}; + #[cfg(feature = "flac-encode")] pub use crate::write::flac::encoder::{Encoder, EncoderConfig, Error, STREAMINFO_OFFSET}; } +#[cfg(feature = "flac-decode")] +mod flac_decode; pub use buffer::AudioBuffer; /// The craft-media this crate is built with, for its containers: using it rather than a separate @@ -107,8 +152,6 @@ 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(feature = "pcm-encode")] -pub use write::wav_float_header; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -118,7 +161,20 @@ pub use write::wav_float_header; feature = "ac3-encode", feature = "eac3-encode" ))] -pub use write::{ENCODE_EXTENSIONS, FileEncoder, encode, encode_format_for}; +pub use write::FileEncoder; +#[cfg(feature = "pcm-encode")] +pub use write::wav_float_header; +#[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}; @@ -224,6 +280,16 @@ impl From for AudioError { } } +#[cfg(feature = "vmd-decode")] +impl From for AudioError { + fn from(e: vmd::Error) -> Self { + match e { + vmd::Error::Unsupported(_) => AudioError::Unsupported(e.to_string()), + _ => AudioError::Malformed(e.to_string()), + } + } +} + #[cfg(feature = "opus-encode")] impl From for AudioError { fn from(e: opus::encoder::Error) -> Self { @@ -256,6 +322,10 @@ pub enum EncodeFormat { Ac3, /// An E-AC-3 stream: up to 7.1 at 32, 44.1 or 48 kHz. Eac3, + /// Ogg Vorbis, 1–8 channels at any sample rate, whole-buffer encoding only. Variable bit + /// rate: a [`RateControl::Bitrate`] picks the quality whose nominal rate it is + /// ([`quality_for_bitrate`]), [`RateControl::Quality`] sets it directly. + Ogg, } impl EncodeFormat { @@ -270,6 +340,7 @@ impl EncodeFormat { EncodeFormat::Mp3, EncodeFormat::Ac3, EncodeFormat::Eac3, + EncodeFormat::Ogg, ]; /// The extension a new file of this format gets, lower case and without the dot: `"wav"`, @@ -284,6 +355,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => "mp3", EncodeFormat::Ac3 => "ac3", EncodeFormat::Eac3 => "eac3", + EncodeFormat::Ogg => "ogg", } } @@ -297,6 +369,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => "audio/mpeg", EncodeFormat::Ac3 => "audio/ac3", EncodeFormat::Eac3 => "audio/eac3", + EncodeFormat::Ogg => "audio/ogg", } } @@ -309,6 +382,7 @@ impl EncodeFormat { EncodeFormat::Aac | EncodeFormat::Alac => Container::Mp4, EncodeFormat::Mp3 => Container::MpegAudio, EncodeFormat::Ac3 | EncodeFormat::Eac3 => Container::Ac3, + EncodeFormat::Ogg => Container::Ogg, } } @@ -322,6 +396,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => CodecId::Mp3, EncodeFormat::Ac3 => CodecId::Ac3, EncodeFormat::Eac3 => CodecId::Eac3, + EncodeFormat::Ogg => CodecId::Vorbis, } } @@ -335,10 +410,11 @@ impl EncodeFormat { EncodeFormat::Mp3 => "mp3-encode", EncodeFormat::Ac3 => "ac3-encode", EncodeFormat::Eac3 => "eac3-encode", + EncodeFormat::Ogg => "vorbis-encode", } } - /// Whether [`encode`] and [`FileEncoder`] write this format in this build (its + /// 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 { @@ -349,6 +425,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => cfg!(feature = "mp3-encode"), EncodeFormat::Ac3 => cfg!(feature = "ac3-encode"), EncodeFormat::Eac3 => cfg!(feature = "eac3-encode"), + EncodeFormat::Ogg => cfg!(feature = "vorbis-encode"), } } @@ -359,7 +436,7 @@ impl EncodeFormat { 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 => None, + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac | EncodeFormat::Alac | EncodeFormat::Ogg => None, } } @@ -369,7 +446,7 @@ impl EncodeFormat { pub fn max_channels(self) -> u16 { match self { EncodeFormat::Wav | EncodeFormat::Aiff => 32_767, - EncodeFormat::Flac | EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Eac3 => 8, + EncodeFormat::Flac | EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Eac3 | EncodeFormat::Ogg => 8, EncodeFormat::Ac3 => 6, EncodeFormat::Mp3 => 2, } @@ -386,6 +463,9 @@ impl EncodeFormat { // Apple's layout tags for 1–8 channels, surrounds as back speakers. EncodeFormat::Alac => &[&[0x4], &[0x3], &[0x7], &[0x107], &[0x37], &[0x3F], &[0x13F], &[0xFF]], EncodeFormat::Mp3 => &[&[0x4], &[0x3]], + // The Vorbis I §4.3.9 layouts for 1–8 channels (6.1 with a back centre and sides, 7.1 + // with sides and backs), written in Vorbis order. + EncodeFormat::Ogg => &[&[0x4], &[0x3], &[0x7], &[0x33], &[0x37], &[0x3F], &[0x70F], &[0x63F]], // 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. @@ -427,16 +507,16 @@ impl EncodeFormat { } } - /// Whether the format takes [`RateControl::Quality`]: AAC. The other lossy formats are - /// written at a constant bit rate only. + /// Whether the format takes [`RateControl::Quality`]: AAC and Ogg Vorbis. The other lossy + /// formats are written at a constant bit rate only. pub fn supports_quality(self) -> bool { - self == EncodeFormat::Aac + matches!(self, EncodeFormat::Aac | EncodeFormat::Ogg) } /// 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) + matches!(self, EncodeFormat::Aac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 | EncodeFormat::Ogg) } } @@ -449,10 +529,12 @@ pub enum RateControl { /// 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. + /// codes silence. Vorbis takes 64–500 kbit/s and writes the quality whose nominal rate that is + /// ([`quality_for_bitrate`]); its rate varies with the audio. 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. + /// needs. AAC and Vorbis (0.0 is Vorbis quality -1, 1.0 quality 10); values outside the range + /// are clamped, and NaN is an error. Quality(f32), } @@ -718,3 +800,10 @@ mod tests { assert!(matches!(e, AudioError::Encode(_)), "{e}"); } } + +/// DVD and Blu-ray LPCM packet decoding. +pub mod lpcm; + +/// Non-seeking canonical WAV streaming primitives. +#[cfg(feature = "pcm-encode")] +pub mod wav_stream; diff --git a/crates/audio/src/lpcm.rs b/crates/audio/src/lpcm.rs new file mode 100644 index 000000000..5ec13b35d --- /dev/null +++ b/crates/audio/src/lpcm.rs @@ -0,0 +1,118 @@ +//! DVD-Video and Blu-ray LPCM packet grammar and sample decoding. + +/// Blu-ray / AVCHD LPCM packet header (4 bytes before the samples). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BlurayLpcm { + /// Sample rate in hertz. + pub sample_rate: u32, + /// Number of decoded channels. + pub channels: usize, + /// Significant bits per sample. + pub bits: u32, +} + +/// Channels of each channel_assignment code (mono, stereo, 3/0, 2/1, 3/1, 2/2, 3/2, 3/2+LFE, +/// 3/4, 3/4+LFE). +const BD_LPCM_CHANNELS: [usize; 12] = [0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8]; + +/// Parse and validate the four-byte Blu-ray LPCM header. +pub fn bluray_lpcm_header(p: &[u8]) -> Option { + if p.len() < 4 { + return None; + } + let channels = *BD_LPCM_CHANNELS.get((p[2] >> 4) as usize).filter(|&&c| c > 0)?; + let sample_rate = match p[2] & 15 { + 1 => 48_000, + 4 => 96_000, + 5 => 192_000, + _ => return None, + }; + let bits = match p[3] >> 6 { + 1 => 16, + 2 => 20, + 3 => 24, + _ => return None, + }; + Some(BlurayLpcm { sample_rate, channels, bits }) +} + +/// Decode one Blu-ray LPCM packet (big-endian; channels padded to an even count; 20-bit +/// samples are stored in 24 bits). +pub fn decode_bluray_lpcm(p: &[u8]) -> Option>> { + let h = bluray_lpcm_header(p)?; + let coded = (h.channels + 1) & !1; + let bps = if h.bits == 16 { 2 } else { 3 }; + let data = &p[4..]; + let n = data.len() / (coded * bps); + let mut out = vec![Vec::with_capacity(n); h.channels]; + for k in 0..n { + for (c, o) in out.iter_mut().enumerate() { + let at = (k * coded + c) * bps; + let v = if bps == 2 { + i16::from_be_bytes([data[at], data[at + 1]]) as f32 / 32768.0 + } else { + (i32::from_be_bytes([data[at], data[at + 1], data[at + 2], 0]) >> 8) as f32 / 8_388_608.0 + }; + o.push(v); + } + } + Some(out) +} + +/// Bytes per two sample frames of DVD LPCM. The caller must bound `channels` to the DVD channel range. +pub fn dvd_lpcm_group_bytes(channels: usize, bits: u32) -> usize { + match bits { + 16 => 4 * channels, + 20 => 5 * channels, + _ => 6 * channels, + } +} + +/// Decode DVD-Video LPCM (big-endian). 16-bit samples are interleaved; 20- and 24-bit samples +/// come in groups of two frames: the upper 16 bits of all the group's samples, then their low +/// 4 / 8 bits. The caller must bound `channels` to the DVD channel range. +pub fn decode_dvd_lpcm(data: &[u8], channels: usize, bits: u32) -> Vec> { + let ch = channels.max(1); + let group = dvd_lpcm_group_bytes(ch, bits); + let groups = data.len() / group; + let mut out = vec![Vec::with_capacity(groups * 2); ch]; + for g in 0..groups { + let b = &data[g * group..(g + 1) * group]; + for f in 0..2 { + for (c, o) in out.iter_mut().enumerate() { + let k = f * ch + c; + let hi = i16::from_be_bytes([b[2 * k], b[2 * k + 1]]) as i32; + let v = match bits { + 16 => hi as f32 / 32768.0, + 20 => { + let nib = b[4 * ch + k / 2]; + let lo = if k.is_multiple_of(2) { nib >> 4 } else { nib & 15 } as i32; + ((hi << 4) | lo) as f32 / 524_288.0 + } + _ => ((hi << 8) | b[4 * ch + k] as i32) as f32 / 8_388_608.0, + }; + o.push(v); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn bluray_header_and_even_channel_padding() { + let packet = [0, 0, 0x31, 0x40, 0x40, 0, 0xc0, 0]; + assert_eq!(bluray_lpcm_header(&packet), Some(BlurayLpcm { sample_rate: 48_000, channels: 2, bits: 16 })); + assert_eq!(decode_bluray_lpcm(&packet), Some(vec![vec![0.5], vec![-0.5]])); + assert_eq!(decode_bluray_lpcm(&packet[..3]), None); + } + #[test] + fn dvd_lpcm_16_20_and_24_bit_groups() { + assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0], 1, 16), vec![vec![0.5, -0.5]]); + assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0, 0], 1, 20), vec![vec![0.5, -0.5]]); + assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0, 0, 0], 1, 24), vec![vec![0.5, -0.5]]); + assert_eq!(decode_dvd_lpcm(&[1, 2, 3], 1, 16), vec![Vec::::new()]); + } +} diff --git a/crates/audio/src/mp3/mod.rs b/crates/audio/src/mp3/mod.rs index d28607110..e273e903c 100644 --- a/crates/audio/src/mp3/mod.rs +++ b/crates/audio/src/mp3/mod.rs @@ -39,13 +39,13 @@ mod decoder; #[cfg(feature = "mp3-encode")] mod encoder; #[cfg(feature = "mp3-encode")] -mod filterbank; +pub(crate) mod filterbank; #[cfg(feature = "mp3-encode")] mod huffman; mod huffman_tables; #[cfg(feature = "mp3-encode")] mod quantize; -mod tables; +pub(crate) mod tables; #[cfg(feature = "mp3-decode")] pub use decoder::{Decoder, InfoTag}; diff --git a/crates/audio/src/mpa/encoder.rs b/crates/audio/src/mpa/encoder.rs new file mode 100644 index 000000000..000f86fe7 --- /dev/null +++ b/crates/audio/src/mpa/encoder.rs @@ -0,0 +1,493 @@ +//! The Layer II encoder; the module docs are in `mpa/mod.rs`. + +// Index loops follow the specification's pseudo-code (FilmCraft allows this lint workspace-wide). +#![allow(clippy::needless_range_loop)] + +use craft_media::bitstream::BitWriter; + +use super::tables::{self, AllocTable, SUBBANDS}; +use crate::mp3::filterbank::Polyphase; +use crate::mp3::tables::ath_db; + +/// Settings an [`Encoder`] refuses. +#[non_exhaustive] +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum EncodeError { + /// A sample rate outside [`SAMPLE_RATES`]. + #[error("MP2: unsupported sample rate {0} Hz (32, 44.1, 48 kHz, or 16, 22.05, 24 kHz)")] + SampleRate(u32), + /// A bit rate that is not one of [`bitrates`] for the sample rate and channel count. + #[error("MP2: unsupported bit rate {kbps} kbit/s at {rate} Hz with {channels} channel(s)")] + Bitrate { + /// The bit rate asked for, kbit/s. + kbps: u32, + /// The sample rate, Hz. + rate: u32, + /// The channel count. + channels: usize, + }, + /// More than two channels, or none. + #[error("MP2: unsupported channel count {0} (1 or 2)")] + Channels(usize), +} + +/// Result with this module's [`EncodeError`]. +pub type EncodeResult = std::result::Result; + +/// Encoder settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Config { + /// One of [`SAMPLE_RATES`]. + pub sample_rate: u32, + /// 1 or 2. Two channels are coded as stereo (`mode` 00), each with its own allocation. + pub channels: usize, + /// One of [`bitrates`] for the sample rate and channel count, kbit/s. + pub bitrate_kbps: u32, +} + +impl Config { + /// `channels` at `sample_rate`, constant `bitrate_kbps`. + pub fn cbr(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Config { + Config { sample_rate, channels, bitrate_kbps } + } +} + +/// The sample rates the encoder accepts. +pub const SAMPLE_RATES: [u32; 6] = [32_000, 44_100, 48_000, 16_000, 22_050, 24_000]; + +/// Samples by which a standard decoder's output lags the input: the polyphase analysis and +/// synthesis filters. +pub const DELAY: u32 = 481; + +/// Samples per channel in a frame. +pub const FRAME_SAMPLES: usize = 1152; + +/// Bit rates ISO/IEC 11172-3 Table 3-B.2 allows for a single channel at 32 / 44.1 / 48 kHz. +const MPEG1_MONO: [u32; 10] = [32, 48, 56, 64, 80, 96, 112, 128, 160, 192]; +/// Bit rates it allows for two channels. +const MPEG1_STEREO: [u32; 10] = [64, 96, 112, 128, 160, 192, 224, 256, 320, 384]; + +/// Whether `rate` is one of the MPEG-2 lower sampling frequencies; `None` if it is unsupported. +fn is_lsf(rate: u32) -> Option { + match rate { + 32_000 | 44_100 | 48_000 => Some(false), + 16_000 | 22_050 | 24_000 => Some(true), + _ => None, + } +} + +/// The bit rates (kbit/s) a Layer II stream can use at `sample_rate` with `channels` channels: +/// at 32 / 44.1 / 48 kHz the combinations ISO/IEC 11172-3 allows (32-192 for one channel, 64-384 +/// for two), at the lower sampling frequencies 8-160 for either. Empty for an unsupported rate. +pub fn bitrates(sample_rate: u32, channels: usize) -> &'static [u32] { + match is_lsf(sample_rate) { + Some(false) if channels == 1 => &MPEG1_MONO, + Some(false) => &MPEG1_STEREO, + Some(true) => &tables::BITRATES_LSF_L23[1..], + None => &[], + } +} + +/// The highest bit rate at `sample_rate` and `channels` not above `kbps` (the lowest one when +/// `kbps` is below all of them); `None` for an unsupported rate. +pub fn nearest_bitrate(sample_rate: u32, channels: usize, kbps: u32) -> Option { + let rates = bitrates(sample_rate, channels); + rates.iter().rev().find(|&&r| r <= kbps).or(rates.first()).copied() +} + +/// SNR-free noise model: the power of the error of rounding a value in ±1 to one of `steps` +/// levels spaced `2 / steps` apart, is `(2 / steps)² / 12`. +fn quantization_noise(steps: u16) -> f32 { + let d = 2.0 / f32::from(steps); + d * d / 12.0 +} + +/// Index of the scalefactor for a peak of `peak` (Table 3-B.1): the smallest scalefactor that is +/// at least `peak`, i.e. the largest index. +fn scalefactor_index(peak: f32) -> u32 { + if peak.is_nan() || peak <= 0.0 { + return 62; + } + let mut i = (3.0 * (1.0 - f64::from(peak).log2())).floor().clamp(0.0, 62.0) as u32; + while i > 0 && tables::scalefactor(i) < peak { + i -= 1; + } + while i < 62 && tables::scalefactor(i + 1) >= peak { + i += 1; + } + i +} + +/// Which scalefactors of a subband's three parts are sent (`scfsi`, §2.4.1.6) and what they are. +fn share(sf: [u32; 3]) -> (u32, [u32; 3]) { + let near = |a: u32, b: u32| a.abs_diff(b) <= 1; + let [a, b, c] = sf; + if near(a, b) && near(b, c) && near(a, c) { + let m = a.min(b).min(c); + (2, [m, m, m]) + } else if near(a, b) { + let m = a.min(b); + (1, [m, m, c]) + } else if near(b, c) { + let m = b.min(c); + (3, [a, m, m]) + } else { + (0, sf) + } +} + +/// Scalefactors sent for an `scfsi` class. +fn scalefactors_sent(scfsi: u32) -> u64 { + match scfsi { + 0 => 3, + 2 => 1, + _ => 2, + } +} + +/// Bits of the 12 granules of samples in a subband with `steps` quantization steps. +fn sample_bits(steps: u16) -> u64 { + 12 * match tables::grouping(steps) { + Some(bits) => u64::from(bits), + None => 3 * u64::from((u32::from(steps) + 1).trailing_zeros()), + } +} + +/// What the encoder decided for one channel of a frame. +#[derive(Clone)] +struct ChannelPlan { + /// The allocation value (index into the table's row) per subband. + alloc: [usize; SUBBANDS], + /// `scfsi` per subband. + scfsi: [u32; SUBBANDS], + /// The scalefactor index of each part of each subband, after sharing. + sf: [[u32; 3]; SUBBANDS], + /// Mean square of each subband's samples. + energy: [f32; SUBBANDS], +} + +/// A Layer II encoder. Feed planar `f32` samples (full scale ±1) to [`Encoder::encode`]; it +/// returns whole frames as they are completed. [`Encoder::flush`] pads the end with silence and +/// returns the rest. +/// +/// ``` +/// use craft_audio::mpa::encoder::{Config, DELAY, Encoder}; +/// +/// let left: Vec = (0..48_000).map(|i| (i as f32 * 0.05).sin() * 0.5).collect(); +/// let right = left.clone(); +/// let mut enc = Encoder::new(Config::cbr(48_000, 2, 192))?; +/// let mut mp2 = enc.encode(&[&left, &right]); // whole frames as they complete +/// mp2.extend(enc.flush()); // pads with silence to the last input sample +/// assert_eq!(mp2.len() % 576, 0); // 192 kbit/s at 48 kHz: 576 bytes per frame +/// assert_eq!(DELAY, 481); // a decoder's output lags the input by this many samples +/// # Ok::<(), craft_audio::mpa::encoder::EncodeError>(()) +/// ``` +pub struct Encoder { + cfg: Config, + lsf: bool, + sr_index: u32, + br_index: u32, + table: AllocTable, + sblimit: usize, + /// The masking offset floor per subband (power), from the threshold in quiet. + ath: [f32; SUBBANDS], + poly: Vec, + /// Buffered input per channel, and how much of it is consumed. + input: Vec>, + consumed: usize, + /// Remainder accumulator for the padding slot (44.1 / 22.05 kHz). + pad_acc: u64, + samples_in: u64, + frames: u64, +} + +impl Encoder { + /// An encoder for `cfg`, or the setting it cannot carry. + pub fn new(cfg: Config) -> EncodeResult { + let lsf = is_lsf(cfg.sample_rate).ok_or(EncodeError::SampleRate(cfg.sample_rate))?; + if !(1..=2).contains(&cfg.channels) { + return Err(EncodeError::Channels(cfg.channels)); + } + let bad = EncodeError::Bitrate { kbps: cfg.bitrate_kbps, rate: cfg.sample_rate, channels: cfg.channels }; + if !bitrates(cfg.sample_rate, cfg.channels).contains(&cfg.bitrate_kbps) { + return Err(bad); + } + let (rates, bitrate_table): (&[u32; 3], &[u32; 15]) = + if lsf { (&[22_050, 24_000, 16_000], &tables::BITRATES_LSF_L23) } else { (&tables::SAMPLE_RATES, &tables::BITRATES_MPEG1_L2) }; + let sr_index = rates.iter().position(|&r| r == cfg.sample_rate).ok_or(EncodeError::SampleRate(cfg.sample_rate))?; + let br_index = bitrate_table.iter().position(|&b| b == cfg.bitrate_kbps).ok_or(bad)?; + let per_channel = cfg.bitrate_kbps / cfg.channels as u32; + let table = AllocTable::select(lsf, cfg.sample_rate, per_channel); + let sblimit = table.sblimit().min(SUBBANDS); + let mut ath = [0f32; SUBBANDS]; + for (sb, a) in ath.iter_mut().enumerate() { + let centre = (sb as f64 + 0.5) * f64::from(cfg.sample_rate) / 64.0; + // a full-scale sine has a mean square of 1/2 and plays back at about 96 dB SPL + *a = (0.5 * 10f64.powf((ath_db(centre) - 96.0) / 10.0)) as f32; + } + Ok(Encoder { + cfg, + lsf, + sr_index: sr_index as u32, + br_index: br_index as u32, + table, + sblimit, + ath, + poly: vec![Polyphase::new(); cfg.channels], + input: vec![Vec::new(); cfg.channels], + consumed: 0, + pad_acc: 0, + samples_in: 0, + frames: 0, + }) + } + + /// The settings. + pub fn config(&self) -> &Config { + &self.cfg + } + + /// Samples per channel in a frame: 1152. + pub fn frame_samples(&self) -> usize { + FRAME_SAMPLES + } + + /// Samples by which a standard decoder's output lags the input. + pub fn delay(&self) -> u32 { + DELAY + } + + /// Frames written so far. + pub fn frames(&self) -> u64 { + self.frames + } + + /// Encode planar samples (one slice per channel; a missing channel is silence, extra ones + /// are ignored, every channel takes the first channel's length). Returns the completed frames. + pub fn encode(&mut self, planar: &[&[f32]]) -> Vec { + let n = planar.first().map_or(0, |p| p.len()); + for (c, buf) in self.input.iter_mut().enumerate() { + let src = planar.get(c).copied().unwrap_or(&[]); + buf.extend((0..n).map(|i| src.get(i).copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-4.0, 4.0))); + } + self.samples_in = self.samples_in.saturating_add(n as u64); + let mut out = Vec::new(); + self.drain(&mut out); + out + } + + /// Encode the buffered rest padded with silence, plus enough silence that a decoder outputs + /// every input sample, and return the remaining frames. + pub fn flush(&mut self) -> Vec { + let fs = FRAME_SAMPLES as u64; + let needed = if self.samples_in == 0 { self.frames } else { self.samples_in.saturating_add(u64::from(DELAY)).div_ceil(fs) }; + let have = self.input.first().map_or(0, |b| b.len().saturating_sub(self.consumed)); + let want = (needed.saturating_sub(self.frames) as usize).saturating_mul(FRAME_SAMPLES); + if want > have { + for buf in &mut self.input { + buf.resize(self.consumed + want, 0.0); + } + } + let mut out = Vec::new(); + self.drain(&mut out); + self.input.iter_mut().for_each(Vec::clear); + self.consumed = 0; + out + } + + /// Encode every whole frame of buffered input. + fn drain(&mut self, out: &mut Vec) { + while self.input.first().is_some_and(|b| b.len() - self.consumed >= FRAME_SAMPLES) { + let mut sub = vec![[[0f32; SUBBANDS]; 36]; self.cfg.channels]; + for (ch, slots) in sub.iter_mut().enumerate() { + let (Some(buf), Some(poly)) = (self.input.get(ch), self.poly.get_mut(ch)) else { continue }; + let frame = buf.get(self.consumed..self.consumed + FRAME_SAMPLES).unwrap_or(&[]); + for (slot, chunk) in slots.iter_mut().zip(frame.as_chunks::<32>().0) { + poly.filter(chunk, slot); + } + } + self.consumed += FRAME_SAMPLES; + self.write_frame(&sub, out); + self.frames += 1; + } + // keep the buffer small + if self.consumed >= 1 << 16 { + for buf in &mut self.input { + buf.drain(..self.consumed); + } + self.consumed = 0; + } + } + + /// The scalefactors and energies of a channel's 36 time slots. + fn analyse(&self, slots: &[[f32; SUBBANDS]; 36]) -> ChannelPlan { + let mut plan = ChannelPlan { alloc: [0; SUBBANDS], scfsi: [0; SUBBANDS], sf: [[62; 3]; SUBBANDS], energy: [0.0; SUBBANDS] }; + for sb in 0..self.sblimit { + let mut sf = [62u32; 3]; + for (part, s) in sf.iter_mut().enumerate() { + let peak = slots[12 * part..12 * part + 12].iter().map(|slot| slot[sb].abs()).fold(0f32, f32::max); + *s = scalefactor_index(peak); + } + (plan.scfsi[sb], plan.sf[sb]) = share(sf); + plan.energy[sb] = slots.iter().map(|slot| slot[sb] * slot[sb]).sum::() / 36.0; + } + plan + } + + /// Choose the allocation of every subband of every channel with the bits the frame has. + fn allocate(&self, plans: &mut [ChannelPlan], mut bits_left: i64) { + let nch = plans.len(); + // power the quantization noise of each subband may have before it is audible: a spread + // of the band energies, never below the threshold in quiet + let mut mask = vec![[0f32; SUBBANDS]; nch]; + for (m, plan) in mask.iter_mut().zip(plans.iter()) { + for sb in 0..self.sblimit { + let mut level = self.ath[sb]; + for j in 0..self.sblimit { + let atten_db = 14.0 + 20.0 * sb.abs_diff(j) as f32; + level = level.max(plan.energy[j] * 10f32.powf(-atten_db / 10.0)); + } + m[sb] = level; + } + } + // the fixed cost: every subband's allocation field + for sb in 0..self.sblimit { + bits_left -= (nch * self.table.row(sb).len().trailing_zeros() as usize) as i64; + } + // the noise a subband has with allocation `a`: dropped, or the mean over its parts + let noise = |plan: &ChannelPlan, sb: usize, a: usize| -> f32 { + let row = self.table.row(sb); + let steps = row.get(a).copied().unwrap_or(0); + if steps == 0 { + return plan.energy[sb]; + } + let mean_sf2 = plan.sf[sb].iter().map(|&i| tables::scalefactor(i).powi(2)).sum::() / 3.0; + (quantization_noise(steps) * mean_sf2).min(plan.energy[sb]) + }; + let cost = |plan: &ChannelPlan, sb: usize, a: usize| -> i64 { + let row = self.table.row(sb); + let step = |a: usize| row.get(a).copied().unwrap_or(0); + let (from, to) = (step(a), step(a + 1)); + let mut bits = sample_bits(to) as i64 - if from == 0 { 0 } else { sample_bits(from) as i64 }; + if from == 0 { + bits += 2 + 6 * scalefactors_sent(plan.scfsi[sb]) as i64; + } + bits + }; + let mut blocked = vec![[false; SUBBANDS]; nch]; + loop { + // the subband whose noise is furthest above its mask + let mut best: Option<(usize, usize, f32)> = None; + for (ch, plan) in plans.iter().enumerate() { + for sb in 0..self.sblimit { + let a = plan.alloc[sb]; + if a + 1 >= self.table.row(sb).len() || blocked[ch][sb] || plan.energy[sb] <= 0.0 { + continue; + } + let ratio = noise(plan, sb, a) / mask[ch][sb].max(1e-20); + if ratio > 1e-3 && best.is_none_or(|(_, _, r)| ratio > r) { + best = Some((ch, sb, ratio)); + } + } + } + let Some((ch, sb, _)) = best else { break }; + let plan = &mut plans[ch]; + let c = cost(plan, sb, plan.alloc[sb]); + if c <= bits_left { + bits_left -= c; + plan.alloc[sb] += 1; + } else { + blocked[ch][sb] = true; + } + } + } + + fn write_frame(&mut self, sub: &[[[f32; SUBBANDS]; 36]], out: &mut Vec) { + let nch = self.cfg.channels; + // frame length: 144 bytes per kbit/s over the sampling rate, plus a slot when the + // remainder has added up to one + let rate = u64::from(self.cfg.sample_rate); + let exact = 144 * u64::from(self.cfg.bitrate_kbps) * 1000; + self.pad_acc += exact % rate; + let pad = self.pad_acc >= rate; + if pad { + self.pad_acc -= rate; + } + let frame_bytes = (exact / rate) as usize + usize::from(pad); + + let mut plans: Vec = sub.iter().map(|s| self.analyse(s)).collect(); + self.allocate(&mut plans, frame_bytes as i64 * 8 - 32); + + let mut w = BitWriter::new(); + w.write_bits(0xFFF, 12); + w.write_bits(u32::from(!self.lsf), 1); + w.write_bits(0b10, 2); // Layer II + w.write_bits(1, 1); // no CRC + w.write_bits(self.br_index, 4); + w.write_bits(self.sr_index, 2); + w.write_bits(u32::from(pad), 1); + w.write_bits(0, 1); // private + w.write_bits(if nch == 1 { 3 } else { 0 }, 2); // mono or stereo + w.write_bits(0, 2); // mode extension + w.write_bits(0, 1); // copyright + w.write_bits(1, 1); // original + w.write_bits(0, 2); // emphasis + for sb in 0..self.sblimit { + let nbal = self.table.row(sb).len().trailing_zeros(); + for plan in &plans { + w.write_bits(plan.alloc[sb] as u32, nbal); + } + } + for sb in 0..self.sblimit { + for plan in &plans { + if plan.alloc[sb] != 0 { + w.write_bits(plan.scfsi[sb], 2); + } + } + } + for sb in 0..self.sblimit { + for plan in &plans { + if plan.alloc[sb] == 0 { + continue; + } + let [a, b, c] = plan.sf[sb]; + match plan.scfsi[sb] { + 0 => [a, b, c].iter().for_each(|&s| w.write_bits(s, 6)), + 1 => [a, c].iter().for_each(|&s| w.write_bits(s, 6)), + 2 => w.write_bits(a, 6), + _ => [a, b].iter().for_each(|&s| w.write_bits(s, 6)), + } + } + } + for gr in 0..12 { + let part = gr / 4; + for sb in 0..self.sblimit { + for (ch, plan) in plans.iter().enumerate() { + let a = plan.alloc[sb]; + let steps = self.table.row(sb).get(a).copied().unwrap_or(0); + if steps == 0 { + continue; + } + let scale = tables::scalefactor(plan.sf[sb][part]); + let n = u32::from(steps); + let code = |k: usize| -> u32 { + let x = (sub[ch][3 * gr + k][sb] / scale).clamp(-1.0, 1.0); + // the reconstruction points are (2v + 1 - n) / n + ((x * n as f32 + n as f32 - 1.0) / 2.0).round().clamp(0.0, (n - 1) as f32) as u32 + }; + let v = [code(0), code(1), code(2)]; + match tables::grouping(steps) { + Some(bits) => w.write_bits(v[0] + n * v[1] + n * n * v[2], bits), + None => { + let nb = (n + 1).trailing_zeros(); + v.iter().for_each(|&x| w.write_bits(x, nb)); + } + } + } + } + } + let mut bytes = w.finish(); + bytes.resize(frame_bytes, 0); + out.extend_from_slice(&bytes); + } +} diff --git a/crates/audio/src/mpa/mod.rs b/crates/audio/src/mpa/mod.rs index f1d5b6378..3db204176 100644 --- a/crates/audio/src/mpa/mod.rs +++ b/crates/audio/src/mpa/mod.rs @@ -13,12 +13,30 @@ //! format (bit rate index 0, whose frame length is only known from the next sync word) and the //! CRC (read, not checked, like most decoders). //! +//! # Encoder (feature `mpa-encode`) +//! +//! [`encoder::Encoder`] writes Layer II streams, written from ISO/IEC 11172-3 (§2.4.1.6 bit stream +//! syntax, Annex B tables, Annex C encoding process) and ISO/IEC 13818-3. +//! +//! - Constant bit rate: 32-192 kbit/s mono and 64-384 kbit/s stereo at 32 / 44.1 / 48 kHz (the +//! rate and mode pairs of Table 3-B.2), 8-160 kbit/s at 16 / 22.05 / 24 kHz. Mono, or stereo with +//! each channel allocated on its own (no joint stereo, no dual channel). +//! - The polyphase analysis filterbank of Annex C.1.3 (shared with the Layer III encoder), a +//! scalefactor per 12 samples with the `scfsi` sharing of §2.4.1.6, and a bit allocation chosen by +//! spending the frame's bits where the quantization noise is furthest above a simple masking +//! estimate (the band energies spread over the neighbouring subbands, never below the threshold +//! in quiet). It is not one of the psychoacoustic models of Annex D. +//! - Output: frames only, no CRC, no ID3 tag. Frames written one after another are a playable +//! `.mp2` file. A decoder's output lags the input by [`encoder::DELAY`] samples. +//! //! From FilmCraft's `filmcraft-mpa` (storytold/filmcraft@8fda2f2). Public items keep their names, so //! FilmCraft can re-export this module. // Index loops follow the specification's pseudo-code (FilmCraft allows this lint workspace-wide). #![allow(clippy::needless_range_loop)] +#[cfg(feature = "mpa-encode")] +pub mod encoder; pub(crate) mod tables; use craft_media::bitstream::BitReader; diff --git a/crates/audio/src/opus/decode/celt/mdct.rs b/crates/audio/src/opus/decode/celt/mdct.rs index b3bfcf0f7..7503d9ebe 100644 --- a/crates/audio/src/opus/decode/celt/mdct.rs +++ b/crates/audio/src/opus/decode/celt/mdct.rs @@ -4,141 +4,7 @@ //! producing the N/2 "folded" time samples; the window overlap region is then unfolded against the //! folded tail of the previous block, which the caller keeps in place in the output buffer. -#[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 } - } - #[inline] - fn sub(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. Radix 2, 3 and 4 use dedicated -/// butterflies; radix 5 uses a generic one. -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 tw = &self.twiddle; - match p { - 2 => { - for k in 0..m { - let a0 = out[k]; - let a1 = out[m + k].mul(tw[k * tw_stride]); - out[k] = a0.add(a1); - out[m + k] = a0.sub(a1); - } - } - 4 => { - for k in 0..m { - let t0 = out[k]; - let t1 = out[m + k].mul(tw[k * tw_stride]); - let t2 = out[2 * m + k].mul(tw[2 * k * tw_stride]); - let t3 = out[3 * m + k].mul(tw[3 * k * tw_stride]); - let s0 = t0.add(t2); - let d0 = t0.sub(t2); - let s1 = t1.add(t3); - let d1 = t1.sub(t3); - out[k] = s0.add(s1); - out[2 * m + k] = s0.sub(s1); - // -j * d1 = (d1.im, -d1.re) - out[m + k] = Cpx { re: d0.re + d1.im, im: d0.im - d1.re }; - out[3 * m + k] = Cpx { re: d0.re - d1.im, im: d0.im + d1.re }; - } - } - 3 => { - // sin(-2*pi/3) = -sqrt(3)/2 - let h = tw[self.n / 3].im; - for k in 0..m { - let t0 = out[k]; - let t1 = out[m + k].mul(tw[k * tw_stride]); - let t2 = out[2 * m + k].mul(tw[2 * k * tw_stride]); - let s = t1.add(t2); - let d = t1.sub(t2); - let a = Cpx { re: t0.re - 0.5 * s.re, im: t0.im - 0.5 * s.im }; - out[k] = t0.add(s); - // j * h * d = (-h * d.im, h * d.re) - out[m + k] = Cpx { re: a.re - h * d.im, im: a.im + h * d.re }; - out[2 * m + k] = Cpx { re: a.re + h * d.im, im: a.im - h * d.re }; - } - } - _ => { - // Radix 5 (at most once per transform): generic butterfly with the five roots of - // unity looked up once. - let mut w5 = [Cpx::default(); 5]; - for (q, w) in w5.iter_mut().enumerate() { - *w = tw[q * (self.n / p)]; - } - let mut t = [Cpx::default(); 5]; - for k in 0..m { - t[0] = out[k]; - for q in 1..p { - t[q] = out[q * m + k].mul(tw[q * k * tw_stride]); - } - for q2 in 0..p { - let mut acc = t[0]; - for q in 1..p { - acc = acc.add(t[q].mul(w5[(q * q2) % p])); - } - out[q2 * m + k] = acc; - } - } - } - } - } -} +use crate::opus::fft::{Cpx, Fft}; pub struct Imdct { /// Full MDCT length (2x the number of coefficients). diff --git a/crates/audio/src/opus/decode/celt/rate.rs b/crates/audio/src/opus/decode/celt/rate.rs index 782d68d5c..29e8566c1 100644 --- a/crates/audio/src/opus/decode/celt/rate.rs +++ b/crates/audio/src/opus/decode/celt/rate.rs @@ -1,272 +1,45 @@ //! Pulse cache and bit allocation (RFC 6716 §4.3.3, §4.3.4.1). -use super::tables::{ALLOC, EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS, OVERLAP}; +use super::tables::{EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS, OVERLAP}; use crate::opus::decode::range::{BITRES, RangeDecoder}; -const MAX_PSEUDO: i32 = 40; -const LOG_MAX_PSEUDO: i32 = 6; +pub use crate::opus::rate_common::get_pulses; +#[cfg(test)] +use crate::opus::rate_common::log2_frac; +#[cfg(test)] +pub use crate::opus::rate_common::pvq_v; 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 = crate::opus::decode::range::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) as u128 (saturating far above 2^32). -pub fn pvq_v(n: usize, k: usize) -> u128 { - // V(N,K) = V(N-1,K) + V(N,K-1) + V(N-1,K-1); computed row by row. - if k == 0 { - return 1; - } - if n == 0 { - return 0; - } - let mut row = vec![0u128; k + 1]; // V(0, k) - row[0] = 1; - for _ in 0..n { - let mut prev_diag = row[0]; // V(n-1, 0) - // V(n, 0) = 1 - for kk in 1..=k { - let up = row[kk]; // V(n-1, 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 shared by all CELT decoders. +/// Decoder mode: shared allocation tables and decoder-specific inverse transforms. pub struct Mode { - /// log2 of band width in 1/8 bits. - pub log_n: [i32; NB_EBANDS], - /// Index into `cache_bits` for `(LM+1)*NB_EBANDS + band` (-1 when unused). - pub cache_index: Vec, - /// `cache[0]` = max pseudo-pulses; `cache[k]` = bits(k) - 1 in 1/8 bits. - pub cache_bits: Vec, - /// Per-band maximum allocation: `[(2*LM + C-1)*NB_EBANDS + band]`. - pub caps: Vec, + core: crate::opus::rate_common::Mode, pub window: [f32; OVERLAP], pub mdct: [super::mdct::Imdct; MAX_LM + 1], } - 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(), + pub fn new() -> Self { + let mut mode = Self { + core: crate::opus::rate_common::Mode::new(), window: [0.0; OVERLAP], mdct: [super::mdct::Imdct::new(1920), super::mdct::Imdct::new(960), super::mdct::Imdct::new(480), super::mdct::Imdct::new(240)], }; - m.caps = compute_caps(&m); for i in 0..OVERLAP { let x = std::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / OVERLAP as f64; let s = x.sin(); - m.window[i] = (std::f64::consts::FRAC_PI_2 * s * s).sin() as f32; + mode.window[i] = (std::f64::consts::FRAC_PI_2 * s * s).sin() as f32; } - 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 + mode } } - -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(); // (N, K, offset) - 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; - // Reuse the entry of an earlier band with the same size. - '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; - } - } +impl std::ops::Deref for Mode { + type Target = crate::opus::rate_common::Mode; + fn deref(&self) -> &Self::Target { + &self.core } - 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) -} - -/// Bits (1/2^frac units, rounded up) needed for each K in `0..=maxk` for dimension `n`. -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) { - let v = pvq_v(n, k); - *o = log2_frac(v 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. @@ -296,89 +69,8 @@ pub struct AllocationInput<'a, 'd> { pub fn compute_allocation(input: AllocationInput<'_, '_>) -> Allocation { let AllocationInput { mode: m, start, end, offsets, cap, trim: alloc_trim, total, channels: c, lm, decoder: dec } = input; - 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; - } + let crate::opus::rate_common::Bracket { skip_start, bits1, bits2, thresh, total, skip_rsv, intensity_rsv, dual_stereo_rsv } = + crate::opus::rate_common::bracket(start, end, offsets, cap, alloc_trim, total, c, lm); interp_bits2pulses(InterpPulsesInput { mode: m, start, diff --git a/crates/audio/src/opus/decode/celt/tables.rs b/crates/audio/src/opus/decode/celt/tables.rs index f2381f714..b65d05c09 100644 --- a/crates/audio/src/opus/decode/celt/tables.rs +++ b/crates/audio/src/opus/decode/celt/tables.rs @@ -14,6 +14,7 @@ pub const MAX_LM: usize = 3; pub const PREEMPH: f32 = 0.850_006_1; /// Static allocation table (Table 57), indexed `[quality][band]`, in 1/32 bit per MDCT bin. +#[cfg(not(feature = "opus-encode"))] 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], @@ -38,6 +39,7 @@ pub const ALLOC: [[u8; NB_EBANDS]; 11] = transpose([ [0, 0, 0, 0, 0, 1, 1, 1, 1, 20, 104], ]); +#[cfg(not(feature = "opus-encode"))] const fn transpose(t: [[u8; 11]; NB_EBANDS]) -> [[u8; NB_EBANDS]; 11] { let mut out = [[0u8; NB_EBANDS]; 11]; let mut b = 0; diff --git a/crates/audio/src/opus/decode/silk/resampler.rs b/crates/audio/src/opus/decode/silk/resampler.rs index 0671778cc..7d3f803ef 100644 --- a/crates/audio/src/opus/decode/silk/resampler.rs +++ b/crates/audio/src/opus/decode/silk/resampler.rs @@ -4,25 +4,7 @@ //! RFC 6716 Table 54 (and the integer delays used when no rate conversion is needed), so that the //! SILK output lines up with the CELT layer in Hybrid mode. -/// Dot product with eight independent partial sums, so the additions pipeline and the loop -/// vectorises instead of waiting on one 4-cycle add chain. Rounds differently from a -/// sequential sum (the resampler is not normative). -#[inline] -fn dot8(a: &[f32], b: &[f32]) -> f32 { - let mut s = [0f32; 8]; - let (ca, ra) = a.as_chunks::<8>(); - let (cb, rb) = b.as_chunks::<8>(); - for (x, y) in ca.iter().zip(cb) { - for l in 0..8 { - s[l] += x[l] * y[l]; - } - } - let mut acc = ((s[0] + s[4]) + (s[1] + s[5])) + ((s[2] + s[6]) + (s[3] + s[7])); - for (x, y) in ra.iter().zip(rb) { - acc += x * y; - } - acc -} +use crate::opus::dot::dot8; #[derive(Clone)] pub struct Resampler { diff --git a/crates/audio/src/opus/dot.rs b/crates/audio/src/opus/dot.rs new file mode 100644 index 000000000..536209e0a --- /dev/null +++ b/crates/audio/src/opus/dot.rs @@ -0,0 +1,20 @@ +//! Shared fixed-order FIR dot product. + +/// Dot product with eight independent partial sums, which the compiler can vectorise (a single +/// running sum is bound by the latency of the float addition). The sums are combined pairwise. +#[inline] +pub(super) fn dot8(a: &[f32], b: &[f32]) -> f32 { + let mut s = [0f32; 8]; + let (ca, ra) = a.as_chunks::<8>(); + let (cb, rb) = b.as_chunks::<8>(); + for (x, y) in ca.iter().zip(cb) { + for l in 0..8 { + s[l] += x[l] * y[l]; + } + } + let mut acc = ((s[0] + s[4]) + (s[1] + s[5])) + ((s[2] + s[6]) + (s[3] + s[7])); + for (x, y) in ra.iter().zip(rb) { + acc += x * y; + } + acc +} diff --git a/crates/audio/src/opus/encoder/bands.rs b/crates/audio/src/opus/encoder/bands.rs index 604aab595..697332eb2 100644 --- a/crates/audio/src/opus/encoder/bands.rs +++ b/crates/audio/src/opus/encoder/bands.rs @@ -8,7 +8,8 @@ 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}; +use crate::opus::encoder::tables::EBANDS; +use crate::opus::encoder::{CeltFrame, rate::Allocation}; pub const SPREAD_NORMAL: usize = 2; @@ -55,7 +56,7 @@ fn exp_rotation1_inv(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) { if len <= stride { return; } - if len >= 2 * stride + 1 { + if len > 2 * stride { for i in 0..=len - 2 * stride - 1 { let x1 = x[i]; let x2 = x[i + stride]; @@ -96,12 +97,24 @@ pub fn exp_rotation_inv(x: &mut [f32], len: usize, k: usize, spread: usize) { } } +/// Relative slack for the pulse-candidate filter in [`pvq_search`]: far above the f32 rounding of +/// the filter score (a few 1e-7), far below the spread of real scores. +const PVQ_SCORE_SLACK: f32 = 1e-5; + /// 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(); + // `abs`, `dy` (2 y + 1, infinite in the padding) and the per-pass scores `score`, each padded to + // whole 8-lane chunks. + let np = n.next_multiple_of(8); + let mut buf = vec![0f32; 3 * np]; + let (abs, rest) = buf.split_at_mut(np); + let (dy, score) = rest.split_at_mut(np); + for (a, v) in abs.iter_mut().zip(x) { + *a = v.abs(); + } + let sum: f32 = abs[..n].iter().sum(); if !sum.is_finite() || sum <= 1e-15 { y[0] = k as i32; return; @@ -113,30 +126,69 @@ pub fn pvq_search(x: &[f32], k: usize, y: &mut [i32]) { // 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; + // Non-negative and at most k, so the truncating cast is the floor. + let p = (abs[j] * r) as i32; y[j] = p; placed += p as usize; xy += abs[j] * p as f32; yy += (p * p) as f32; } } + for j in 0..np { + dy[j] = if j < n { 2.0 * y[j] as f32 + 1.0 } else { f32::INFINITY }; + } while placed < k { + // Vectorisable scores (xy + |x_j|)^2 / (yy + 2 y_j + 1) and their maximum. + for ((sc, &a), &d) in score.iter_mut().zip(abs.iter()).zip(dy.iter()) { + let t = xy + a; + *sc = t * t / (yy + d); + } + let mut lane_max = [0f32; 8]; + for c in score.as_chunks::<8>().0 { + for i in 0..8 { + lane_max[i] = if c[i] > lane_max[i] { c[i] } else { lane_max[i] }; + } + } + let top = lane_max.iter().fold(0f32, |m, &v| if v > m { v } else { m }); + // The exact cross-multiplied test below, in index order with the first maximum winning, only + // matters for entries within rounding distance of the top score: every other entry is beaten + // by the top one whenever it is reached and never beats it afterwards. Running the test on + // those alone therefore picks the same pulse as running it on all of them. + let filter = top > 1e-30 && top.is_finite(); + let lo = top * (1.0 - PVQ_SCORE_SLACK); + // Usually exactly one entry qualifies; its index falls out of a lane-wise count. + let mut count = [0u32; 8]; + let mut index = [0u32; 8]; + for (ci, c) in score.as_chunks::<8>().0.iter().enumerate() { + for i in 0..8 { + let hit = u32::from(c[i] >= lo); + count[i] += hit; + index[i] += hit * (ci * 8 + i) as u32; + } + } 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; + if filter && count.iter().sum::() == 1 { + best = index.iter().sum::() as usize; + } else { + let mut best_num = -1f32; + let mut best_den = 1f32; + for j in 0..n { + if !filter || score[j] >= lo { + 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; + dy[best] = 2.0 * y[best] as f32 + 1.0; placed += 1; } for j in 0..n { @@ -146,25 +198,45 @@ pub fn pvq_search(x: &[f32], k: usize, y: &mut [i32]) { } } -/// 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); +/// Largest band width and pulse count the encoder codes (176 coefficients, `get_pulses(40)` = 128). +const PVQ_MAX_N: usize = 176; +const PVQ_MAX_K: usize = 128; + +/// Row-major `V(n, k)` for `n <= max_n`, `k <= max_k` with row stride `max_k + 1`, saturated at +/// `u32::MAX` (a codebook that large is never coded, see `rate::fits_in32`). +fn build_pvq_table(max_n: usize, max_k: usize) -> Vec { + let w = max_k + 1; + let mut v = vec![0u32; (max_n + 1) * w]; v[0] = 1; - for nn in 1..=n { + for nn in 1..=max_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); + for kk in 1..=max_k { + let sum = v[(nn - 1) * w + kk] as u64 + v[nn * w + kk - 1] as u64 + v[(nn - 1) * w + kk - 1] as u64; + v[nn * w + kk] = sum.min(u32::MAX as u64) as u32; } } - let total = v[n * w + k]; - let vv = |nn: usize, kx: usize| v[nn * w + kx]; + v +} + +fn pvq_table() -> &'static [u32] { + static TABLE: std::sync::OnceLock> = std::sync::OnceLock::new(); + TABLE.get_or_init(|| build_pvq_table(PVQ_MAX_N, PVQ_MAX_K)) +} + +/// 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) { + let n = y.len(); + // Shapes outside the coded range (never produced by the band layout) get a local table. + let local; + let (v, w) = if n <= PVQ_MAX_N && k <= PVQ_MAX_K { + (pvq_table(), PVQ_MAX_K + 1) + } else { + local = build_pvq_table(n, k); + (&local[..], k + 1) + }; + let row = |nn: usize| &v[nn * w..(nn + 1) * w]; + let total = row(n)[k] as u64; let mut index = 0u64; let mut kk = k; for j in 0..n { @@ -173,10 +245,11 @@ pub fn encode_pulses(y: &[i32], k: usize, enc: &mut RangeEncoder, v: &mut Vec { pub i: usize, pub spread: usize, pub remaining_bits: i32, - pvq_v: Vec, iy: Vec, tmp: Vec, } @@ -217,7 +289,7 @@ impl BandEnc<'_, '_> { 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) }; + 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; } @@ -287,36 +359,29 @@ impl BandEnc<'_, '_> { iy.clear(); iy.resize(n, 0); pvq_search(&tmp, k, &mut iy); - encode_pulses(&iy, k, self.enc, &mut self.pvq_v); + encode_pulses(&iy, k, self.enc); 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, -) { +/// Shape-coding controls, independent of the selected band allocation. +pub struct BandCoding { + pub spread: usize, + pub total_bits: i32, +} + +/// Codes all band shapes (`quant_all_bands`, encoder side, long blocks). `x` holds +/// `frame.channels` channels of `n_total` normalised MDCT coefficients each. +pub fn quant_all_bands(m: &Mode, frame: CeltFrame, x: &[f32], n_total: usize, allocation: &Allocation, coding: BandCoding, enc: &mut RangeEncoder) { + let CeltFrame { start, end, channels: c, lm } = frame; + let Allocation { pulses, dual_stereo, intensity, coded_bands, balance, .. } = allocation; + let (dual_stereo, intensity, coded_bands, mut balance) = (*dual_stereo, *intensity, *coded_bands, *balance); + let BandCoding { spread, total_bits } = coding; 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() }; + let mut ctx = BandEnc { m, enc, i: 0, spread, remaining_bits: 0, iy: Vec::new(), tmp: Vec::new() }; for i in start..end { ctx.i = i; let xo = mm * EBANDS[i] as usize; @@ -362,7 +427,7 @@ mod tests { x[i + stride] = c * x2 + s * x1; x[i] = c * x1 + ms * x2; } - if len >= 2 * stride + 1 { + if len > 2 * stride { for i in (0..=len - 2 * stride - 1).rev() { let x1 = x[i]; let x2 = x[i + stride]; @@ -466,12 +531,11 @@ mod tests { #[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); + encode_pulses(&y, k, &mut e); let buf = e.done(16); let mut d = RangeDecoder::new(&buf); assert_eq!(decode_pulses(n, k, &mut d), y, "n={n} k={k}"); @@ -480,6 +544,165 @@ mod tests { } } + /// The per-call table encoder this module used before the shared table. + fn encode_pulses_reference(y: &[i32], k: usize, enc: &mut RangeEncoder) { + let n = y.len(); + 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 { + 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; + 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; + } + if total >= 2 { + enc.uint(index as u32, total as u32); + } + } + + #[test] + fn pvq_table_encode_matches_per_call_table() { + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let mut next = move |m: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed % m + }; + let mut checked = 0; + for n in (1..=PVQ_MAX_N).step_by(5).chain([PVQ_MAX_N]) { + for k in (1..=PVQ_MAX_K).step_by(3).chain([PVQ_MAX_K]) { + if crate::opus::encoder::rate::pvq_v(n, k) > u32::MAX as u128 { + continue; + } + for _ in 0..4 { + let mut y = vec![0i32; n]; + for _ in 0..k { + let at = next(n as u64) as usize; + y[at] += if next(2) == 0 { 1 } else { -1 }; + } + // Opposite pulses cancel; top up so that sum |y| = k again. + let mut have: usize = y.iter().map(|v| v.unsigned_abs() as usize).sum(); + while have < k { + let at = next(n as u64) as usize; + y[at] += if y[at] < 0 { -1 } else { 1 }; + have += 1; + } + let (mut a, mut b) = (RangeEncoder::new(), RangeEncoder::new()); + encode_pulses(&y, k, &mut a); + encode_pulses_reference(&y, k, &mut b); + assert_eq!(a.done(16), b.done(16), "n={n} k={k}"); + checked += 1; + } + } + } + assert!(checked > 100, "{checked}"); + } + + /// The scalar greedy search the vectorised one replaced. + fn pvq_search_ref(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 { + 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]; + } + } + } + + #[test] + fn pvq_search_matches_scalar_reference() { + let mut state = 0x9e3779b97f4a7c15u64; + let mut rnd = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0 + }; + let mut a = vec![0i32; 200]; + let mut b = vec![0i32; 200]; + let mut cases = 0; + for round in 0..6000 { + let n = 1 + (round * 37 + (rnd().abs() * 176.0) as usize) % 176; + let k = 1 + (rnd().abs() * 127.0) as usize; + let scale = [1.0f32, 1e-9, 1e6, 3e-3][round % 4]; + let x: Vec = (0..n) + .map(|_| match round % 6 { + 0 => rnd(), + 1 => if rnd() > 0.8 { rnd() } else { 0.0 }, + 2 => (rnd() * 4.0).round() / 4.0, + 3 => if rnd() > 0.0 { 1.0 } else { -1.0 }, + 4 => rnd().powi(5), + _ => if rnd() > 0.95 { 3.0 * rnd() } else { 1e-4 * rnd() }, + } * scale) + .collect(); + pvq_search(&x, k, &mut a); + pvq_search_ref(&x, k, &mut b); + assert_eq!(a[..n], b[..n], "n={n} k={k} round={round}"); + cases += 1; + } + assert_eq!(cases, 6000); + } + #[test] fn pvq_search_finds_good_direction() { let x: Vec = (0..32).map(|i| ((i as f32) * 0.7).sin()).collect(); diff --git a/crates/audio/src/opus/encoder/energy.rs b/crates/audio/src/opus/encoder/energy.rs index 8d4f357d0..fb5cc5a4b 100644 --- a/crates/audio/src/opus/encoder/energy.rs +++ b/crates/audio/src/opus/encoder/energy.rs @@ -4,8 +4,9 @@ //! 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::CeltFrame; use crate::opus::encoder::range::RangeEncoder; -use crate::opus::encoder::rate::MAX_FINE_BITS; +use crate::opus::encoder::rate::{Allocation, 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; @@ -56,18 +57,15 @@ pub fn laplace_encode(enc: &mut RangeEncoder, value: i32, mut fs: u32, decay: u3 /// `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, + frame: CeltFrame, e: &[f32; 2 * NB_EBANDS], old_e: &mut [f32; 2 * NB_EBANDS], intra: bool, enc: &mut RangeEncoder, - c: usize, - lm: usize, budget: i32, ) { + let CeltFrame { start, end, channels: c, lm } = frame; 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]; @@ -112,14 +110,13 @@ pub fn quant_coarse_energy( /// `quant_fine_energy`: raw bits refining each band's quantised energy. pub fn quant_fine_energy( - start: usize, - end: usize, + frame: CeltFrame, e: &[f32; 2 * NB_EBANDS], old_e: &mut [f32; 2 * NB_EBANDS], fine_quant: &[i32; NB_EBANDS], enc: &mut RangeEncoder, - c: usize, ) { + let CeltFrame { start, end, channels: c, .. } = frame; for i in start..end { let fq = fine_quant[i]; if fq <= 0 { @@ -139,18 +136,16 @@ pub fn quant_fine_energy( /// `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, + frame: CeltFrame, e: &[f32; 2 * NB_EBANDS], old_e: &mut [f32; 2 * NB_EBANDS], - fine_quant: &[i32; NB_EBANDS], - fine_priority: &[i32; NB_EBANDS], + allocation: &Allocation, mut bits_left: i32, enc: &mut RangeEncoder, - c: usize, ) { + let CeltFrame { start, end, channels: c, .. } = frame; + let Allocation { fine_quant, fine_priority, .. } = allocation; for prio in 0..2 { let mut i = start; while i < end && bits_left >= c as i32 { diff --git a/crates/audio/src/opus/encoder/mdct.rs b/crates/audio/src/opus/encoder/mdct.rs index 6a42cce96..7cac21d93 100644 --- a/crates/audio/src/opus/encoder/mdct.rs +++ b/crates/audio/src/opus/encoder/mdct.rs @@ -9,84 +9,7 @@ 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; - } - } - } -} +use crate::opus::fft::{Cpx, Fft}; /// Forward MDCT producing `n` coefficients from a block of `n + OVERLAP` samples. pub struct Mdct { @@ -199,6 +122,31 @@ mod tests { .collect() } + #[test] + fn fft_matches_dft() { + // Every radix combination, including the 480-point size of the 20 ms frame. + for &n in &[2usize, 3, 4, 5, 6, 8, 12, 15, 16, 20, 24, 30, 48, 60, 120, 240, 480] { + let fft = Fft::new(n); + let x: Vec = (0..n).map(|i| Cpx { re: ((i * 37 % 101) as f32 - 50.0) / 7.0, im: ((i * 53 % 89) as f32 - 44.0) / 9.0 }).collect(); + let mut y = x.clone(); + fft.process(&mut y, &mut Vec::new()); + for k in 0..n { + let (mut re, mut im) = (0f64, 0f64); + for (j, v) in x.iter().enumerate() { + let ph = -2.0 * std::f64::consts::PI * ((j * k) % n) as f64 / n as f64; + re += v.re as f64 * ph.cos() - v.im as f64 * ph.sin(); + im += v.re as f64 * ph.sin() + v.im as f64 * ph.cos(); + } + assert!( + (y[k].re as f64 - re).abs() < 2e-3 && (y[k].im as f64 - im).abs() < 2e-3, + "n={n} k={k}: ({}, {}) vs ({re}, {im})", + y[k].re, + y[k].im + ); + } + } + } + #[test] fn matches_direct_formula() { for &n in &[240usize, 960] { diff --git a/crates/audio/src/opus/encoder/mod.rs b/crates/audio/src/opus/encoder/mod.rs index cbb0d7984..8a3df07f1 100644 --- a/crates/audio/src/opus/encoder/mod.rs +++ b/crates/audio/src/opus/encoder/mod.rs @@ -10,8 +10,9 @@ //! 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. +//! From EffectCraft's `effectcraft-opusenc` (storytold/effectcraft@c618429), with its later speed-ups +//! and CELT stage refactor up to storytold/effectcraft@d6c9ad66. Public items keep their names, so +//! EffectCraft can re-export this module. //! //! ``` //! # #[cfg(feature = "opus-encode")] { @@ -26,6 +27,7 @@ //! # } //! ``` +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] // The bit-allocation code mirrors the normative integer arithmetic; keep C-like shift expressions. #![allow(clippy::precedence, clippy::int_plus_one)] @@ -36,19 +38,28 @@ mod range; mod rate; mod resample; mod silk; -mod tables; +pub(super) mod tables; use std::sync::OnceLock; -use bands::{SPREAD_NORMAL, quant_all_bands}; +use bands::{BandCoding, 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 rate::{AllocationInput, 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}; +/// Band range, channel count and transform size shared by CELT coding stages. +#[derive(Clone, Copy)] +struct CeltFrame { + start: usize, + end: usize, + channels: usize, + lm: usize, +} + /// Samples per channel in one 20 ms frame at 48 kHz. const N: usize = 960; /// LM of a 20 ms frame (8 short blocks). @@ -338,7 +349,7 @@ impl Encoder { 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)); + packet.extend_from_slice(&self.encode_celt(RangeEncoder::new(), len, 0..NB_EBANDS, &log_e, silence)); } Mode::Silk => { let x = self.silk_input(pcm); @@ -368,7 +379,7 @@ impl Encoder { } 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)); + packet.extend_from_slice(&self.encode_celt(enc, len, HYBRID_START_BAND..end, &log_e, false)); } } Ok(packet) @@ -430,10 +441,18 @@ impl Encoder { /// 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 { + fn encode_celt( + &mut self, + mut enc: RangeEncoder, + len: usize, + bands: std::ops::Range, + log_e: &[f32; 2 * NB_EBANDS], + silence: bool, + ) -> Vec { let m = celt_mode(); let c = self.channels; + let frame = CeltFrame { start: bands.start, end: bands.end, channels: c, lm: LM }; + let CeltFrame { start, end, .. } = frame; 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]); @@ -462,10 +481,10 @@ impl Encoder { 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); + quant_coarse_energy(frame, log_e, &mut old_intra, true, &mut enc_intra, 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); + quant_coarse_energy(frame, log_e, &mut old_inter, false, &mut enc, total_bits_raw); if enc_intra.tell_frac() < enc.tell_frac() { enc = enc_intra; self.old_band_e = old_intra; @@ -473,14 +492,14 @@ impl Encoder { 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); + quant_coarse_energy(frame, log_e, &mut self.old_band_e, false, &mut enc, 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; + let tf_select_rsv = LM > 0 && tell + logp < budget; budget -= tf_select_rsv as i32; for _ in start..end { if tell + logp <= budget { @@ -512,27 +531,11 @@ impl Encoder { 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 alloc = compute_allocation(m, frame, AllocationInput { offsets: &offsets, cap: &cap, trim: alloc_trim, bits }, &mut enc); + quant_fine_energy(frame, log_e, &mut self.old_band_e, &alloc.fine_quant, &mut enc); + quant_all_bands(m, frame, &self.freq, N, &alloc, BandCoding { spread: SPREAD_NORMAL, total_bits: total_bits_raw << BITRES }, &mut enc); 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); + quant_energy_finalise(frame, log_e, &mut self.old_band_e, &alloc, bits_left, &mut enc); 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); diff --git a/crates/audio/src/opus/encoder/rate.rs b/crates/audio/src/opus/encoder/rate.rs index c360f9da7..3eb9575d4 100644 --- a/crates/audio/src/opus/encoder/rate.rs +++ b/crates/audio/src/opus/encoder/rate.rs @@ -4,254 +4,18 @@ //! 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}; +use crate::opus::encoder::CeltFrame; +use crate::opus::encoder::range::{BITRES, RangeEncoder}; +use crate::opus::encoder::tables::{EBANDS, LOG2_FRAC_TABLE, NB_EBANDS}; -const MAX_PSEUDO: i32 = 40; -const LOG_MAX_PSEUDO: i32 = 6; +#[cfg(test)] +pub use crate::opus::rate_common::pvq_v; +pub use crate::opus::rate_common::{Mode, get_pulses}; 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, @@ -263,125 +27,43 @@ pub struct Allocation { 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) +/// Per-band limits, boosts and available budget for the allocation search. +pub struct AllocationInput<'a> { + pub offsets: &'a [i32; NB_EBANDS], + pub cap: &'a [i32; NB_EBANDS], + pub trim: i32, + pub bits: i32, } -#[allow(clippy::too_many_arguments)] -fn interp_bits2pulses( - m: &Mode, - start: usize, - end: usize, +/// `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. +pub fn compute_allocation(m: &Mode, frame: CeltFrame, input: AllocationInput<'_>, enc: &mut RangeEncoder) -> Allocation { + let CeltFrame { start, end, channels: c, lm } = frame; + let AllocationInput { offsets, cap, trim: alloc_trim, bits: total } = input; + let crate::opus::rate_common::Bracket { skip_start, bits1, bits2, thresh, total, skip_rsv, intensity_rsv, dual_stereo_rsv } = + crate::opus::rate_common::bracket(start, end, offsets, cap, alloc_trim, total, c, lm); + let interpolation = + AllocationInterpolation { skip_start, bits1: &bits1, bits2: &bits2, thresh: &thresh, cap, total, skip_rsv, intensity_rsv, dual_stereo_rsv }; + interp_bits2pulses(m, frame, interpolation, enc) +} + +/// Bracketing allocation vectors and signalling reserves for the interpolation stage. +struct AllocationInterpolation<'a> { skip_start: usize, - bits1: &[i32; NB_EBANDS], - bits2: &[i32; NB_EBANDS], - thresh: &[i32; NB_EBANDS], - cap: &[i32; NB_EBANDS], - mut total: i32, + bits1: &'a [i32; NB_EBANDS], + bits2: &'a [i32; NB_EBANDS], + thresh: &'a [i32; NB_EBANDS], + cap: &'a [i32; NB_EBANDS], + total: i32, skip_rsv: i32, - mut intensity_rsv: i32, - mut dual_stereo_rsv: i32, - c: usize, - lm: usize, - enc: &mut RangeEncoder, -) -> Allocation { + intensity_rsv: i32, + dual_stereo_rsv: i32, +} + +fn interp_bits2pulses(m: &Mode, frame: CeltFrame, interpolation: AllocationInterpolation<'_>, enc: &mut RangeEncoder) -> Allocation { + let CeltFrame { start, end, channels: c, lm } = frame; + let AllocationInterpolation { skip_start, bits1, bits2, thresh, cap, mut total, skip_rsv, mut intensity_rsv, mut dual_stereo_rsv } = + interpolation; let ci = c as i32; let alloc_floor = ci << BITRES; let stereo = (c > 1) as i32; @@ -393,7 +75,7 @@ fn interp_bits2pulses( let mut psum = 0; let mut done = false; for j in (start..end).rev() { - let tmp = bits1[j] + (mid * bits2[j] >> ALLOC_STEPS); + let tmp = bits1[j] + ((mid * bits2[j]) >> ALLOC_STEPS); if tmp >= thresh[j] || done { done = true; psum += tmp.min(cap[j]); @@ -411,7 +93,7 @@ fn interp_bits2pulses( let mut psum = 0; let mut done = false; for j in (start..end).rev() { - let mut tmp = bits1[j] + (lo * bits2[j] >> ALLOC_STEPS); + 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 { @@ -500,9 +182,9 @@ fn interp_bits2pulses( if n == 2 { offset += (den << BITRES) >> 2; } - if bits[j] + offset < den * 2 << BITRES { + if bits[j] + offset < (den * 2) << BITRES { offset += nclogn >> 2; - } else if bits[j] + offset < den * 3 << BITRES { + } else if bits[j] + offset < (den * 3) << BITRES { offset += nclogn >> 3; } let mut eb = (bits[j] + offset + (den << (BITRES - 1))).max(0); @@ -513,7 +195,7 @@ fn interp_bits2pulses( 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; + bits[j] -= (ci * eb) << BITRES; } else { excess = (bit - (ci << BITRES)).max(0); bits[j] = bit - excess; @@ -523,7 +205,7 @@ fn interp_bits2pulses( 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; + let extra_bits = (extra_fine * ci) << BITRES; fine_priority[j] = (extra_bits >= excess - balance) as i32; excess -= extra_bits; } diff --git a/crates/audio/src/opus/encoder/resample.rs b/crates/audio/src/opus/encoder/resample.rs index 9045cb86d..a72589919 100644 --- a/crates/audio/src/opus/encoder/resample.rs +++ b/crates/audio/src/opus/encoder/resample.rs @@ -45,6 +45,8 @@ fn design(fc: f64, beta: f64, delay: usize) -> Vec { h.iter().map(|&v| v as f32).collect() } +use crate::opus::dot::dot8; + /// Decimates one channel of 48 kHz audio by 3, 4 or 6. #[derive(Clone)] pub struct Downsampler { @@ -77,7 +79,7 @@ impl Downsampler { 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()); + out.push(dot8(win, &self.h)); } let n = self.buf.len(); self.buf.copy_within(n - (taps - 1).., 0); @@ -97,6 +99,16 @@ mod tests { (x.iter().map(|&v| (v as f64).powi(2)).sum::() / x.len() as f64).sqrt() } + #[test] + fn dot8_matches_sequential_sum() { + for len in [0usize, 1, 7, 8, 9, 63, 167, 251] { + let a: Vec = (0..len).map(|i| ((i * 37 % 101) as f32 - 50.0) / 50.0).collect(); + let b: Vec = (0..len).map(|i| ((i * 53 % 89) as f32 - 44.0) / 44.0).collect(); + let exact: f64 = a.iter().zip(&b).map(|(&x, &y)| x as f64 * y as f64).sum(); + assert!((dot8(&a, &b) as f64 - exact).abs() < 1e-4, "len {len}"); + } + } + #[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)] { diff --git a/crates/audio/src/opus/encoder/silk/analysis.rs b/crates/audio/src/opus/encoder/silk/analysis.rs index 439331076..d80052046 100644 --- a/crates/audio/src/opus/encoder/silk/analysis.rs +++ b/crates/audio/src/opus/encoder/silk/analysis.rs @@ -69,28 +69,55 @@ pub fn levinson(r: &[f64], order: usize) -> Vec { } /// 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 { +/// `e^{jωd/2} P(e^{jω})`, with `cos_m(m)` giving `cos(m ω)`. +#[inline] +fn cos_series_with(p: &[f64], cos_m: impl Fn(usize) -> 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 += 2.0 * p[k] * cos_m(h - k); } s } +fn cos_series(p: &[f64], w: f64) -> f64 { + cos_series_with(p, |m| (m as f64 * w).cos()) +} + +/// Number of grid intervals the root search scans over `[0, π]`. +const GRID: usize = 1024; +/// Largest multiple of ω in the series (half the LPC order, at most 16 / 2). +const MAX_H: usize = 8; +/// Bisection steps per root: the bracket shrinks to 3e-9 rad, far below one Q15 NLSF step (9.6e-5 rad). +const BISECT_STEPS: usize = 20; + +/// `cos(m · π g / GRID)` for every grid point `g` and `m` in `0..=MAX_H`, computed with the same +/// expression as [`cos_series`], so the table values are bit-identical to calling `cos` there. +fn grid_cos() -> &'static [[f64; MAX_H + 1]] { + static TABLE: std::sync::OnceLock> = std::sync::OnceLock::new(); + TABLE.get_or_init(|| { + (0..=GRID) + .map(|g| { + let w = std::f64::consts::PI * g as f64 / GRID as f64; + std::array::from_fn(|m| (m as f64 * w).cos()) + }) + .collect() + }) +} + fn roots(p: &[f64], out: &mut Vec) { - const GRID: usize = 1024; + let grid = grid_cos(); + let at_grid = |g: usize| cos_series_with(p, |m| grid[g][m]); let mut w0 = 0.0; - let mut f0 = cos_series(p, w0); + let mut f0 = at_grid(0); for g in 1..=GRID { let w1 = std::f64::consts::PI * g as f64 / GRID as f64; - let f1 = cos_series(p, w1); + let f1 = at_grid(g); 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 { + for _ in 0..BISECT_STEPS { let mid = 0.5 * (lo + hi); let fm = cos_series(p, mid); if fm * flo <= 0.0 { @@ -111,6 +138,9 @@ fn roots(p: &[f64], out: &mut Vec) { /// when the root search fails (unstable or degenerate filter). pub fn a2nlsf(a: &[f64]) -> Option> { let d = a.len(); + if d > 2 * MAX_H { + return None; + } let mut c = vec![0f64; d + 2]; c[0] = 1.0; for k in 0..d { @@ -199,9 +229,20 @@ pub fn pitch_search(x: &[f32], start: usize, len: usize, fs_khz: usize) -> Pitch 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 }; + // The contour search revisits the same (subframe, lag) pairs for neighbouring base lags and + // codebook entries, so each correlation is computed once. + let span = (18 * fs - min_lag + 1) as usize; + let memo = std::cell::RefCell::new(vec![f64::NAN; 4 * span]); 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 slot = k * span + (l - min_lag) as usize; + let cached = memo.borrow()[slot]; + if !cached.is_nan() { + return cached; + } + let v = ncorr(x, start + k * sub..start + (k + 1) * sub, l as usize); + memo.borrow_mut()[slot] = v; + v }; let mut best = (f64::MIN, lag, 0usize); for l0 in (lag - 2).max(min_lag)..=(lag + 2).min(max_lag) { @@ -319,4 +360,59 @@ mod tests { } } } + + /// The root search as it was before the grid table: `cos` called for every evaluation. + fn roots_reference(p: &[f64], out: &mut Vec) { + 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..BISECT_STEPS { + 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; + } + } + + #[test] + fn grid_table_roots_are_bit_identical_to_direct_cos() { + let mut seed = 7u64; + let mut rnd = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 + }; + let mut found = 0; + for len in [11usize, 17] { + for _ in 0..300 { + let mut p = vec![0f64; len]; + for k in 0..len / 2 + 1 { + p[k] = rnd(); + p[len - 1 - k] = p[k]; + } + let (mut a, mut b) = (Vec::new(), Vec::new()); + roots(&p, &mut a); + roots_reference(&p, &mut b); + assert_eq!(a.iter().map(|v| v.to_bits()).collect::>(), b.iter().map(|v| v.to_bits()).collect::>()); + found += a.len(); + } + } + assert!(found > 1000, "{found}"); + } } diff --git a/crates/audio/src/opus/encoder/silk/mod.rs b/crates/audio/src/opus/encoder/silk/mod.rs index d82e537e0..0fda4f59a 100644 --- a/crates/audio/src/opus/encoder/silk/mod.rs +++ b/crates/audio/src/opus/encoder/silk/mod.rs @@ -129,6 +129,48 @@ struct Coded { pulses: Vec, } +/// Noise-feedback history (decoded − input), most recent first, as a double-length ring: each +/// sample is stored at `pos` and `pos + MAX_LPC_ORDER`, so `buf[pos..pos + MAX_LPC_ORDER]` is +/// always the contiguous window and a push costs two stores instead of a shift. +struct NfRing { + buf: [f64; 2 * MAX_LPC_ORDER], + /// Index of the most recent sample, always below `MAX_LPC_ORDER`. + pos: usize, +} + +impl NfRing { + fn new(hist: &[f64; MAX_LPC_ORDER]) -> Self { + let mut buf = [0.0; 2 * MAX_LPC_ORDER]; + buf[..MAX_LPC_ORDER].copy_from_slice(hist); + buf[MAX_LPC_ORDER..].copy_from_slice(hist); + NfRing { buf, pos: 0 } + } + + /// The history, most recent first. + fn window(&self) -> &[f64] { + self.buf.get(self.pos..self.pos + MAX_LPC_ORDER).unwrap_or(&[]) + } + + /// Makes `v` the most recent sample and drops the oldest. + fn push(&mut self, v: f64) { + self.pos = self.pos.checked_sub(1).unwrap_or(MAX_LPC_ORDER - 1); + for i in [self.pos, self.pos + MAX_LPC_ORDER] { + if let Some(slot) = self.buf.get_mut(i) { + *slot = v; + } + } + } + + /// The history as a plain array, most recent first. + fn to_array(&self) -> [f64; MAX_LPC_ORDER] { + let mut out = [0.0; MAX_LPC_ORDER]; + for (o, v) in out.iter_mut().zip(self.window()) { + *o = *v; + } + out + } +} + #[derive(Clone)] struct Channel { fs_khz: usize, @@ -237,7 +279,7 @@ impl Channel { let sub = self.sub; let order = self.order; let st = &mut self.dec; - let nf = &mut self.nf; + let mut ring = NfRing::new(&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]; @@ -355,7 +397,7 @@ impl Channel { } 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 fb: f64 = nf_c.iter().zip(ring.window()).take(order).map(|(c, e)| c * e).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; @@ -394,11 +436,11 @@ impl Channel { 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; + ring.push(xq[n] as f64 - x[n] as f64); } s_lpc.copy_within(sub..sub + MAX_LPC_ORDER, 0); } + self.nf = ring.to_array(); 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) @@ -485,6 +527,14 @@ struct Prep { pred_q13: [i32; 2], } +/// One rate-loop trial: the frame coded at gain offset `offset`. +struct Trial { + offset: f64, + bits: i32, + state: SilkEncoder, + coder: RangeEncoder, +} + /// SILK encoder for one mono or stereo (mid/side) stream. #[derive(Clone)] pub struct SilkEncoder { @@ -635,11 +685,20 @@ impl SilkEncoder { 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 + // Every trial codes the frame into a clone of the encoder and the range coder. The result + // is kept per offset: the hard-limit check below hits the memo for the chosen offset, and + // the final step adopts that trial instead of coding the frame once more. + let mut trials: Vec = Vec::new(); + let mut trial = |s: &Self, o: f64| -> i32 { + if let Some(t) = trials.iter().find(|t| t.offset == o) { + return t.bits; + } + let mut state = s.clone(); + let mut coder = enc.clone(); + state.code(&prep, o, &mut coder); + let bits = coder.tell() - start_bits; + trials.push(Trial { offset: o, bits, state, coder }); + bits }; // Bisection on the gain offset: the smallest offset (finest quantisation) within budget. let target = target_bits.min(max_bits as f64); @@ -701,8 +760,20 @@ impl SilkEncoder { while trial(self, o) > max_bits && o < 12.0 { o += 1.0; } + match trials.iter().position(|t| t.offset == o) { + Some(i) => { + let t = trials.swap_remove(i); + *self = t.state; + *enc = t.coder; + } + None => self.code(&prep, o, enc), + } + self.end_frame(&prep, o); + } + + /// Advances the input history and the frame counter after frame `prep` was coded at `o`. + fn end_frame(&mut self, prep: &Prep, o: f64) { self.last_offset = o; - self.code(&prep, o, enc); for ch in 0..self.channels { self.ch[ch].push_history(&prep.x[ch]); } @@ -712,3 +783,80 @@ impl SilkEncoder { self.frame += 1; } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Deterministic speech-like test input: two harmonics with a moving pitch, a syllable + /// envelope, noise and short silences, at the internal rate and 16-bit scale. + fn signal(len: usize, fs_khz: usize, seed: u32) -> Vec { + let mut s = seed; + let fs = (fs_khz * 1000) as f64; + (0..len) + .map(|i| { + 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; + let t = i as f64 / fs; + let f0 = 140.0 + 40.0 * (t * 1.3).sin(); + let env = ((t * 4.0).sin().max(0.0)).powf(0.7); + let voiced = (std::f64::consts::TAU * f0 * t).sin() + 0.5 * (std::f64::consts::TAU * 2.0 * f0 * t).sin(); + (8000.0 * env * voiced + 600.0 * noise) as f32 + }) + .collect() + } + + #[test] + fn nf_ring_matches_a_shifted_history() { + let mut hist = [0f64; MAX_LPC_ORDER]; + for (i, h) in hist.iter_mut().enumerate() { + *h = i as f64 * 0.5 - 3.0; + } + let mut ring = NfRing::new(&hist); + assert_eq!(ring.window(), &hist[..]); + for n in 0..100 { + let v = (n as f64 * 0.37).sin() * 100.0; + hist.copy_within(0..MAX_LPC_ORDER - 1, 1); + hist[0] = v; + ring.push(v); + assert_eq!(ring.window(), &hist[..], "after push {n}"); + } + assert_eq!(ring.to_array(), hist); + } + + /// The rate loop adopts the memoised trial for the chosen offset. A second encoder that codes + /// every frame afresh at that offset (what the loop did before the memo) must produce the + /// same bytes, frame after frame, so the adopted encoder and range-coder states are exact. + #[test] + fn adopting_the_memoised_trial_equals_coding_the_frame_again() { + for (fs_khz, channels, target_bits, max_bits) in + [(8, 1, 200.0, 1000), (12, 1, 320.0, 1000), (16, 1, 480.0, 1000), (16, 2, 640.0, 1000), (16, 1, 900.0, 400), (8, 2, 120.0, 160)] + { + let mut memo = SilkEncoder::new(fs_khz, channels); + let mut fresh = memo.clone(); + let l = memo.frame_len(); + let frames = 40; + let left = signal(l * frames, fs_khz, 7); + let right: Vec = signal(l * frames + 37, fs_khz, 11)[37..].iter().map(|v| v * 0.6).collect(); + for f in 0..frames { + let mut input = vec![left[f * l..(f + 1) * l].to_vec()]; + if channels == 2 { + input.push(right[f * l..(f + 1) * l].to_vec()); + } + let mut enc = RangeEncoder::new(); + memo.encode(&input, target_bits, max_bits, &mut enc); + let o = memo.last_offset; + let prep = fresh.prepare(&input); + let mut enc_fresh = RangeEncoder::new(); + fresh.code(&prep, o, &mut enc_fresh); + fresh.end_frame(&prep, o); + assert_eq!(enc.tell(), enc_fresh.tell(), "{fs_khz} kHz {channels} ch frame {f}"); + assert_eq!(enc.done(1275), enc_fresh.done(1275), "{fs_khz} kHz {channels} ch frame {f}"); + for c in 0..channels { + assert_eq!(memo.ch[c].nf, fresh.ch[c].nf, "noise feedback, channel {c}, frame {f}"); + assert_eq!(memo.ch[c].dec.s_lpc_q14, fresh.ch[c].dec.s_lpc_q14, "LPC state, channel {c}, frame {f}"); + } + } + } + } +} diff --git a/crates/audio/src/opus/fft.rs b/crates/audio/src/opus/fft.rs new file mode 100644 index 000000000..300c78d48 --- /dev/null +++ b/crates/audio/src/opus/fft.rs @@ -0,0 +1,130 @@ +//! Shared CELT forward complex FFT. + +#[derive(Clone, Copy, Default, Debug)] +pub struct Cpx { + pub re: f32, + pub im: f32, +} + +impl Cpx { + #[inline] + pub(crate) 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] + pub(crate) fn add(self, o: Cpx) -> Cpx { + Cpx { re: self.re + o.re, im: self.im + o.im } + } + #[inline] + pub(crate) fn sub(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 { + pub(crate) n: usize, + pub(crate) factors: Vec, + pub(crate) 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); + } + } + // The twiddle index q * k * tw_stride is always below n, so no modulo is needed. + let tw = &self.twiddle; + match p { + 2 => { + for k in 0..m { + let a0 = out[k]; + let a1 = out[m + k].mul(tw[k * tw_stride]); + out[k] = a0.add(a1); + out[m + k] = a0.sub(a1); + } + } + 4 => { + for k in 0..m { + let t0 = out[k]; + let t1 = out[m + k].mul(tw[k * tw_stride]); + let t2 = out[2 * m + k].mul(tw[2 * k * tw_stride]); + let t3 = out[3 * m + k].mul(tw[3 * k * tw_stride]); + let (s0, d0) = (t0.add(t2), t0.sub(t2)); + let (s1, d1) = (t1.add(t3), t1.sub(t3)); + out[k] = s0.add(s1); + out[2 * m + k] = s0.sub(s1); + // The odd outputs combine d0 with -j * d1 = (d1.im, -d1.re) and its negative. + out[m + k] = Cpx { re: d0.re + d1.im, im: d0.im - d1.re }; + out[3 * m + k] = Cpx { re: d0.re - d1.im, im: d0.im + d1.re }; + } + } + 3 => { + // Imaginary part of exp(-2 pi i / 3) = -sqrt(3) / 2. + let h = tw[self.n / 3].im; + for k in 0..m { + let t0 = out[k]; + let t1 = out[m + k].mul(tw[k * tw_stride]); + let t2 = out[2 * m + k].mul(tw[2 * k * tw_stride]); + let (s, d) = (t1.add(t2), t1.sub(t2)); + let a = Cpx { re: t0.re - 0.5 * s.re, im: t0.im - 0.5 * s.im }; + out[k] = t0.add(s); + // j * h * d = (-h * d.im, h * d.re) + out[m + k] = Cpx { re: a.re - h * d.im, im: a.im + h * d.re }; + out[2 * m + k] = Cpx { re: a.re + h * d.im, im: a.im - h * d.re }; + } + } + _ => { + // Generic DFT butterfly (radix 5, once per transform). + let roots: [Cpx; 5] = std::array::from_fn(|q| if q < p { tw[q * (self.n / p)] } else { Cpx::default() }); + let mut t = [Cpx::default(); 5]; + for k in 0..m { + t[0] = out[k]; + for q in 1..p { + t[q] = out[q * m + k].mul(tw[q * k * tw_stride]); + } + for q2 in 0..p { + let mut acc = t[0]; + for q in 1..p { + acc = acc.add(t[q].mul(roots[(q * q2) % p])); + } + out[q2 * m + k] = acc; + } + } + } + } + } +} diff --git a/crates/audio/src/opus/mod.rs b/crates/audio/src/opus/mod.rs index b67e1ef3d..84e81ec8c 100644 --- a/crates/audio/src/opus/mod.rs +++ b/crates/audio/src/opus/mod.rs @@ -7,14 +7,18 @@ //! 20 ms, mono or stereo). From EffectCraft's `effectcraft-opusenc` (storytold/effectcraft@c618429). //! //! 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); +//! halves share the FFT, resampling dot product and CELT allocation preparation; range coders and +//! mode-specific MDCT processing remain separate. [`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 and // EffectCraft allow these lints workspace-wide). #![allow(clippy::needless_range_loop, clippy::too_many_arguments)] +mod dot; +mod fft; +mod rate_common; + #[cfg(feature = "opus-decode")] mod decode; #[cfg(feature = "opus-encode")] diff --git a/crates/audio/src/opus/rate_common.rs b/crates/audio/src/opus/rate_common.rs new file mode 100644 index 000000000..86b27c90a --- /dev/null +++ b/crates/audio/src/opus/rate_common.rs @@ -0,0 +1,362 @@ +//! CELT pulse cache and allocation caps shared by encoder and decoder. + +#[cfg(not(feature = "opus-encode"))] +use super::decode::celt::tables::{ALLOC, EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS}; +#[cfg(feature = "opus-encode")] +use super::encoder::tables::{ALLOC, EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS}; + +const BITRES: u32 = 3; +const MAX_PSEUDO: i32 = 40; +const LOG_MAX_PSEUDO: i32 = 6; +const MAX_FINE_BITS: i32 = 8; +const FINE_OFFSET: i32 = 21; +const QTHETA_OFFSET: i32 = 4; +const QTHETA_OFFSET_TWOPHASE: i32 = 16; +fn ilog(x: u32) -> i32 { + (32 - x.leading_zeros()) as i32 +} + +/// 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], + pub(crate) cache_index: Vec, + pub(crate) cache_bits: Vec, + pub(crate) 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 +} + +/// Shared allocation search before encoder/decoder signalling diverges. +pub struct Bracket { + pub skip_start: usize, + pub bits1: [i32; NB_EBANDS], + pub bits2: [i32; NB_EBANDS], + pub thresh: [i32; NB_EBANDS], + pub total: i32, + pub skip_rsv: i32, + pub intensity_rsv: i32, + pub dual_stereo_rsv: i32, +} + +pub fn bracket( + start: usize, + end: usize, + offsets: &[i32; NB_EBANDS], + cap: &[i32; NB_EBANDS], + alloc_trim: i32, + total: i32, + c: usize, + lm: usize, +) -> Bracket { + 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; + } + Bracket { skip_start, bits1, bits2, thresh, total, skip_rsv, intensity_rsv, dual_stereo_rsv } +} diff --git a/crates/audio/src/pcm_export.rs b/crates/audio/src/pcm_export.rs new file mode 100644 index 000000000..618ba281d --- /dev/null +++ b/crates/audio/src/pcm_export.rs @@ -0,0 +1,287 @@ +//! Audio-only files: WAV (RIFF, little-endian PCM; RF64 past 4 GiB) and AIFF (big-endian PCM), +//! 16, 24 or 32-bit integer or 32-bit float ([`SampleFormat`]), for streaming export. +//! Float WAV is `WAVE_FORMAT_IEEE_FLOAT` with a `fact` chunk; float AIFF is AIFF-C (`fl32`). +//! +//! The header is written first from the known length (`header`), then the samples in chunks +//! (`encode`) and the pad byte (`pad`), so an export streams to disk instead of building the +//! file in memory. + +/// PCM representation in an exported file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SampleFormat { + /// 16-bit signed integer. + Int16, + /// 24-bit signed integer. + Int24, + /// 32-bit signed integer. + Int32, + /// 32-bit IEEE float. + Float32, +} + +impl SampleFormat { + /// Bits per sample. + pub fn bits(self) -> u16 { + match self { + Self::Int16 => 16, + Self::Int24 => 24, + Self::Int32 | Self::Float32 => 32, + } + } + /// Bytes per sample. + pub fn bytes(self) -> usize { + usize::from(self.bits() / 8) + } + /// Whether this is a floating point format. + pub fn is_float(self) -> bool { + self == Self::Float32 + } + /// Clip and quantize one sample with symmetric integer full scale; NaN becomes silence. + pub fn quantise(self, s: f32) -> i32 { + let s = s.clamp(-1.0, 1.0); + match self { + Self::Int16 => (s * 32_767.0).round() as i32, + Self::Int24 => (s * 8_388_607.0).round() as i32, + Self::Int32 => (f64::from(s) * 2_147_483_647.0).round() as i32, + Self::Float32 => 0, + } + } + /// Sanitize a floating sample: NaN becomes silence, infinity becomes the largest finite value. + pub fn float(s: f32) -> f32 { + if s.is_nan() { 0.0 } else { s.clamp(f32::MIN, f32::MAX) } + } +} + +/// The container of an audio-only export. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PcmContainer { + /// RIFF/WAVE or RF64. + Wav, + /// AIFF or AIFF-C. + Aiff, +} + +/// Bytes of sample data for `frames` frames, or None when that does not fit 64 bits. +fn data_len(frames: u64, channels: u16, format: SampleFormat) -> Option { + frames.checked_mul(u64::from(channels))?.checked_mul(format.bytes() as u64) +} + +/// The pad byte after an odd-sized data chunk (RIFF and AIFF chunks are word-aligned). +pub fn pad(frames: u64, channels: u16, format: SampleFormat) -> &'static [u8] { + if data_len(frames, channels, format).is_some_and(|n| n & 1 == 1) { &[0] } else { &[] } +} + +/// `KSDATAFORMAT_SUBTYPE_PCM` / `_IEEE_FLOAT` after their first two bytes (the format tag). +const SUBTYPE_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]; + +/// AIFF-C format version 1 (`FVER`). +const AIFC_VERSION_1: u32 = 0xA280_5140; + +/// The AIFF-C compression name of `fl32`, as a Pascal string of even length. +const FL32_NAME: &[u8] = b"\x1532-bit floating point"; + +/// Everything before the samples of a file of `frames` frames. A WAV whose RIFF size would not +/// fit 32 bits (4 GiB: 24-bit 5.1 at 96 kHz after about 41 minutes) is written as RF64 (EBU Tech +/// 3306), with the 64-bit sizes in a `ds64` chunk. AIFF has no 64-bit form, so a longer AIFF is +/// an error naming WAV instead. +pub fn header(container: PcmContainer, channels: u16, sample_rate: u32, format: SampleFormat, frames: u64) -> Result, String> { + let too_long = || "the audio is too long to write".to_string(); + if channels == 0 { + return Err("audio needs at least one channel".into()); + } + if sample_rate == 0 { + return Err("audio needs a sample rate".into()); + } + let bits = format.bits(); + let bps = bits / 8; + let float = format.is_float(); + let data = data_len(frames, channels, format).ok_or_else(too_long)?; + let block_align = channels.checked_mul(bps).ok_or("too many audio channels")?; + match container { + PcmContainer::Wav => { + let byte_rate = + u32::try_from(u64::from(sample_rate) * u64::from(block_align)).map_err(|_| "the audio sample rate is too high".to_string())?; + let ext = channels > 2; + // plain PCM has no cbSize; IEEE float has an empty one + let fmt_len: u32 = if ext { + 40 + } else if float { + 18 + } else { + 16 + }; + // every format but integer PCM has a `fact` chunk (the frame count; RF64: in `ds64`) + let fact_len: u64 = if float { 12 } else { 0 }; + let padded = data.checked_add(data & 1).ok_or_else(too_long)?; + // "WAVE" + fmt chunk + fact chunk + data chunk header + samples + let riff = (4 + 8 + u64::from(fmt_len) + fact_len + 8).checked_add(padded).ok_or_else(too_long)?; + let rf64 = riff > u64::from(u32::MAX); + let mut v = Vec::with_capacity(100); + if rf64 { + const DS64: u64 = 8 + 28; + v.extend_from_slice(b"RF64"); + v.extend_from_slice(&u32::MAX.to_le_bytes()); + v.extend_from_slice(b"WAVEds64"); + v.extend_from_slice(&28u32.to_le_bytes()); + v.extend_from_slice(&riff.checked_add(DS64).ok_or_else(too_long)?.to_le_bytes()); + v.extend_from_slice(&data.to_le_bytes()); + v.extend_from_slice(&frames.to_le_bytes()); + v.extend_from_slice(&0u32.to_le_bytes()); // no table entries + } else { + v.extend_from_slice(b"RIFF"); + v.extend_from_slice(&(riff as u32).to_le_bytes()); + v.extend_from_slice(b"WAVE"); + } + let tag: u16 = if float { 3 } else { 1 }; + v.extend_from_slice(b"fmt "); + v.extend_from_slice(&fmt_len.to_le_bytes()); + v.extend_from_slice(&(if ext { 0xFFFE } else { tag }).to_le_bytes()); + v.extend_from_slice(&channels.to_le_bytes()); + v.extend_from_slice(&sample_rate.to_le_bytes()); + v.extend_from_slice(&byte_rate.to_le_bytes()); + v.extend_from_slice(&block_align.to_le_bytes()); + v.extend_from_slice(&bits.to_le_bytes()); + if ext { + // cbSize, valid bits, channel mask, KSDATAFORMAT_SUBTYPE_PCM / _IEEE_FLOAT + v.extend_from_slice(&22u16.to_le_bytes()); + v.extend_from_slice(&bits.to_le_bytes()); + let mask: u32 = if channels == 6 { 0x3F } else { 0 }; + v.extend_from_slice(&mask.to_le_bytes()); + v.extend_from_slice(&tag.to_le_bytes()); + v.extend_from_slice(&SUBTYPE_TAIL); + } else if float { + v.extend_from_slice(&0u16.to_le_bytes()); + } + if float { + v.extend_from_slice(b"fact"); + v.extend_from_slice(&4u32.to_le_bytes()); + v.extend_from_slice(&(if rf64 { u32::MAX } else { u32::try_from(frames).unwrap_or(u32::MAX) }).to_le_bytes()); + } + v.extend_from_slice(b"data"); + v.extend_from_slice(&(if rf64 { u32::MAX } else { data as u32 }).to_le_bytes()); + Ok(v) + } + PcmContainer::Aiff => { + let aiff_too_long = || "AIFF holds at most 4 GB of audio: export WAV, which has no such limit".to_string(); + let frames32 = u32::try_from(frames).map_err(|_| aiff_too_long())?; + // SSND: offset + block size + samples + let ssnd = u32::try_from(data.checked_add(8).ok_or_else(aiff_too_long)?).map_err(|_| aiff_too_long())?; + // floats need AIFF-C: a version chunk, and the compression type and name in COMM + let comm: u32 = if float { 18 + 4 + FL32_NAME.len() as u32 } else { 18 }; + let fver: u32 = if float { 8 + 4 } else { 0 }; + let form = (4u32 + fver + (8 + comm)) + .checked_add(8) + .and_then(|n| n.checked_add(ssnd)) + .and_then(|n| n.checked_add(ssnd & 1)) + .ok_or_else(aiff_too_long)?; + let mut v = Vec::with_capacity(90); + v.extend_from_slice(b"FORM"); + v.extend_from_slice(&form.to_be_bytes()); + if float { + v.extend_from_slice(b"AIFCFVER"); + v.extend_from_slice(&4u32.to_be_bytes()); + v.extend_from_slice(&AIFC_VERSION_1.to_be_bytes()); + } else { + v.extend_from_slice(b"AIFF"); + } + v.extend_from_slice(b"COMM"); + v.extend_from_slice(&comm.to_be_bytes()); + v.extend_from_slice(&channels.to_be_bytes()); + v.extend_from_slice(&frames32.to_be_bytes()); + v.extend_from_slice(&bits.to_be_bytes()); + v.extend_from_slice(&extended(sample_rate)); + if float { + v.extend_from_slice(b"fl32"); + v.extend_from_slice(FL32_NAME); + } + v.extend_from_slice(b"SSND"); + v.extend_from_slice(&ssnd.to_be_bytes()); + v.extend_from_slice(&0u32.to_be_bytes()); // offset + v.extend_from_slice(&0u32.to_be_bytes()); // block size + Ok(v) + } + } +} + +/// Append interleaved samples in `format` (little-endian for WAV, big-endian for AIFF). +pub fn encode(container: PcmContainer, interleaved: &[f32], format: SampleFormat, out: &mut Vec) { + let bps = format.bytes(); + out.reserve(interleaved.len().saturating_mul(bps)); + for &s in interleaved { + let q = if format.is_float() { SampleFormat::float(s).to_bits() as i32 } else { format.quantise(s) }; + match container { + PcmContainer::Wav => out.extend_from_slice(q.to_le_bytes().get(..bps).unwrap_or_default()), + PcmContainer::Aiff => out.extend_from_slice(q.to_be_bytes().get(4 - bps..).unwrap_or_default()), + } + } +} + +/// A whole file in memory (short audio; exports stream with [`header`] and [`encode`]). +fn write_whole(container: PcmContainer, interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result, String> { + let per_frame = usize::from(channels.max(1)); + if !interleaved.len().is_multiple_of(per_frame) { + return Err("the samples do not make whole frames".into()); + } + let frames = (interleaved.len() / per_frame) as u64; + let mut v = header(container, channels, sample_rate, format, frames)?; + encode(container, interleaved, format, &mut v); + v.extend_from_slice(pad(frames, channels, format)); + Ok(v) +} + +/// A RIFF/WAVE file of interleaved samples. More than two channels are written as +/// `WAVE_FORMAT_EXTENSIBLE` with the speaker mask of the layout (6 channels: L, R, C, LFE, Ls, Rs +/// = `0x3F`). +pub fn write_wav(interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result, String> { + write_whole(PcmContainer::Wav, interleaved, channels, sample_rate, format) +} + +/// IEEE 754 80-bit extended encoding of a sample rate (AIFF `COMM`). +pub fn extended(rate: u32) -> [u8; 10] { + let mut out = [0u8; 10]; + if rate == 0 { + return out; + } + let shift = rate.leading_zeros(); + let mant = (rate as u64) << (32 + shift); + let exp = 16383 + 31 - shift as u16; + out[..2].copy_from_slice(&exp.to_be_bytes()); + out[2..].copy_from_slice(&mant.to_be_bytes()); + out +} + +/// An AIFF file (`FORM`/`AIFF`, `COMM` + `SSND`; AIFF-C for floats) of interleaved samples. +pub fn write_aiff(interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result, String> { + write_whole(PcmContainer::Aiff, interleaved, channels, sample_rate, format) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn streaming_formats_preserve_samples_and_bounds() { + let samples = [1.0, -1.0, f32::NAN]; + let wav = write_wav(&samples, 1, 48_000, SampleFormat::Int24).unwrap(); + assert_eq!(&wav[..4], b"RIFF"); + assert_eq!(&wav[44..53], &[255, 255, 127, 1, 0, 128, 0, 0, 0]); + let h = header(PcmContainer::Wav, 6, 96_000, SampleFormat::Int24, 96_000 * 3600).unwrap(); + assert_eq!(&h[..4], b"RF64"); + assert!(header(PcmContainer::Aiff, 2, 48_000, SampleFormat::Int24, u64::MAX).is_err()); + let aiff = write_aiff(&[0.25, -3.0], 1, 44_100, SampleFormat::Float32).unwrap(); + assert_eq!(&aiff[8..12], b"AIFC"); + assert_eq!(&aiff[aiff.len() - 8..], [0.25f32.to_be_bytes(), (-3.0f32).to_be_bytes()].concat()); + } + + #[test] + fn zero_channels_rates_and_partial_frames_are_refused() { + for container in [PcmContainer::Wav, PcmContainer::Aiff] { + assert!(header(container, 0, 48_000, SampleFormat::Int16, 1).is_err()); + assert!(header(container, 1, 0, SampleFormat::Int16, 1).is_err()); + assert!(header(container, 2, 48_000, SampleFormat::Int16, 0).is_ok(), "zero frames stay valid"); + } + assert!(write_wav(&[0.5], 0, 48_000, SampleFormat::Int16).is_err()); + assert!(write_wav(&[0.1, 0.2, 0.3], 2, 48_000, SampleFormat::Int16).is_err()); + assert!(write_aiff(&[0.1, 0.2, 0.3], 2, 48_000, SampleFormat::Int16).is_err()); + assert!(write_aiff(&[0.1, 0.2], 2, 48_000, SampleFormat::Int16).is_ok()); + } +} diff --git a/crates/audio/src/pcm_interleaved.rs b/crates/audio/src/pcm_interleaved.rs new file mode 100644 index 000000000..f08c19202 --- /dev/null +++ b/crates/audio/src/pcm_interleaved.rs @@ -0,0 +1,96 @@ +//! Interleaved PCM packet decoding into caller-owned planar channels. + +/// The sample representation in an interleaved PCM packet. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Format { + /// Bits per sample. + pub bits: u16, + /// IEEE floating-point samples. + pub float: bool, + /// Big-endian sample bytes. + pub big_endian: bool, + /// Signed 8-bit integers (wider integer PCM is signed). + pub signed: bool, +} + +/// Append complete interleaved frames to caller-owned planar channels. Empty channel slices and +/// zero-bit formats append nothing. Incomplete frames are ignored; unsupported widths produce +/// silent samples, matching the container adapters that use this API. +pub fn decode_into(data: &[u8], cfg: Format, out: &mut [Vec]) { + let ch = out.len(); + if cfg.bits == 0 || ch == 0 { + return; + } + let bps = usize::from(cfg.bits).div_ceil(8); + let Some(frame_bytes) = bps.checked_mul(ch).filter(|&n| n > 0) else { return }; + let n = data.len() / frame_bytes; + for channel in out.iter_mut() { + channel.reserve(n); + } + // `n` is whole frames within `data`, so every sample slice below is in bounds. + for i in 0..n { + for (c, o) in out.iter_mut().enumerate() { + let off = (i * ch + c) * bps; + let b = &data[off..off + bps]; + let v = match (cfg.bits, cfg.float, cfg.big_endian) { + (32, true, false) => f32::from_le_bytes([b[0], b[1], b[2], b[3]]), + (32, true, true) => f32::from_be_bytes([b[0], b[1], b[2], b[3]]), + (64, true, false) => f64::from_le_bytes(b.try_into().unwrap_or([0; 8])) as f32, + (64, true, true) => f64::from_be_bytes(b.try_into().unwrap_or([0; 8])) as f32, + (8, _, _) => { + if cfg.signed { + b[0] as i8 as f32 / 128.0 + } else { + (b[0] as f32 - 128.0) / 128.0 + } + } + (16, _, false) => i16::from_le_bytes([b[0], b[1]]) as f32 / 32768.0, + (16, _, true) => i16::from_be_bytes([b[0], b[1]]) as f32 / 32768.0, + (24, _, false) => (i32::from_le_bytes([0, b[0], b[1], b[2]]) >> 8) as f32 / 8_388_608.0, + (24, _, true) => (i32::from_be_bytes([b[0], b[1], b[2], 0]) >> 8) as f32 / 8_388_608.0, + (32, false, false) => i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2_147_483_648.0, + (32, false, true) => i32::from_be_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2_147_483_648.0, + _ => 0.0, + }; + o.push(v); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn decodes_endian_and_interleaving_without_touching_partial_frames() { + let mut channels = vec![Vec::new(), Vec::new()]; + let fmt = Format { bits: 16, float: false, big_endian: true, signed: true }; + decode_into(&[0x40, 0, 0xc0, 0, 0xff], fmt, &mut channels); + assert_eq!(channels, [vec![0.5], vec![-0.5]]); + decode_into(&[0; 8], Format { bits: 0, ..fmt }, &mut channels); + assert_eq!(channels, [vec![0.5], vec![-0.5]]); + } + #[test] + fn decodes_sample_representations_and_ignores_invalid_inputs() { + let base = Format { bits: 8, float: false, big_endian: false, signed: false }; + let cases: &[(Format, &[u8], f32)] = &[ + (base, &[192], 0.5), + (Format { signed: true, ..base }, &[192], -0.5), + (Format { bits: 16, ..base }, &[0, 64], 0.5), + (Format { bits: 24, ..base }, &[0, 0, 64], 0.5), + (Format { bits: 24, big_endian: true, ..base }, &[0xc0, 0, 0], -0.5), + (Format { bits: 32, ..base }, &[0, 0, 0, 64], 0.5), + (Format { bits: 32, big_endian: true, ..base }, &[0xc0, 0, 0, 0], -0.5), + (Format { bits: 32, float: true, ..base }, &0.5_f32.to_le_bytes(), 0.5), + (Format { bits: 32, float: true, big_endian: true, ..base }, &(-0.5_f32).to_be_bytes(), -0.5), + (Format { bits: 64, float: true, ..base }, &0.5_f64.to_le_bytes(), 0.5), + (Format { bits: 64, float: true, big_endian: true, ..base }, &(-0.5_f64).to_be_bytes(), -0.5), + (Format { bits: 12, ..base }, &[0xff, 0xff], 0.0), + ]; + for &(format, bytes, expected) in cases { + let mut out = [vec![1.0]]; + decode_into(bytes, format, &mut out); + assert_eq!(out[0], [1.0, expected], "{format:?}"); + } + decode_into(&[1], base, &mut []); + } +} diff --git a/crates/audio/src/qoa.rs b/crates/audio/src/qoa.rs new file mode 100644 index 000000000..a04430137 --- /dev/null +++ b/crates/audio/src/qoa.rs @@ -0,0 +1,411 @@ +//! QOA ("Quite OK Audio"): a decoder (feature `qoa-decode`) and an encoder (feature `qoa-encode`) +//! for whole `.qoa` files, 16-bit, 1 to 8 channels. +//! +//! Written from the published QOA specification (qoaformat.org). A file is an 8-byte header (the +//! magic `qoaf` and the number of samples per channel) followed by frames of up to 5120 samples +//! per channel. Each frame starts with its channel count, sample rate, sample count and size, then +//! the state of one 4-tap sign-sign LMS predictor per channel, then 64-bit slices of 20 samples: +//! a 4-bit scale factor and twenty 3-bit quantised residuals, the channels interleaved slice by +//! slice. +//! +//! Streaming files (a sample count of 0 in the header) are not supported. +//! Samples are `i16`, one `Vec` per channel. + +#[cfg(feature = "qoa-decode")] +const MAX_FRAME_SAMPLES: usize = 5120; +const SLICE_SAMPLES: usize = 20; +const LMS_LEN: usize = 4; +const MAGIC: &[u8; 4] = b"qoaf"; +/// The most channels a file may have. +pub const MAX_CHANNELS: usize = 8; + +/// `dequant[scale factor][quantised residual]`: `round(round((sf + 1)^2.75) * [0.75, -0.75, 2.5, +/// -2.5, 4.5, -4.5, 7, -7])`. +const DEQUANT: [[i32; 8]; 16] = [ + [1, -1, 3, -3, 5, -5, 7, -7], + [5, -5, 18, -18, 32, -32, 49, -49], + [16, -16, 53, -53, 95, -95, 147, -147], + [34, -34, 113, -113, 203, -203, 315, -315], + [63, -63, 210, -210, 378, -378, 588, -588], + [104, -104, 345, -345, 621, -621, 966, -966], + [158, -158, 528, -528, 950, -950, 1477, -1477], + [228, -228, 760, -760, 1368, -1368, 2128, -2128], + [316, -316, 1053, -1053, 1895, -1895, 2947, -2947], + [422, -422, 1405, -1405, 2529, -2529, 3934, -3934], + [548, -548, 1828, -1828, 3290, -3290, 5117, -5117], + [696, -696, 2320, -2320, 4176, -4176, 6496, -6496], + [868, -868, 2893, -2893, 5207, -5207, 8099, -8099], + [1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933], + [1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005], + [1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336], +]; + +/// What went wrong reading or writing a QOA file. +#[non_exhaustive] +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum Error { + /// The input is not a QOA file, or is damaged or truncated. + #[error("malformed QOA: {0}")] + Malformed(&'static str), + /// A valid file this module does not handle (a streaming file). + #[error("unsupported QOA: {0}")] + Unsupported(&'static str), + /// The samples or settings given to the encoder cannot be written as QOA. + #[error("QOA cannot encode: {0}")] + InvalidInput(&'static str), +} + +/// A decoded file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Audio { + /// Sample rate in Hz (1 to 16 777 215). + pub sample_rate: u32, + /// One `Vec` of samples per channel, all the same length. + pub channels: Vec>, +} + +/// The predictor: the last four samples and four weights. +#[derive(Clone, Copy)] +struct Lms { + history: [i32; LMS_LEN], + weights: [i32; LMS_LEN], +} + +impl Lms { + fn new() -> Self { + Lms { history: [0; LMS_LEN], weights: [0, 0, -(1 << 13), 1 << 14] } + } + + fn predict(&self) -> i32 { + let mut p = 0i32; + for i in 0..LMS_LEN { + p = p.wrapping_add(self.weights[i].wrapping_mul(self.history[i])); + } + p >> 13 + } + + fn update(&mut self, sample: i32, residual: i32) { + let delta = residual >> 4; + for i in 0..LMS_LEN { + self.weights[i] += if self.history[i] < 0 { -delta } else { delta }; + } + self.history.copy_within(1.., 0); + self.history[LMS_LEN - 1] = sample; + } +} + +fn clamp16(v: i32) -> i32 { + v.clamp(-32768, 32767) +} + +#[cfg(feature = "qoa-decode")] +mod decode { + use super::{Audio, DEQUANT, Error, LMS_LEN, Lms, MAGIC, MAX_CHANNELS, MAX_FRAME_SAMPLES, SLICE_SAMPLES, clamp16}; + + fn be16(b: &[u8], i: usize) -> u16 { + u16::from_be_bytes([b[i], b[i + 1]]) + } + + /// Decode a whole `.qoa` file. + /// + /// The declared length is checked against the input before anything is allocated: a slice of + /// 8 bytes holds at most 20 samples, so a file cannot declare more samples than that. + pub fn decode(bytes: &[u8]) -> Result { + if bytes.len() < 8 || &bytes[..4] != MAGIC { + return Err(Error::Malformed("missing the qoaf magic")); + } + let total = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize; + if total == 0 { + return Err(Error::Unsupported("streaming files (a sample count of 0)")); + } + if bytes.len() < 16 { + return Err(Error::Malformed("truncated frame header")); + } + let channels = usize::from(bytes[8]); + let sample_rate = u32::from_be_bytes([0, bytes[9], bytes[10], bytes[11]]); + if channels == 0 || channels > MAX_CHANNELS || sample_rate == 0 { + return Err(Error::Malformed("bad channel count or sample rate")); + } + // 8 bytes (20 samples) per channel at the very least, plus the frame headers. + let room = (bytes.len() - 8) / (8 * channels) * SLICE_SAMPLES; + if total > room { + return Err(Error::Malformed("the file is too short for its declared length")); + } + let mut out: Vec> = Vec::new(); + for _ in 0..channels { + let mut v = Vec::new(); + v.try_reserve_exact(total).map_err(|_| Error::Malformed("too many samples"))?; + out.push(v); + } + let mut pos = 8; + let mut done = 0usize; + while done < total { + let head = bytes.get(pos..pos + 8).ok_or(Error::Malformed("truncated frame header"))?; + let rate = u32::from_be_bytes([0, head[1], head[2], head[3]]); + if usize::from(head[0]) != channels || rate != sample_rate { + return Err(Error::Malformed("the channel count or sample rate changes between frames")); + } + let samples = usize::from(be16(head, 4)); + let size = usize::from(be16(head, 6)); + let slices = samples.div_ceil(SLICE_SAMPLES); + if samples == 0 || samples > MAX_FRAME_SAMPLES || samples > total - done { + return Err(Error::Malformed("bad frame sample count")); + } + if size != 8 + 16 * channels + 8 * slices * channels { + return Err(Error::Malformed("frame size does not match its sample count")); + } + let frame = bytes.get(pos..pos + size).ok_or(Error::Malformed("truncated frame"))?; + let mut lms = [Lms::new(); MAX_CHANNELS]; + for (c, state) in lms.iter_mut().take(channels).enumerate() { + let at = 8 + c * 16; + for i in 0..LMS_LEN { + state.history[i] = i32::from(be16(frame, at + 2 * i) as i16); + state.weights[i] = i32::from(be16(frame, at + 8 + 2 * i) as i16); + } + } + let mut at = 8 + 16 * channels; + for s in 0..slices { + let n = (samples - s * SLICE_SAMPLES).min(SLICE_SAMPLES); + for (c, state) in lms.iter_mut().take(channels).enumerate() { + let mut slice = u64::from_be_bytes([ + frame[at], + frame[at + 1], + frame[at + 2], + frame[at + 3], + frame[at + 4], + frame[at + 5], + frame[at + 6], + frame[at + 7], + ]); + at += 8; + let table = &DEQUANT[(slice >> 60) as usize & 15]; + for _ in 0..n { + let dequantised = table[(slice >> 57) as usize & 7]; + slice <<= 3; + let sample = clamp16(state.predict() + dequantised); + out[c].push(sample as i16); + state.update(sample, dequantised); + } + } + } + pos += size; + done += samples; + } + Ok(Audio { sample_rate, channels: out }) + } +} +#[cfg(feature = "qoa-decode")] +pub use decode::decode; + +#[cfg(feature = "qoa-encode")] +mod encode { + use super::{DEQUANT, Error, Lms, MAGIC, MAX_CHANNELS, SLICE_SAMPLES, clamp16}; + + /// The quantised residual (0..8) whose dequantised value is nearest `residual`. + fn quantise(table: &[i32; 8], residual: i32) -> usize { + let mut best = 0; + let mut best_err = i64::MAX; + for (q, &d) in table.iter().enumerate() { + let e = i64::from(residual - d).pow(2); + if e < best_err { + best = q; + best_err = e; + } + } + best + } + + /// Encode one slice of one channel with every scale factor and keep the one with the least + /// squared error. Returns the 64-bit slice; `lms` is advanced to the chosen result. + fn encode_slice(lms: &mut Lms, samples: &[i16]) -> u64 { + let mut best: Option<(i64, u64, Lms)> = None; + for (sf, table) in DEQUANT.iter().enumerate() { + let mut trial = *lms; + let mut slice = sf as u64; + let mut err = 0i64; + for k in 0..SLICE_SAMPLES { + let mut q = 0; + if let Some(&s) = samples.get(k) { + let predicted = trial.predict(); + q = quantise(table, i32::from(s) - predicted); + let sample = clamp16(predicted + table[q]); + err += i64::from(i32::from(s) - sample).pow(2); + trial.update(sample, table[q]); + } + slice = slice << 3 | q as u64; + } + // 4 + 60 bits are in `slice`; the scale factor belongs on top. + let slice = slice & ((1 << 60) - 1) | (sf as u64) << 60; + if best.as_ref().is_none_or(|b| err < b.0) { + best = Some((err, slice, trial)); + } + } + match best { + Some((_, slice, state)) => { + *lms = state; + slice + } + None => 0, + } + } + + /// Encode `channels` (one `Vec` of samples per channel, all the same length) as a `.qoa` file. + pub fn encode(sample_rate: u32, channels: &[Vec]) -> Result, Error> { + let n = channels.len(); + if n == 0 || n > MAX_CHANNELS { + return Err(Error::InvalidInput("QOA stores 1 to 8 channels")); + } + if sample_rate == 0 || sample_rate > 0x00ff_ffff { + return Err(Error::InvalidInput("the sample rate must be 1 to 16777215 Hz")); + } + let total = channels[0].len(); + if channels.iter().any(|c| c.len() != total) { + return Err(Error::InvalidInput("the channels differ in length")); + } + let total32 = u32::try_from(total).map_err(|_| Error::InvalidInput("too many samples"))?; + if total == 0 { + return Err(Error::InvalidInput("QOA cannot store an empty file")); + } + let mut out = Vec::with_capacity(8 + total * n / 2); + out.extend_from_slice(MAGIC); + out.extend_from_slice(&total32.to_be_bytes()); + let mut lms = [Lms::new(); MAX_CHANNELS]; + let mut start = 0; + while start < total { + let len = (total - start).min(5120); + let slices = len.div_ceil(SLICE_SAMPLES); + let size = 8 + 16 * n + 8 * slices * n; + out.push(n as u8); + out.extend_from_slice(&sample_rate.to_be_bytes()[1..]); + out.extend_from_slice(&(len as u16).to_be_bytes()); + out.extend_from_slice(&(size as u16).to_be_bytes()); + // The state a frame starts from is written as 16-bit values, so the predictor + // continues from exactly what a decoder reads. + for state in lms.iter_mut().take(n) { + for v in state.history.iter_mut().chain(state.weights.iter_mut()) { + *v = i32::from(*v as i16); + out.extend_from_slice(&(*v as i16).to_be_bytes()); + } + } + for s in 0..slices { + let from = start + s * SLICE_SAMPLES; + let to = (from + SLICE_SAMPLES).min(start + len); + for (c, state) in lms.iter_mut().take(n).enumerate() { + out.extend_from_slice(&encode_slice(state, &channels[c][from..to]).to_be_bytes()); + } + } + start += len; + } + Ok(out) + } +} +#[cfg(feature = "qoa-encode")] +pub use encode::encode; + +#[cfg(all(test, feature = "qoa-decode", feature = "qoa-encode"))] +mod tests { + use super::*; + + fn tone(frames: usize, ch: usize) -> Vec> { + (0..ch) + .map(|c| (0..frames).map(|i| (((i as f64) * (0.03 + 0.01 * c as f64)).sin() * 12000.0 + ((i * 7919) % 200) as f64) as i16).collect()) + .collect() + } + + fn snr(a: &[i16], b: &[i16]) -> f64 { + let (mut s, mut e) = (0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + s += f64::from(x).powi(2); + e += (f64::from(x) - f64::from(y)).powi(2); + } + 10.0 * (s / e.max(1.0)).log10() + } + + #[test] + fn dequant_table_matches_its_formula() { + for (sf, row) in DEQUANT.iter().enumerate() { + let scale = ((sf as f64 + 1.0).powf(2.75)).round(); + for (q, base) in [0.75, -0.75, 2.5, -2.5, 4.5, -4.5, 7.0, -7.0].into_iter().enumerate() { + assert_eq!(f64::from(row[q]), (scale * base).round(), "sf {sf} q {q}"); + } + } + } + + #[test] + fn round_trips_with_a_good_signal_to_noise_ratio() { + for (frames, ch) in [(1, 1), (19, 2), (20, 1), (21, 2), (5120, 1), (5121, 2), (12_345, 8)] { + let src = tone(frames, ch); + let bytes = encode(44_100, &src).unwrap(); + let back = decode(&bytes).unwrap(); + assert_eq!((back.sample_rate, back.channels.len(), back.channels[0].len()), (44_100, ch, frames)); + if frames > 1000 { + for (c, (a, b)) in src.iter().zip(&back.channels).enumerate() { + assert!(snr(a, b) > 25.0, "{frames}x{ch} channel {c}"); + } + } + } + } + + #[test] + fn silence_and_full_scale_extremes_survive() { + let silent = vec![vec![0i16; 3000]]; + // No residual value is zero, so silence decodes to a tiny residue, never exactly 0. + let quiet = decode(&encode(8000, &silent).unwrap()).unwrap(); + assert!(quiet.channels[0].iter().all(|&s| s.abs() <= 2), "silence stays within 2 LSB"); + let square: Vec = (0..4000).map(|i| if (i / 50) % 2 == 0 { i16::MAX } else { i16::MIN }).collect(); + let back = decode(&encode(48_000, std::slice::from_ref(&square)).unwrap()).unwrap(); + assert_eq!(back.channels[0].len(), square.len()); + } + + #[test] + fn the_file_has_the_documented_layout() { + let bytes = encode(48_000, &tone(100, 2)).unwrap(); + assert_eq!(&bytes[..4], b"qoaf"); + assert_eq!(u32::from_be_bytes(bytes[4..8].try_into().unwrap()), 100); + assert_eq!(bytes[8], 2); + assert_eq!(&bytes[9..12], &48_000u32.to_be_bytes()[1..]); + assert_eq!(u16::from_be_bytes([bytes[12], bytes[13]]), 100); + // 8 header + 2 channels * 16 state + 5 slices * 2 channels * 8 + assert_eq!(usize::from(u16::from_be_bytes([bytes[14], bytes[15]])), 8 + 32 + 80); + assert_eq!(bytes.len(), 8 + 8 + 32 + 80); + // The first frame starts from the specified predictor state. + assert_eq!(&bytes[16 + 8..16 + 16], &[0, 0, 0, 0, 0xe0, 0, 0x40, 0]); + } + + #[test] + fn invalid_input_to_the_encoder_is_refused() { + assert!(encode(44_100, &[]).is_err()); + assert!(encode(0, &[vec![0; 10]]).is_err()); + assert!(encode(1 << 24, &[vec![0; 10]]).is_err()); + assert!(encode(44_100, &[vec![0; 10], vec![0; 9]]).is_err()); + assert!(encode(44_100, &[vec![]]).is_err()); + assert!(encode(44_100, &vec![vec![0; 10]; 9]).is_err()); + } + + #[test] + fn hostile_input_is_an_error_not_a_panic() { + let good = encode(44_100, &tone(6000, 2)).unwrap(); + for len in 0..good.len().min(600) { + let _ = decode(&good[..len]); + } + assert!(decode(&good[..good.len() - 1]).is_err()); + // A header that declares more samples than the bytes can hold. + let mut huge = good.clone(); + huge[4..8].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(decode(&huge).is_err()); + // A streaming file, and a frame whose size field lies. + let mut streaming = good.clone(); + streaming[4..8].fill(0); + assert_eq!(decode(&streaming), Err(Error::Unsupported("streaming files (a sample count of 0)"))); + let mut lying = good.clone(); + lying[14] ^= 1; + assert!(decode(&lying).is_err()); + let mut zero_rate = good.clone(); + zero_rate[9..12].fill(0); + assert!(decode(&zero_rate).is_err()); + let mut changed = good; + let second = 8 + usize::from(u16::from_be_bytes([changed[14], changed[15]])); + changed[second] = 1; + assert!(decode(&changed).is_err()); + } +} 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/sbc.rs b/crates/audio/src/sbc.rs new file mode 100644 index 000000000..35165e966 --- /dev/null +++ b/crates/audio/src/sbc.rs @@ -0,0 +1,1999 @@ +//! Bluetooth Low Complexity Subband Coding (SBC) audio codec. +//! +//! Clean-room implementation based on Bluetooth SIG Advanced Audio Distribution Profile +//! (A2DP) Specification v1.3, Appendix B (Section 12: "Technical Specification of SBC") +//! and Hands-Free Profile (HFP 1.6) mSBC specification. +//! +//! SBC is a subband codec designed to deliver audio quality with low computational +//! complexity, operating at 16 kHz, 32 kHz, 44.1 kHz, or 48 kHz in Mono, Dual Channel, +//! Stereo, or Joint Stereo configurations with 4 or 8 subbands. + +#![allow(clippy::excessive_precision, clippy::needless_range_loop, clippy::cognitive_complexity, clippy::too_many_arguments)] + +const MAX_INPUT_BYTES: usize = 64 * 1024 * 1024; +const MAX_SAMPLES: usize = 64 * 1024 * 1024; + +/// Standard SBC syncword byte (`0x9C`). +pub const SYNCWORD_SBC: u8 = 0x9C; +/// mSBC wideband speech syncword byte (`0xAD`). +pub const SYNCWORD_MSBC: u8 = 0xAD; + +/// Offset table for 4 subbands loudness bit allocation (Table 12.21). +pub static OFFSET4: [[i8; 4]; 4] = [[-1, 0, 0, 0], [-2, 0, 0, 1], [-2, 0, 0, 1], [-2, 0, 0, 1]]; + +/// Offset table for 8 subbands loudness bit allocation (Table 12.22). +pub static OFFSET8: [[i8; 8]; 4] = [[-2, 0, 0, 0, 0, 0, 0, 1], [-3, 0, 0, 0, 0, 0, 1, 2], [-4, 0, 0, 0, 0, 0, 1, 2], [-4, 0, 0, 0, 0, 0, 1, 2]]; + +/// Analysis and synthesis filter coefficients for 4 subbands (Table 12.23). +pub(crate) static PROTO_4_40: [f32; 40] = [ + 0.0000000000e+00_f32, + 5.3654897600e-04_f32, + 1.4918835700e-03_f32, + 2.7337090400e-03_f32, + 3.8372019300e-03_f32, + 3.8920514900e-03_f32, + 1.8658169100e-03_f32, + -3.0601228600e-03_f32, + 1.0913762000e-02_f32, + 2.0438508700e-02_f32, + 2.8875739200e-02_f32, + 3.2193929000e-02_f32, + 2.5876781100e-02_f32, + 6.1324518600e-03_f32, + -2.8821727400e-02_f32, + -7.7646349400e-02_f32, + 1.3559327400e-01_f32, + 1.9498784100e-01_f32, + 2.4663666200e-01_f32, + 2.8182820300e-01_f32, + 2.9431533200e-01_f32, + 2.8182820300e-01_f32, + 2.4663666200e-01_f32, + 1.9498784100e-01_f32, + -1.3559327400e-01_f32, + -7.7646349400e-02_f32, + -2.8821727400e-02_f32, + 6.1324518600e-03_f32, + 2.5876781100e-02_f32, + 3.2193929000e-02_f32, + 2.8875739200e-02_f32, + 2.0438508700e-02_f32, + -1.0913762000e-02_f32, + -3.0601228600e-03_f32, + 1.8658169100e-03_f32, + 3.8920514900e-03_f32, + 3.8372019300e-03_f32, + 2.7337090400e-03_f32, + 1.4918835700e-03_f32, + 5.3654897600e-04_f32, +]; + +/// Analysis and synthesis filter coefficients for 8 subbands (Table 12.24). +pub(crate) static PROTO_8_80: [f32; 80] = [ + 0.0000000000e+00_f32, + 1.5657539800e-04_f32, + 3.4325642500e-04_f32, + 5.5462020200e-04_f32, + 8.2391950600e-04_f32, + 1.1399250700e-03_f32, + 1.4764016900e-03_f32, + 1.7837172500e-03_f32, + 2.0118254200e-03_f32, + 2.1037198900e-03_f32, + 1.9945455400e-03_f32, + 1.6165628300e-03_f32, + 9.0215450200e-04_f32, + -1.7880536100e-04_f32, + -1.6497309800e-03_f32, + -3.4971745400e-03_f32, + 5.6594947300e-03_f32, + 8.0294116300e-03_f32, + 1.0458444300e-02_f32, + 1.2747233500e-02_f32, + 1.4652526300e-02_f32, + 1.5904560300e-02_f32, + 1.6220847100e-02_f32, + 1.5318410600e-02_f32, + 1.2937180600e-02_f32, + 8.8575754000e-03_f32, + 2.9240844200e-03_f32, + -4.9157802400e-03_f32, + -1.4640407600e-02_f32, + -2.6109875200e-02_f32, + -3.9075138100e-02_f32, + -5.3187303200e-02_f32, + 6.7998943100e-02_f32, + 8.2984757800e-02_f32, + 9.7575391800e-02_f32, + 1.1119668900e-01_f32, + 1.2326454800e-01_f32, + 1.3326441500e-01_f32, + 1.4075350500e-01_f32, + 1.4538984700e-01_f32, + 1.4695506800e-01_f32, + 1.4538984700e-01_f32, + 1.4075350500e-01_f32, + 1.3326441500e-01_f32, + 1.2326454800e-01_f32, + 1.1119668900e-01_f32, + 9.7575391800e-02_f32, + 8.2984757800e-02_f32, + -6.7998943100e-02_f32, + -5.3187303200e-02_f32, + -3.9075138100e-02_f32, + -2.6109875200e-02_f32, + -1.4640407600e-02_f32, + -4.9157802400e-03_f32, + 2.9240844200e-03_f32, + 8.8575754000e-03_f32, + 1.2937180600e-02_f32, + 1.5318410600e-02_f32, + 1.6220847100e-02_f32, + 1.5904560300e-02_f32, + 1.4652526300e-02_f32, + 1.2747233500e-02_f32, + 1.0458444300e-02_f32, + 8.0294116300e-03_f32, + -5.6594947300e-03_f32, + -3.4971745400e-03_f32, + -1.6497309800e-03_f32, + -1.7880536100e-04_f32, + 9.0215450200e-04_f32, + 1.6165628300e-03_f32, + 1.9945455400e-03_f32, + 2.1037198900e-03_f32, + 2.0118254200e-03_f32, + 1.7837172500e-03_f32, + 1.4764016900e-03_f32, + 1.1399250700e-03_f32, + 8.2391950600e-04_f32, + 5.5462020200e-04_f32, + 3.4325642500e-04_f32, + 1.5657539800e-04_f32, +]; + +/// Scaled synthesis filter prototype for 4 subbands. +pub(crate) static SYNTH_D_4: [f32; 40] = [ + -0.0000000000e+00_f32, + -2.1461959040e-03_f32, + -5.9675342800e-03_f32, + -1.0934836160e-02_f32, + -1.5348807720e-02_f32, + -1.5568205960e-02_f32, + -7.4632676400e-03_f32, + 1.2240491440e-02_f32, + -4.3655048000e-02_f32, + -8.1754034800e-02_f32, + -1.1550295680e-01_f32, + -1.2877571600e-01_f32, + -1.0350712440e-01_f32, + -2.4529807440e-02_f32, + 1.1528690960e-01_f32, + 3.1058539760e-01_f32, + -5.4237309600e-01_f32, + -7.7995136400e-01_f32, + -9.8654664800e-01_f32, + -1.1273128120e+00_f32, + -1.1772613280e+00_f32, + -1.1273128120e+00_f32, + -9.8654664800e-01_f32, + -7.7995136400e-01_f32, + 5.4237309600e-01_f32, + 3.1058539760e-01_f32, + 1.1528690960e-01_f32, + -2.4529807440e-02_f32, + -1.0350712440e-01_f32, + -1.2877571600e-01_f32, + -1.1550295680e-01_f32, + -8.1754034800e-02_f32, + 4.3655048000e-02_f32, + 1.2240491440e-02_f32, + -7.4632676400e-03_f32, + -1.5568205960e-02_f32, + -1.5348807720e-02_f32, + -1.0934836160e-02_f32, + -5.9675342800e-03_f32, + -2.1461959040e-03_f32, +]; + +/// Scaled synthesis filter prototype for 8 subbands. +pub(crate) static SYNTH_D_8: [f32; 80] = [ + -0.0000000000e+00_f32, + -1.2526031840e-03_f32, + -2.7460514000e-03_f32, + -4.4369616160e-03_f32, + -6.5913560480e-03_f32, + -9.1194005600e-03_f32, + -1.1811213520e-02_f32, + -1.4269738000e-02_f32, + -1.6094603360e-02_f32, + -1.6829759120e-02_f32, + -1.5956364320e-02_f32, + -1.2932502640e-02_f32, + -7.2172360160e-03_f32, + 1.4304428880e-03_f32, + 1.3197847840e-02_f32, + 2.7977396320e-02_f32, + -4.5275957840e-02_f32, + -6.4235293040e-02_f32, + -8.3667554400e-02_f32, + -1.0197786800e-01_f32, + -1.1722021040e-01_f32, + -1.2723648240e-01_f32, + -1.2976677680e-01_f32, + -1.2254728480e-01_f32, + -1.0349744480e-01_f32, + -7.0860603200e-02_f32, + -2.3392675360e-02_f32, + 3.9326241920e-02_f32, + 1.1712326080e-01_f32, + 2.0887900160e-01_f32, + 3.1260110480e-01_f32, + 4.2549842560e-01_f32, + -5.4399154480e-01_f32, + -6.6387806240e-01_f32, + -7.8060313440e-01_f32, + -8.8957351200e-01_f32, + -9.8611638400e-01_f32, + -1.0661153200e+00_f32, + -1.1260280400e+00_f32, + -1.1631187760e+00_f32, + -1.1756405440e+00_f32, + -1.1631187760e+00_f32, + -1.1260280400e+00_f32, + -1.0661153200e+00_f32, + -9.8611638400e-01_f32, + -8.8957351200e-01_f32, + -7.8060313440e-01_f32, + -6.6387806240e-01_f32, + 5.4399154480e-01_f32, + 4.2549842560e-01_f32, + 3.1260110480e-01_f32, + 2.0887900160e-01_f32, + 1.1712326080e-01_f32, + 3.9326241920e-02_f32, + -2.3392675360e-02_f32, + -7.0860603200e-02_f32, + -1.0349744480e-01_f32, + -1.2254728480e-01_f32, + -1.2976677680e-01_f32, + -1.2723648240e-01_f32, + -1.1722021040e-01_f32, + -1.0197786800e-01_f32, + -8.3667554400e-02_f32, + -6.4235293040e-02_f32, + 4.5275957840e-02_f32, + 2.7977396320e-02_f32, + 1.3197847840e-02_f32, + 1.4304428880e-03_f32, + -7.2172360160e-03_f32, + -1.2932502640e-02_f32, + -1.5956364320e-02_f32, + -1.6829759120e-02_f32, + -1.6094603360e-02_f32, + -1.4269738000e-02_f32, + -1.1811213520e-02_f32, + -9.1194005600e-03_f32, + -6.5913560480e-03_f32, + -4.4369616160e-03_f32, + -2.7460514000e-03_f32, + -1.2526031840e-03_f32, +]; + +pub(crate) static SYNTH_COS_4: [[f32; 4]; 8] = [ + [7.0710678119e-01_f32, -7.0710678119e-01_f32, -7.0710678119e-01_f32, 7.0710678119e-01_f32], + [3.8268343237e-01_f32, -9.2387953251e-01_f32, 9.2387953251e-01_f32, -3.8268343237e-01_f32], + [6.1232339957e-17_f32, -1.8369701987e-16_f32, 3.0616169979e-16_f32, -4.2862637970e-16_f32], + [-3.8268343237e-01_f32, 9.2387953251e-01_f32, -9.2387953251e-01_f32, 3.8268343237e-01_f32], + [-7.0710678119e-01_f32, 7.0710678119e-01_f32, 7.0710678119e-01_f32, -7.0710678119e-01_f32], + [-9.2387953251e-01_f32, -3.8268343237e-01_f32, 3.8268343237e-01_f32, 9.2387953251e-01_f32], + [-1.0000000000e+00_f32, -1.0000000000e+00_f32, -1.0000000000e+00_f32, -1.0000000000e+00_f32], + [-9.2387953251e-01_f32, -3.8268343237e-01_f32, 3.8268343237e-01_f32, 9.2387953251e-01_f32], +]; + +pub(crate) static SYNTH_COS_8: [[f32; 8]; 16] = [ + [ + 7.0710678119e-01_f32, + -7.0710678119e-01_f32, + -7.0710678119e-01_f32, + 7.0710678119e-01_f32, + 7.0710678119e-01_f32, + -7.0710678119e-01_f32, + -7.0710678119e-01_f32, + 7.0710678119e-01_f32, + ], + [ + 5.5557023302e-01_f32, + -9.8078528040e-01_f32, + 1.9509032202e-01_f32, + 8.3146961230e-01_f32, + -8.3146961230e-01_f32, + -1.9509032202e-01_f32, + 9.8078528040e-01_f32, + -5.5557023302e-01_f32, + ], + [ + 3.8268343237e-01_f32, + -9.2387953251e-01_f32, + 9.2387953251e-01_f32, + -3.8268343237e-01_f32, + -3.8268343237e-01_f32, + 9.2387953251e-01_f32, + -9.2387953251e-01_f32, + 3.8268343237e-01_f32, + ], + [ + 1.9509032202e-01_f32, + -5.5557023302e-01_f32, + 8.3146961230e-01_f32, + -9.8078528040e-01_f32, + 9.8078528040e-01_f32, + -8.3146961230e-01_f32, + 5.5557023302e-01_f32, + -1.9509032202e-01_f32, + ], + [ + 6.1232339957e-17_f32, + -1.8369701987e-16_f32, + 3.0616169979e-16_f32, + -4.2862637970e-16_f32, + 5.5109105962e-16_f32, + -2.4499125789e-15_f32, + -9.8033641995e-16_f32, + -2.6948419388e-15_f32, + ], + [ + -1.9509032202e-01_f32, + 5.5557023302e-01_f32, + -8.3146961230e-01_f32, + 9.8078528040e-01_f32, + -9.8078528040e-01_f32, + 8.3146961230e-01_f32, + -5.5557023302e-01_f32, + 1.9509032202e-01_f32, + ], + [ + -3.8268343237e-01_f32, + 9.2387953251e-01_f32, + -9.2387953251e-01_f32, + 3.8268343237e-01_f32, + 3.8268343237e-01_f32, + -9.2387953251e-01_f32, + 9.2387953251e-01_f32, + -3.8268343237e-01_f32, + ], + [ + -5.5557023302e-01_f32, + 9.8078528040e-01_f32, + -1.9509032202e-01_f32, + -8.3146961230e-01_f32, + 8.3146961230e-01_f32, + 1.9509032202e-01_f32, + -9.8078528040e-01_f32, + 5.5557023302e-01_f32, + ], + [ + -7.0710678119e-01_f32, + 7.0710678119e-01_f32, + 7.0710678119e-01_f32, + -7.0710678119e-01_f32, + -7.0710678119e-01_f32, + 7.0710678119e-01_f32, + 7.0710678119e-01_f32, + -7.0710678119e-01_f32, + ], + [ + -8.3146961230e-01_f32, + 1.9509032202e-01_f32, + 9.8078528040e-01_f32, + 5.5557023302e-01_f32, + -5.5557023302e-01_f32, + -9.8078528040e-01_f32, + -1.9509032202e-01_f32, + 8.3146961230e-01_f32, + ], + [ + -9.2387953251e-01_f32, + -3.8268343237e-01_f32, + 3.8268343237e-01_f32, + 9.2387953251e-01_f32, + 9.2387953251e-01_f32, + 3.8268343237e-01_f32, + -3.8268343237e-01_f32, + -9.2387953251e-01_f32, + ], + [ + -9.8078528040e-01_f32, + -8.3146961230e-01_f32, + -5.5557023302e-01_f32, + -1.9509032202e-01_f32, + 1.9509032202e-01_f32, + 5.5557023302e-01_f32, + 8.3146961230e-01_f32, + 9.8078528040e-01_f32, + ], + [ + -1.0000000000e+00_f32, + -1.0000000000e+00_f32, + -1.0000000000e+00_f32, + -1.0000000000e+00_f32, + -1.0000000000e+00_f32, + -1.0000000000e+00_f32, + -1.0000000000e+00_f32, + -1.0000000000e+00_f32, + ], + [ + -9.8078528040e-01_f32, + -8.3146961230e-01_f32, + -5.5557023302e-01_f32, + -1.9509032202e-01_f32, + 1.9509032202e-01_f32, + 5.5557023302e-01_f32, + 8.3146961230e-01_f32, + 9.8078528040e-01_f32, + ], + [ + -9.2387953251e-01_f32, + -3.8268343237e-01_f32, + 3.8268343237e-01_f32, + 9.2387953251e-01_f32, + 9.2387953251e-01_f32, + 3.8268343237e-01_f32, + -3.8268343237e-01_f32, + -9.2387953251e-01_f32, + ], + [ + -8.3146961230e-01_f32, + 1.9509032202e-01_f32, + 9.8078528040e-01_f32, + 5.5557023302e-01_f32, + -5.5557023302e-01_f32, + -9.8078528040e-01_f32, + -1.9509032202e-01_f32, + 8.3146961230e-01_f32, + ], +]; + +pub(crate) static ANALYSIS_COS_4: [[f32; 8]; 4] = [ + [ + 7.0710678119e-01_f32, + 9.2387953251e-01_f32, + 1.0000000000e+00_f32, + 9.2387953251e-01_f32, + 7.0710678119e-01_f32, + 3.8268343237e-01_f32, + 6.1232339957e-17_f32, + -3.8268343237e-01_f32, + ], + [ + -7.0710678119e-01_f32, + 3.8268343237e-01_f32, + 1.0000000000e+00_f32, + 3.8268343237e-01_f32, + -7.0710678119e-01_f32, + -9.2387953251e-01_f32, + -1.8369701987e-16_f32, + 9.2387953251e-01_f32, + ], + [ + -7.0710678119e-01_f32, + -3.8268343237e-01_f32, + 1.0000000000e+00_f32, + -3.8268343237e-01_f32, + -7.0710678119e-01_f32, + 9.2387953251e-01_f32, + 3.0616169979e-16_f32, + -9.2387953251e-01_f32, + ], + [ + 7.0710678119e-01_f32, + -9.2387953251e-01_f32, + 1.0000000000e+00_f32, + -9.2387953251e-01_f32, + 7.0710678119e-01_f32, + -3.8268343237e-01_f32, + -4.2862637970e-16_f32, + 3.8268343237e-01_f32, + ], +]; + +pub(crate) static ANALYSIS_COS_8: [[f32; 16]; 8] = [ + [ + 7.0710678119e-01_f32, + 8.3146961230e-01_f32, + 9.2387953251e-01_f32, + 9.8078528040e-01_f32, + 1.0000000000e+00_f32, + 9.8078528040e-01_f32, + 9.2387953251e-01_f32, + 8.3146961230e-01_f32, + 7.0710678119e-01_f32, + 5.5557023302e-01_f32, + 3.8268343237e-01_f32, + 1.9509032202e-01_f32, + 6.1232339957e-17_f32, + -1.9509032202e-01_f32, + -3.8268343237e-01_f32, + -5.5557023302e-01_f32, + ], + [ + -7.0710678119e-01_f32, + -1.9509032202e-01_f32, + 3.8268343237e-01_f32, + 8.3146961230e-01_f32, + 1.0000000000e+00_f32, + 8.3146961230e-01_f32, + 3.8268343237e-01_f32, + -1.9509032202e-01_f32, + -7.0710678119e-01_f32, + -9.8078528040e-01_f32, + -9.2387953251e-01_f32, + -5.5557023302e-01_f32, + -1.8369701987e-16_f32, + 5.5557023302e-01_f32, + 9.2387953251e-01_f32, + 9.8078528040e-01_f32, + ], + [ + -7.0710678119e-01_f32, + -9.8078528040e-01_f32, + -3.8268343237e-01_f32, + 5.5557023302e-01_f32, + 1.0000000000e+00_f32, + 5.5557023302e-01_f32, + -3.8268343237e-01_f32, + -9.8078528040e-01_f32, + -7.0710678119e-01_f32, + 1.9509032202e-01_f32, + 9.2387953251e-01_f32, + 8.3146961230e-01_f32, + 3.0616169979e-16_f32, + -8.3146961230e-01_f32, + -9.2387953251e-01_f32, + -1.9509032202e-01_f32, + ], + [ + 7.0710678119e-01_f32, + -5.5557023302e-01_f32, + -9.2387953251e-01_f32, + 1.9509032202e-01_f32, + 1.0000000000e+00_f32, + 1.9509032202e-01_f32, + -9.2387953251e-01_f32, + -5.5557023302e-01_f32, + 7.0710678119e-01_f32, + 8.3146961230e-01_f32, + -3.8268343237e-01_f32, + -9.8078528040e-01_f32, + -4.2862637970e-16_f32, + 9.8078528040e-01_f32, + 3.8268343237e-01_f32, + -8.3146961230e-01_f32, + ], + [ + 7.0710678119e-01_f32, + 5.5557023302e-01_f32, + -9.2387953251e-01_f32, + -1.9509032202e-01_f32, + 1.0000000000e+00_f32, + -1.9509032202e-01_f32, + -9.2387953251e-01_f32, + 5.5557023302e-01_f32, + 7.0710678119e-01_f32, + -8.3146961230e-01_f32, + -3.8268343237e-01_f32, + 9.8078528040e-01_f32, + 5.5109105962e-16_f32, + -9.8078528040e-01_f32, + 3.8268343237e-01_f32, + 8.3146961230e-01_f32, + ], + [ + -7.0710678119e-01_f32, + 9.8078528040e-01_f32, + -3.8268343237e-01_f32, + -5.5557023302e-01_f32, + 1.0000000000e+00_f32, + -5.5557023302e-01_f32, + -3.8268343237e-01_f32, + 9.8078528040e-01_f32, + -7.0710678119e-01_f32, + -1.9509032202e-01_f32, + 9.2387953251e-01_f32, + -8.3146961230e-01_f32, + -2.4499125789e-15_f32, + 8.3146961230e-01_f32, + -9.2387953251e-01_f32, + 1.9509032202e-01_f32, + ], + [ + -7.0710678119e-01_f32, + 1.9509032202e-01_f32, + 3.8268343237e-01_f32, + -8.3146961230e-01_f32, + 1.0000000000e+00_f32, + -8.3146961230e-01_f32, + 3.8268343237e-01_f32, + 1.9509032202e-01_f32, + -7.0710678119e-01_f32, + 9.8078528040e-01_f32, + -9.2387953251e-01_f32, + 5.5557023302e-01_f32, + -9.8033641995e-16_f32, + -5.5557023302e-01_f32, + 9.2387953251e-01_f32, + -9.8078528040e-01_f32, + ], + [ + 7.0710678119e-01_f32, + -8.3146961230e-01_f32, + 9.2387953251e-01_f32, + -9.8078528040e-01_f32, + 1.0000000000e+00_f32, + -9.8078528040e-01_f32, + 9.2387953251e-01_f32, + -8.3146961230e-01_f32, + 7.0710678119e-01_f32, + -5.5557023302e-01_f32, + 3.8268343237e-01_f32, + -1.9509032202e-01_f32, + -2.6948419388e-15_f32, + 1.9509032202e-01_f32, + -3.8268343237e-01_f32, + 5.5557023302e-01_f32, + ], +]; + +/// Sampling frequency of the SBC bitstream. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SamplingFrequency { + /// 16 000 Hz + Freq16k, + /// 32 000 Hz + Freq32k, + /// 44 100 Hz + Freq44k1, + /// 48 000 Hz + Freq48k, +} + +impl SamplingFrequency { + /// Returns sampling frequency in Hz. + #[inline] + #[must_use] + pub const fn as_hz(self) -> u32 { + match self { + Self::Freq16k => 16_000, + Self::Freq32k => 32_000, + Self::Freq44k1 => 44_100, + Self::Freq48k => 48_000, + } + } + + /// Derives sampling frequency from Hz. + pub fn from_hz(hz: u32) -> Result { + match hz { + 16_000 => Ok(Self::Freq16k), + 32_000 => Ok(Self::Freq32k), + 44_100 => Ok(Self::Freq44k1), + 48_000 => Ok(Self::Freq48k), + _ => Err(Error::InvalidSampleRate(hz)), + } + } + + /// Returns the 2-bit header code. + #[inline] + #[must_use] + pub const fn code(self) -> u8 { + match self { + Self::Freq16k => 0b00, + Self::Freq32k => 0b01, + Self::Freq44k1 => 0b10, + Self::Freq48k => 0b11, + } + } + + /// Index into offset tables (0 to 3). + #[inline] + #[must_use] + pub const fn table_index(self) -> usize { + match self { + Self::Freq16k => 0, + Self::Freq32k => 1, + Self::Freq44k1 => 2, + Self::Freq48k => 3, + } + } +} + +/// Number of blocks per SBC frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BlockCount { + /// 4 blocks + Blocks4, + /// 8 blocks + Blocks8, + /// 12 blocks + Blocks12, + /// 16 blocks + Blocks16, + /// 15 blocks (mSBC wideband speech) + Blocks15, +} + +impl BlockCount { + /// Returns integer block count. + #[inline] + #[must_use] + pub const fn count(self) -> usize { + match self { + Self::Blocks4 => 4, + Self::Blocks8 => 8, + Self::Blocks12 => 12, + Self::Blocks16 => 16, + Self::Blocks15 => 15, + } + } + + /// Derives block count from integer. + pub fn from_count(count: usize) -> Result { + match count { + 4 => Ok(Self::Blocks4), + 8 => Ok(Self::Blocks8), + 12 => Ok(Self::Blocks12), + 16 => Ok(Self::Blocks16), + 15 => Ok(Self::Blocks15), + _ => Err(Error::InvalidBlockCount(count)), + } + } + + /// Returns 2-bit header code. + #[inline] + #[must_use] + pub const fn code(self) -> u8 { + match self { + Self::Blocks4 => 0b00, + Self::Blocks8 => 0b01, + Self::Blocks12 => 0b10, + Self::Blocks16 | Self::Blocks15 => 0b11, + } + } +} + +/// Channel mode of the SBC bitstream. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChannelMode { + /// 1 channel (Mono) + Mono, + /// 2 channels with independent bit allocation + DualChannel, + /// 2 channels with shared bit allocation + Stereo, + /// 2 channels with shared bit allocation and joint mid/side subbands + JointStereo, +} + +impl ChannelMode { + /// Returns number of audio channels. + #[inline] + #[must_use] + pub const fn channels(self) -> usize { + match self { + Self::Mono => 1, + Self::DualChannel | Self::Stereo | Self::JointStereo => 2, + } + } + + /// Returns 2-bit header code. + #[inline] + #[must_use] + pub const fn code(self) -> u8 { + match self { + Self::Mono => 0b00, + Self::DualChannel => 0b01, + Self::Stereo => 0b10, + Self::JointStereo => 0b11, + } + } +} + +/// Bit allocation method. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum AllocationMethod { + /// Psychoacoustic loudness allocation + #[default] + Loudness, + /// Signal-to-noise ratio allocation + Snr, +} + +impl AllocationMethod { + /// Returns 1-bit header code. + #[inline] + #[must_use] + pub const fn code(self) -> u8 { + match self { + Self::Loudness => 0, + Self::Snr => 1, + } + } +} + +/// Number of subbands. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Subbands { + /// 4 subbands + Subbands4, + /// 8 subbands + Subbands8, +} + +impl Subbands { + /// Returns number of subbands as integer. + #[inline] + #[must_use] + pub const fn count(self) -> usize { + match self { + Self::Subbands4 => 4, + Self::Subbands8 => 8, + } + } + + /// Derives Subbands from integer. + pub fn from_count(count: usize) -> Result { + match count { + 4 => Ok(Self::Subbands4), + 8 => Ok(Self::Subbands8), + _ => Err(Error::InvalidSubbands(count)), + } + } + + /// Returns 1-bit header code. + #[inline] + #[must_use] + pub const fn code(self) -> u8 { + match self { + Self::Subbands4 => 0, + Self::Subbands8 => 1, + } + } +} + +/// Parsed header of an SBC audio frame. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Header { + /// Syncword byte (`0x9C` or `0xAD`). + pub syncword: u8, + /// Sampling frequency. + pub sampling_frequency: SamplingFrequency, + /// Number of blocks. + pub blocks: BlockCount, + /// Channel mode. + pub channel_mode: ChannelMode, + /// Allocation method. + pub allocation_method: AllocationMethod, + /// Number of subbands. + pub subbands: Subbands, + /// Bitpool size (1 to 255). + pub bitpool: u8, + /// Stored CRC-8 parity check word. + pub crc_check: u8, + /// Joint stereo flags for subbands 0..subbands-1. + pub join: [bool; 8], +} + +impl Header { + /// Parses an SBC frame header from a byte slice. + pub fn parse(src: &[u8]) -> Result { + if src.len() < 4 { + return Err(Error::TruncatedFrame { expected: 4, actual: src.len() }); + } + let syncword = src[0]; + if syncword == SYNCWORD_MSBC { + let crc_check = src[3]; + return Ok(Self { + syncword, + sampling_frequency: SamplingFrequency::Freq16k, + blocks: BlockCount::Blocks15, + channel_mode: ChannelMode::Mono, + allocation_method: AllocationMethod::Loudness, + subbands: Subbands::Subbands8, + bitpool: 26, + crc_check, + join: [false; 8], + }); + } + if syncword != SYNCWORD_SBC { + return Err(Error::InvalidSyncword(syncword)); + } + let b1 = src[1]; + let freq_code = (b1 >> 6) & 3; + let blocks_code = (b1 >> 4) & 3; + let mode_code = (b1 >> 2) & 3; + let alloc_code = (b1 >> 1) & 1; + let subbands_code = b1 & 1; + + let sampling_frequency = match freq_code { + 0 => SamplingFrequency::Freq16k, + 1 => SamplingFrequency::Freq32k, + 2 => SamplingFrequency::Freq44k1, + _ => SamplingFrequency::Freq48k, + }; + let blocks = match blocks_code { + 0 => BlockCount::Blocks4, + 1 => BlockCount::Blocks8, + 2 => BlockCount::Blocks12, + _ => BlockCount::Blocks16, + }; + let channel_mode = match mode_code { + 0 => ChannelMode::Mono, + 1 => ChannelMode::DualChannel, + 2 => ChannelMode::Stereo, + _ => ChannelMode::JointStereo, + }; + let allocation_method = if alloc_code == 0 { AllocationMethod::Loudness } else { AllocationMethod::Snr }; + let subbands = if subbands_code == 0 { Subbands::Subbands4 } else { Subbands::Subbands8 }; + let bitpool = src[2]; + let crc_check = src[3]; + + let max_bitpool = match channel_mode { + ChannelMode::Mono | ChannelMode::DualChannel => 16 * subbands.count(), + ChannelMode::Stereo | ChannelMode::JointStereo => 32 * subbands.count(), + }; + if bitpool == 0 || (bitpool as usize) > max_bitpool { + return Err(Error::InvalidBitpool(bitpool)); + } + + let mut join = [false; 8]; + if channel_mode == ChannelMode::JointStereo && src.len() >= 5 { + let join_byte = src[4]; + let sb_count = subbands.count(); + for sb in 0..(sb_count.saturating_sub(1)) { + let bit_shift = 7 - (sb as u8); + join[sb] = ((join_byte >> bit_shift) & 1) != 0; + } + } + + Ok(Self { syncword, sampling_frequency, blocks, channel_mode, allocation_method, subbands, bitpool, crc_check, join }) + } + + /// Total length of the frame in bytes (Section 12.9). + #[must_use] + pub fn frame_length(&self) -> usize { + if self.syncword == SYNCWORD_MSBC { + return 57; + } + let nrof_subbands = self.subbands.count(); + let nrof_channels = self.channel_mode.channels(); + let nrof_blocks = self.blocks.count(); + let bitpool = self.bitpool as usize; + + let base = 4 + (4 * nrof_subbands * nrof_channels) / 8; + match self.channel_mode { + ChannelMode::Mono | ChannelMode::DualChannel => base + (nrof_blocks * nrof_channels * bitpool).div_ceil(8), + ChannelMode::Stereo => base + (nrof_blocks * bitpool).div_ceil(8), + ChannelMode::JointStereo => base + (nrof_subbands + nrof_blocks * bitpool).div_ceil(8), + } + } + + /// Number of audio samples per channel produced by this frame. + #[inline] + #[must_use] + pub const fn samples_per_frame(&self) -> usize { + self.blocks.count() * self.subbands.count() + } + + /// Number of audio channels. + #[inline] + #[must_use] + pub const fn channels(&self) -> usize { + self.channel_mode.channels() + } + + /// Sampling rate in Hz. + #[inline] + #[must_use] + pub const fn sample_rate(&self) -> u32 { + self.sampling_frequency.as_hz() + } + + /// Bit rate of the stream in bits per second (Section 12.9). + #[must_use] + pub fn bit_rate_bps(&self) -> u32 { + let flen = self.frame_length() as u64; + let fs = self.sample_rate() as u64; + let sub = self.subbands.count() as u64; + let blk = self.blocks.count() as u64; + let bps = (8 * flen * fs) / (sub * blk); + bps as u32 + } +} + +/// Information about a decoded SBC stream. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StreamInfo { + /// Sample rate in Hz. + pub sample_rate: u32, + /// Channel count (1 or 2). + pub channels: usize, + /// Channel mode. + pub channel_mode: ChannelMode, + /// Block count. + pub blocks: usize, + /// Subband count. + pub subbands: usize, + /// Bitpool setting. + pub bitpool: u8, + /// Allocation method. + pub allocation_method: AllocationMethod, +} + +/// Errors encountered in SBC operations. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// Invalid SBC syncword. + #[error("invalid SBC syncword: {0:#04x}")] + InvalidSyncword(u8), + /// Frame truncated before complete read. + #[error("truncated frame: expected {expected} bytes, got {actual}")] + TruncatedFrame { + /// Expected byte length. + expected: usize, + /// Actual available byte length. + actual: usize, + }, + /// CRC-8 verification mismatch. + #[error("CRC-8 check failed: computed {computed:#04x}, frame header had {stored:#04x}")] + CrcMismatch { + /// Computed CRC-8 value. + computed: u8, + /// Stored CRC-8 in frame header. + stored: u8, + }, + /// Unsupported channel count. + #[error("unsupported channel count: {0} (must be 1 or 2)")] + InvalidChannels(usize), + /// Unsupported sample rate. + #[error("unsupported sample rate: {0} Hz (must be 16000, 32000, 44100, or 48000 Hz)")] + InvalidSampleRate(u32), + /// Unsupported block count. + #[error("unsupported block count: {0} (must be 4, 8, 12, or 16)")] + InvalidBlockCount(usize), + /// Unsupported subbands count. + #[error("unsupported subband count: {0} (must be 4 or 8)")] + InvalidSubbands(usize), + /// Invalid bitpool value. + #[error("invalid bitpool value: {0}")] + InvalidBitpool(u8), + /// Input exceeds safe maximum processing limit. + #[error("input exceeds safe maximum processing limit")] + InputTooLarge, + /// Memory allocation failed. + #[error("memory allocation failed")] + AllocationFailed, +} + +/// Computes CRC-8 with generator polynomial `0x1D` and initial state `0x0F` (Section 12.6.1.1). +pub fn crc8(bits: impl IntoIterator) -> u8 { + let mut crc: u8 = 0x0F; + for bit in bits { + let feedback = (crc >> 7) ^ (if bit { 1 } else { 0 }); + crc = crc.wrapping_shl(1) ^ (if feedback != 0 { 0x1D } else { 0 }); + } + crc +} + +struct BitReader<'a> { + data: &'a [u8], + byte_pos: usize, + bit_pos: u8, +} + +impl<'a> BitReader<'a> { + fn new(data: &'a [u8]) -> Self { + Self { data, byte_pos: 0, bit_pos: 7 } + } + + fn read_bits(&mut self, n: usize) -> Option { + if n == 0 { + return Some(0); + } + if n > 32 { + return None; + } + let mut val = 0u32; + for _ in 0..n { + if self.byte_pos >= self.data.len() { + return None; + } + let bit = (self.data[self.byte_pos] >> self.bit_pos) & 1; + val = (val << 1) | u32::from(bit); + if self.bit_pos == 0 { + self.bit_pos = 7; + self.byte_pos = self.byte_pos.saturating_add(1); + } else { + self.bit_pos -= 1; + } + } + Some(val) + } +} + +struct BitWriter { + bytes: Vec, + cur_byte: u8, + bit_pos: u8, +} + +impl BitWriter { + fn with_capacity(cap: usize) -> Result { + let mut bytes = Vec::new(); + bytes.try_reserve(cap).map_err(|_| Error::AllocationFailed)?; + Ok(Self { bytes, cur_byte: 0, bit_pos: 7 }) + } + + fn write_bits(&mut self, val: u32, n: usize) -> Result<(), Error> { + if n == 0 { + return Ok(()); + } + for i in (0..n).rev() { + let bit = ((val >> i) & 1) as u8; + self.cur_byte |= bit << self.bit_pos; + if self.bit_pos == 0 { + self.bytes.try_reserve(1).map_err(|_| Error::AllocationFailed)?; + self.bytes.push(self.cur_byte); + self.cur_byte = 0; + self.bit_pos = 7; + } else { + self.bit_pos -= 1; + } + } + Ok(()) + } + + fn flush(&mut self) -> Result<(), Error> { + if self.bit_pos < 7 { + self.bytes.try_reserve(1).map_err(|_| Error::AllocationFailed)?; + self.bytes.push(self.cur_byte); + self.cur_byte = 0; + self.bit_pos = 7; + } + Ok(()) + } + + fn finish(mut self) -> Result, Error> { + self.flush()?; + Ok(self.bytes) + } +} + +fn compute_header_crc( + b1: u8, + b2: u8, + channel_mode: ChannelMode, + subbands: usize, + channels: usize, + join: &[bool; 8], + scale_factors: &[[u8; 8]; 2], +) -> u8 { + let mut crc: u8 = 0x0F; + let mut feed_bit = |bit: bool| { + let feedback = (crc >> 7) ^ (if bit { 1 } else { 0 }); + crc = crc.wrapping_shl(1) ^ (if feedback != 0 { 0x1D } else { 0 }); + }; + for i in (0..8).rev() { + feed_bit(((b1 >> i) & 1) != 0); + } + for i in (0..8).rev() { + feed_bit(((b2 >> i) & 1) != 0); + } + if channel_mode == ChannelMode::JointStereo { + for sb in 0..(subbands.saturating_sub(1)) { + feed_bit(join[sb]); + } + feed_bit(false); // RFA + } + for ch in 0..channels { + for sb in 0..subbands { + let sf = scale_factors[ch][sb]; + for i in (0..4).rev() { + feed_bit(((sf >> i) & 1) != 0); + } + } + } + crc +} + +fn compute_bit_allocation( + subbands: usize, + channels: usize, + channel_mode: ChannelMode, + freq_idx: usize, + alloc_method: AllocationMethod, + bitpool: u16, + scale_factors: &[[u8; 8]; 2], + bits: &mut [[u8; 8]; 2], +) { + if channel_mode == ChannelMode::Mono || channel_mode == ChannelMode::DualChannel { + for ch in 0..channels { + let mut bitneed = [0i16; 8]; + if alloc_method == AllocationMethod::Snr { + for sb in 0..subbands { + bitneed[sb] = i16::from(scale_factors[ch][sb]); + } + } else { + for sb in 0..subbands { + let sf = scale_factors[ch][sb]; + if sf == 0 { + bitneed[sb] = -5; + } else { + let off = if subbands == 4 { OFFSET4[freq_idx][sb] as i16 } else { OFFSET8[freq_idx][sb] as i16 }; + let loudness = (sf as i16) - off; + bitneed[sb] = if loudness > 0 { loudness / 2 } else { loudness }; + } + } + } + + let mut max_bitneed = 0i16; + for sb in 0..subbands { + if bitneed[sb] > max_bitneed { + max_bitneed = bitneed[sb]; + } + } + + let mut bitcount = 0u16; + let mut slicecount = 0u16; + let mut bitslice = max_bitneed + 1; + + loop { + bitslice -= 1; + bitcount = bitcount.saturating_add(slicecount); + slicecount = 0; + for sb in 0..subbands { + let bn = bitneed[sb]; + if bn > bitslice + 1 && bn < bitslice + 16 { + slicecount = slicecount.saturating_add(1); + } else if bn == bitslice + 1 { + slicecount = slicecount.saturating_add(2); + } + } + if bitcount.saturating_add(slicecount) >= bitpool || bitslice <= -32 { + break; + } + } + + if bitcount.saturating_add(slicecount) == bitpool { + bitcount = bitcount.saturating_add(slicecount); + bitslice -= 1; + } + + for sb in 0..subbands { + let bn = bitneed[sb]; + if bn < bitslice + 2 { + bits[ch][sb] = 0; + } else { + let b = (bn - bitslice).clamp(0, 16); + bits[ch][sb] = b as u8; + } + } + + let mut sb = 0; + while bitcount < bitpool && sb < subbands { + if bits[ch][sb] >= 2 && bits[ch][sb] < 16 { + bits[ch][sb] = bits[ch][sb].saturating_add(1); + bitcount = bitcount.saturating_add(1); + } else if bitneed[sb] == bitslice + 1 && bitpool > bitcount.saturating_add(1) { + bits[ch][sb] = 2; + bitcount = bitcount.saturating_add(2); + } + sb += 1; + } + + let mut sb = 0; + while bitcount < bitpool && sb < subbands { + if bits[ch][sb] < 16 { + bits[ch][sb] = bits[ch][sb].saturating_add(1); + bitcount = bitcount.saturating_add(1); + } + sb += 1; + } + } + } else { + let mut bitneed = [[0i16; 8]; 2]; + if alloc_method == AllocationMethod::Snr { + for ch in 0..2 { + for sb in 0..subbands { + bitneed[ch][sb] = i16::from(scale_factors[ch][sb]); + } + } + } else { + for ch in 0..2 { + for sb in 0..subbands { + let sf = scale_factors[ch][sb]; + if sf == 0 { + bitneed[ch][sb] = -5; + } else { + let off = if subbands == 4 { OFFSET4[freq_idx][sb] as i16 } else { OFFSET8[freq_idx][sb] as i16 }; + let loudness = (sf as i16) - off; + bitneed[ch][sb] = if loudness > 0 { loudness / 2 } else { loudness }; + } + } + } + } + + let mut max_bitneed = 0i16; + for ch in 0..2 { + for sb in 0..subbands { + if bitneed[ch][sb] > max_bitneed { + max_bitneed = bitneed[ch][sb]; + } + } + } + + let mut bitcount = 0u16; + let mut slicecount = 0u16; + let mut bitslice = max_bitneed + 1; + + loop { + bitslice -= 1; + bitcount = bitcount.saturating_add(slicecount); + slicecount = 0; + for ch in 0..2 { + for sb in 0..subbands { + let bn = bitneed[ch][sb]; + if bn > bitslice + 1 && bn < bitslice + 16 { + slicecount = slicecount.saturating_add(1); + } else if bn == bitslice + 1 { + slicecount = slicecount.saturating_add(2); + } + } + } + if bitcount.saturating_add(slicecount) >= bitpool || bitslice <= -32 { + break; + } + } + + if bitcount.saturating_add(slicecount) == bitpool { + bitcount = bitcount.saturating_add(slicecount); + bitslice -= 1; + } + + for ch in 0..2 { + for sb in 0..subbands { + let bn = bitneed[ch][sb]; + if bn < bitslice + 2 { + bits[ch][sb] = 0; + } else { + let b = (bn - bitslice).clamp(0, 16); + bits[ch][sb] = b as u8; + } + } + } + + let mut ch = 0; + let mut sb = 0; + while bitcount < bitpool && sb < subbands { + if bits[ch][sb] >= 2 && bits[ch][sb] < 16 { + bits[ch][sb] = bits[ch][sb].saturating_add(1); + bitcount = bitcount.saturating_add(1); + } else if bitneed[ch][sb] == bitslice + 1 && bitpool > bitcount.saturating_add(1) { + bits[ch][sb] = 2; + bitcount = bitcount.saturating_add(2); + } + if ch == 1 { + ch = 0; + sb += 1; + } else { + ch = 1; + } + } + + let mut ch = 0; + let mut sb = 0; + while bitcount < bitpool && sb < subbands { + if bits[ch][sb] < 16 { + bits[ch][sb] = bits[ch][sb].saturating_add(1); + bitcount = bitcount.saturating_add(1); + } + if ch == 1 { + ch = 0; + sb += 1; + } else { + ch = 1; + } + } + } +} + +fn synth_subbands_4(v: &mut [f32; 160], s: &[f32; 8], out: &mut [i16; 8]) { + v.copy_within(0..72, 8); + for k in 0..8 { + let mut sum = 0.0f32; + for i in 0..4 { + sum += SYNTH_COS_4[k][i] * s[i]; + } + v[k] = sum; + } + let mut u = [0.0f32; 40]; + for i in 0..5 { + for j in 0..4 { + u[i * 8 + j] = v[i * 16 + j]; + u[i * 8 + 4 + j] = v[i * 16 + 12 + j]; + } + } + for j in 0..4 { + let mut sum = 0.0f32; + for i in 0..10 { + sum += u[j + 4 * i] * SYNTH_D_4[j + 4 * i]; + } + let clamped = sum.clamp(-32768.0, 32767.0).round() as i32; + out[j] = clamped as i16; + } +} + +fn synth_subbands_8(v: &mut [f32; 160], s: &[f32; 8], out: &mut [i16; 8]) { + v.copy_within(0..144, 16); + for k in 0..16 { + let mut sum = 0.0f32; + for i in 0..8 { + sum += SYNTH_COS_8[k][i] * s[i]; + } + v[k] = sum; + } + let mut u = [0.0f32; 80]; + for i in 0..5 { + for j in 0..8 { + u[i * 16 + j] = v[i * 32 + j]; + u[i * 16 + 8 + j] = v[i * 32 + 24 + j]; + } + } + for j in 0..8 { + let mut sum = 0.0f32; + for i in 0..10 { + sum += u[j + 8 * i] * SYNTH_D_8[j + 8 * i]; + } + let clamped = sum.clamp(-32768.0, 32767.0).round() as i32; + out[j] = clamped as i16; + } +} + +fn analysis_subbands_4(x: &mut [f32; 80], pcm_in: &[i16], s_out: &mut [f32; 8]) { + x.copy_within(0..36, 4); + for i in 0..4 { + x[3 - i] = pcm_in[i] as f32; + } + let mut y = [0.0f32; 8]; + for i in 0..8 { + let mut sum = 0.0f32; + for k in 0..5 { + let idx = i + k * 8; + sum += PROTO_4_40[idx] * x[idx]; + } + y[i] = sum; + } + for i in 0..4 { + let mut sum = 0.0f32; + for k in 0..8 { + sum += ANALYSIS_COS_4[i][k] * y[k]; + } + s_out[i] = sum; + } +} + +fn analysis_subbands_8(x: &mut [f32; 80], pcm_in: &[i16], s_out: &mut [f32; 8]) { + x.copy_within(0..72, 8); + for i in 0..8 { + x[7 - i] = pcm_in[i] as f32; + } + let mut y = [0.0f32; 16]; + for i in 0..16 { + let mut sum = 0.0f32; + for k in 0..5 { + let idx = i + k * 16; + sum += PROTO_8_80[idx] * x[idx]; + } + y[i] = sum; + } + for i in 0..8 { + let mut sum = 0.0f32; + for k in 0..16 { + sum += ANALYSIS_COS_8[i][k] * y[k]; + } + s_out[i] = sum; + } +} + +fn calculate_scalefactor(max_abs: f32) -> u8 { + let v = max_abs.abs() as u32; + if v == 0 { + return 0; + } + let mut sf = 0u8; + while sf < 15 && (1u32 << (sf + 1)) <= v { + sf += 1; + } + sf +} + +/// SBC audio decoder. +#[derive(Debug, Clone)] +pub struct Decoder { + v: [[f32; 160]; 2], +} + +impl Default for Decoder { + fn default() -> Self { + Self { v: [[0.0f32; 160]; 2] } + } +} + +impl Decoder { + /// Creates a new SBC decoder. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Resets synthesis filterbank state. + pub fn reset(&mut self) { + self.v = [[0.0f32; 160]; 2]; + } + + /// Decodes a single SBC frame from `packet`, appending linear PCM samples to `dst`. + /// Returns the number of bytes consumed from `packet`. + pub fn decode_frame(&mut self, packet: &[u8], dst: &mut Vec) -> Result { + let header = Header::parse(packet)?; + let frame_len = header.frame_length(); + if packet.len() < frame_len { + return Err(Error::TruncatedFrame { expected: frame_len, actual: packet.len() }); + } + + let channels = header.channels(); + let subbands = header.subbands.count(); + let blocks = header.blocks.count(); + + let mut reader = BitReader::new(&packet[4..frame_len]); + + let mut join = [false; 8]; + if header.channel_mode == ChannelMode::JointStereo { + for sb in 0..(subbands.saturating_sub(1)) { + join[sb] = reader.read_bits(1).unwrap_or(0) != 0; + } + let _ = reader.read_bits(1); // RFA + } + + let mut scale_factors = [[0u8; 8]; 2]; + for ch in 0..channels { + for sb in 0..subbands { + scale_factors[ch][sb] = (reader.read_bits(4).unwrap_or(0) & 0x0F) as u8; + } + } + + // Verify CRC-8 + let expected_crc = if header.syncword == SYNCWORD_MSBC { + compute_header_crc(0x00, 0x00, ChannelMode::Mono, 8, 1, &[false; 8], &scale_factors) + } else { + compute_header_crc(packet[1], packet[2], header.channel_mode, subbands, channels, &join, &scale_factors) + }; + if expected_crc != header.crc_check { + return Err(Error::CrcMismatch { computed: expected_crc, stored: header.crc_check }); + } + + let mut bits = [[0u8; 8]; 2]; + compute_bit_allocation( + subbands, + channels, + header.channel_mode, + header.sampling_frequency.table_index(), + header.allocation_method, + u16::from(header.bitpool), + &scale_factors, + &mut bits, + ); + + let mut levels = [[0u32; 8]; 2]; + let mut scalefactors = [[0.0f32; 8]; 2]; + for ch in 0..channels { + for sb in 0..subbands { + levels[ch][sb] = (1u32 << bits[ch][sb]).saturating_sub(1); + scalefactors[ch][sb] = (1u32 << (u32::from(scale_factors[ch][sb]) + 1)) as f32; + } + } + + // Subband sample reconstruction + let mut sb_sample = [[[0.0f32; 8]; 2]; 16]; + for blk in 0..blocks { + for ch in 0..channels { + for sb in 0..subbands { + let lev = levels[ch][sb]; + if lev > 0 { + let raw_s = reader.read_bits(bits[ch][sb] as usize).unwrap_or(0); + let norm = ((raw_s as f32 * 2.0 + 1.0) / (lev as f32)) - 1.0; + sb_sample[blk][ch][sb] = scalefactors[ch][sb] * norm; + } else { + sb_sample[blk][ch][sb] = 0.0; + } + } + } + } + + // Joint stereo mid/side reconstruction + if header.channel_mode == ChannelMode::JointStereo { + for blk in 0..blocks { + for sb in 0..subbands { + if join[sb] { + let mid = sb_sample[blk][0][sb] + sb_sample[blk][1][sb]; + let side = sb_sample[blk][0][sb] - sb_sample[blk][1][sb]; + sb_sample[blk][0][sb] = mid; + sb_sample[blk][1][sb] = side; + } + } + } + } + + // Synthesis filterbank + let total_samples = blocks * subbands * channels; + dst.try_reserve(total_samples).map_err(|_| Error::AllocationFailed)?; + + let mut block_samples = [[[0i16; 8]; 2]; 16]; + for blk in 0..blocks { + for ch in 0..channels { + if subbands == 4 { + synth_subbands_4(&mut self.v[ch], &sb_sample[blk][ch], &mut block_samples[blk][ch]); + } else { + synth_subbands_8(&mut self.v[ch], &sb_sample[blk][ch], &mut block_samples[blk][ch]); + } + } + for sb in 0..subbands { + for ch in 0..channels { + dst.push(block_samples[blk][ch][sb]); + } + } + } + + Ok(frame_len) + } + + /// Decodes an entire buffer of concatenated SBC frames into interleaved 16-bit PCM. + pub fn decode(&mut self, src: &[u8], dst: &mut Vec) -> Result<(), Error> { + if src.len() > MAX_INPUT_BYTES { + return Err(Error::InputTooLarge); + } + let mut offset = 0; + while offset < src.len() { + let consumed = self.decode_frame(&src[offset..], dst)?; + if consumed == 0 { + break; + } + offset = offset.saturating_add(consumed); + } + Ok(()) + } +} + +/// SBC audio encoder. +#[derive(Debug, Clone)] +pub struct Encoder { + sample_rate: u32, + channels: usize, + channel_mode: ChannelMode, + blocks: BlockCount, + subbands: Subbands, + bitpool: u8, + allocation_method: AllocationMethod, + x: [[f32; 80]; 2], +} + +impl Encoder { + /// Creates a new SBC encoder with custom configuration. + pub fn new( + sample_rate: u32, + channels: usize, + blocks: usize, + subbands: usize, + bitpool: u8, + allocation_method: AllocationMethod, + ) -> Result { + if channels != 1 && channels != 2 { + return Err(Error::InvalidChannels(channels)); + } + let freq = SamplingFrequency::from_hz(sample_rate)?; + let block_cnt = BlockCount::from_count(blocks)?; + let subband_cnt = Subbands::from_count(subbands)?; + let channel_mode = if channels == 1 { ChannelMode::Mono } else { ChannelMode::JointStereo }; + + let max_bitpool = match channel_mode { + ChannelMode::Mono | ChannelMode::DualChannel => 16 * subband_cnt.count(), + ChannelMode::Stereo | ChannelMode::JointStereo => 32 * subband_cnt.count(), + }; + if bitpool == 0 || (bitpool as usize) > max_bitpool { + return Err(Error::InvalidBitpool(bitpool)); + } + + if block_cnt == BlockCount::Blocks15 + && (sample_rate != 16_000 || channels != 1 || subbands != 8 || bitpool != 26 || allocation_method != AllocationMethod::Loudness) + { + return Err(Error::InvalidBlockCount(15)); + } + + Ok(Self { + sample_rate: freq.as_hz(), + channels, + channel_mode, + blocks: block_cnt, + subbands: subband_cnt, + bitpool, + allocation_method, + x: [[0.0f32; 80]; 2], + }) + } + + /// Resets analysis filterbank state. + pub fn reset(&mut self) { + self.x = [[0.0f32; 80]; 2]; + } + + /// Encodes a single frame of linear PCM samples into `dst`. + /// `pcm` must contain `blocks * subbands * channels` interleaved 16-bit samples. + pub fn encode_frame(&mut self, pcm: &[i16], dst: &mut Vec) -> Result<(), Error> { + let subbands = self.subbands.count(); + let blocks = self.blocks.count(); + let expected_samples = blocks * subbands * self.channels; + if pcm.len() < expected_samples { + return Err(Error::TruncatedFrame { expected: expected_samples, actual: pcm.len() }); + } + + // Polyphase analysis filterbank + let mut sb_samples = [[[0.0f32; 8]; 2]; 16]; + for blk in 0..blocks { + for ch in 0..self.channels { + let mut channel_buf = [0i16; 8]; + for i in 0..subbands { + let idx = (blk * subbands + i) * self.channels + ch; + channel_buf[i] = pcm[idx]; + } + if subbands == 4 { + analysis_subbands_4(&mut self.x[ch], &channel_buf, &mut sb_samples[blk][ch]); + } else { + analysis_subbands_8(&mut self.x[ch], &channel_buf, &mut sb_samples[blk][ch]); + } + } + } + + // Scale factors and joint stereo decisions + let mut scale_factors = [[0u8; 8]; 2]; + let mut join = [false; 8]; + + if self.channels == 2 && self.channel_mode == ChannelMode::JointStereo { + for sb in 0..subbands { + let mut max_l = 0.0f32; + let mut max_r = 0.0f32; + for blk in 0..blocks { + let al = sb_samples[blk][0][sb].abs(); + let ar = sb_samples[blk][1][sb].abs(); + if al > max_l { + max_l = al; + } + if ar > max_r { + max_r = ar; + } + } + let sf_l = calculate_scalefactor(max_l); + let sf_r = calculate_scalefactor(max_r); + + if sb < subbands.saturating_sub(1) { + let mut max_mid = 0.0f32; + let mut max_side = 0.0f32; + for blk in 0..blocks { + let mid = (sb_samples[blk][0][sb] + sb_samples[blk][1][sb]) * 0.5; + let side = (sb_samples[blk][0][sb] - sb_samples[blk][1][sb]) * 0.5; + let am = mid.abs(); + let asd = side.abs(); + if am > max_mid { + max_mid = am; + } + if asd > max_side { + max_side = asd; + } + } + let sf_mid = calculate_scalefactor(max_mid); + let sf_side = calculate_scalefactor(max_side); + + if u16::from(sf_l) + u16::from(sf_r) > u16::from(sf_mid) + u16::from(sf_side) { + join[sb] = true; + scale_factors[0][sb] = sf_mid; + scale_factors[1][sb] = sf_side; + for blk in 0..blocks { + let mid = (sb_samples[blk][0][sb] + sb_samples[blk][1][sb]) * 0.5; + let side = (sb_samples[blk][0][sb] - sb_samples[blk][1][sb]) * 0.5; + sb_samples[blk][0][sb] = mid; + sb_samples[blk][1][sb] = side; + } + continue; + } + } + + scale_factors[0][sb] = sf_l; + scale_factors[1][sb] = sf_r; + } + } else { + for ch in 0..self.channels { + for sb in 0..subbands { + let mut max_val = 0.0f32; + for blk in 0..blocks { + let a = sb_samples[blk][ch][sb].abs(); + if a > max_val { + max_val = a; + } + } + scale_factors[ch][sb] = calculate_scalefactor(max_val); + } + } + } + + // Bit allocation + let freq = SamplingFrequency::from_hz(self.sample_rate)?; + let mut bits = [[0u8; 8]; 2]; + compute_bit_allocation( + subbands, + self.channels, + self.channel_mode, + freq.table_index(), + self.allocation_method, + u16::from(self.bitpool), + &scale_factors, + &mut bits, + ); + + // Quantization + let mut levels = [[0u32; 8]; 2]; + let mut scalefactors = [[0.0f32; 8]; 2]; + for ch in 0..self.channels { + for sb in 0..subbands { + levels[ch][sb] = (1u32 << bits[ch][sb]).saturating_sub(1); + scalefactors[ch][sb] = (1u32 << (u32::from(scale_factors[ch][sb]) + 1)) as f32; + } + } + + let mut quantized = [[[0u32; 8]; 2]; 16]; + for blk in 0..blocks { + for ch in 0..self.channels { + for sb in 0..subbands { + let lev = levels[ch][sb]; + if lev > 0 { + let norm = sb_samples[blk][ch][sb] / scalefactors[ch][sb]; + let val = ((norm + 1.0) * (lev as f32)) * 0.5; + let q = val.floor() as i32; + quantized[blk][ch][sb] = (q.clamp(0, lev as i32)) as u32; + } + } + } + } + + // Frame header bytes + let is_msbc = self.blocks == BlockCount::Blocks15; + let (syncword, b1, b2, crc, flen) = if is_msbc { + let crc = compute_header_crc(0x00, 0x00, ChannelMode::Mono, 8, 1, &[false; 8], &scale_factors); + (SYNCWORD_MSBC, 0x00, 0x00, crc, 57) + } else { + let b1 = (freq.code() << 6) + | (self.blocks.code() << 4) + | (self.channel_mode.code() << 2) + | (self.allocation_method.code() << 1) + | self.subbands.code(); + let b2 = self.bitpool; + let crc = compute_header_crc(b1, b2, self.channel_mode, subbands, self.channels, &join, &scale_factors); + let flen = Header { + syncword: SYNCWORD_SBC, + sampling_frequency: freq, + blocks: self.blocks, + channel_mode: self.channel_mode, + allocation_method: self.allocation_method, + subbands: self.subbands, + bitpool: self.bitpool, + crc_check: crc, + join, + } + .frame_length(); + (SYNCWORD_SBC, b1, b2, crc, flen) + }; + + let mut writer = BitWriter::with_capacity(flen)?; + writer.write_bits(u32::from(syncword), 8)?; + writer.write_bits(u32::from(b1), 8)?; + writer.write_bits(u32::from(b2), 8)?; + writer.write_bits(u32::from(crc), 8)?; + + if self.channel_mode == ChannelMode::JointStereo { + for sb in 0..(subbands.saturating_sub(1)) { + writer.write_bits(if join[sb] { 1 } else { 0 }, 1)?; + } + writer.write_bits(0, 1)?; // RFA + } + + for ch in 0..self.channels { + for sb in 0..subbands { + writer.write_bits(u32::from(scale_factors[ch][sb]), 4)?; + } + } + + for blk in 0..blocks { + for ch in 0..self.channels { + for sb in 0..subbands { + if bits[ch][sb] > 0 { + writer.write_bits(quantized[blk][ch][sb], bits[ch][sb] as usize)?; + } + } + } + } + + let frame_bytes = writer.finish()?; + dst.try_reserve(frame_bytes.len()).map_err(|_| Error::AllocationFailed)?; + dst.extend_from_slice(&frame_bytes); + Ok(()) + } + + /// Encodes a stream of linear PCM samples into concatenated SBC frames. + pub fn encode(&mut self, pcm: &[i16], dst: &mut Vec) -> Result<(), Error> { + if pcm.len() > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } + let frame_samples = self.blocks.count() * self.subbands.count() * self.channels; + if !pcm.len().is_multiple_of(frame_samples) { + return Err(Error::TruncatedFrame { expected: frame_samples, actual: pcm.len() % frame_samples }); + } + let mut offset: usize = 0; + while offset.saturating_add(frame_samples) <= pcm.len() { + self.encode_frame(&pcm[offset..offset + frame_samples], dst)?; + offset = offset.saturating_add(frame_samples); + } + Ok(()) + } +} + +/// Decodes an entire SBC bitstream to 16-bit linear PCM and returns stream info. +pub fn decode(src: &[u8]) -> Result<(Vec, StreamInfo), Error> { + if src.is_empty() { + return Err(Error::TruncatedFrame { expected: 4, actual: 0 }); + } + let header = Header::parse(src)?; + let info = StreamInfo { + sample_rate: header.sample_rate(), + channels: header.channels(), + channel_mode: header.channel_mode, + blocks: header.blocks.count(), + subbands: header.subbands.count(), + bitpool: header.bitpool, + allocation_method: header.allocation_method, + }; + let mut decoder = Decoder::new(); + let mut dst = Vec::new(); + let mut offset = 0; + while offset < src.len() { + let frame_hdr = Header::parse(&src[offset..])?; + if frame_hdr.sample_rate() != info.sample_rate || frame_hdr.channels() != info.channels || frame_hdr.channel_mode != info.channel_mode { + return Err(Error::InvalidSampleRate(frame_hdr.sample_rate())); + } + let consumed = decoder.decode_frame(&src[offset..], &mut dst)?; + if consumed == 0 { + break; + } + offset = offset.saturating_add(consumed); + } + Ok((dst, info)) +} + +/// Encodes 16-bit linear PCM audio into an SBC bitstream using standard high-quality defaults. +pub fn encode(pcm: &[i16], sample_rate: u32, channels: usize, bitpool: u8) -> Result, Error> { + let mut encoder = Encoder::new( + sample_rate, + channels, + 16, // standard 16 blocks + 8, // standard 8 subbands + bitpool, + AllocationMethod::Loudness, + )?; + let mut dst = Vec::new(); + encoder.encode(pcm, &mut dst)?; + Ok(dst) +} diff --git a/crates/audio/src/vmd.rs b/crates/audio/src/vmd.rs new file mode 100644 index 000000000..9e45b1a5c --- /dev/null +++ b/crates/audio/src/vmd.rs @@ -0,0 +1,192 @@ +//! Sierra VMD sound decoder (feature `vmd-decode`): the 8-bit PCM and 16-bit DPCM sound of VMD +//! (Video and Music Data) files, as in Sierra's and Coktel Vision's 1990s games. +//! +//! Clean-room, from the public format description at +//! ("Description of the Sierra Video and Music Data (VMD) Format", Mike Melanson and Vladimir +//! Gneushev). The description gives the coding but not the size of a block; the sizes here are +//! what ffmpeg was seen to expect of files made by this crate's tests: +//! +//! | Sound | Bytes in a block of `n` samples a channel | +//! |---|---| +//! | 8-bit | `n` for each channel, interleaved | +//! | 16-bit | 2 for each channel's first sample, then one code for each further sample, interleaved | +//! +//! The header's frame length is `n`, except in old-style stereo (audio flag 0x8000), where it +//! counts both channels. Old-style 16-bit stereo blocks begin with their first samples like the +//! others, which is what ffmpeg reads; the description says they carry the last block's samples +//! over instead. No such file was at hand to settle it. +//! +//! A [`Decoder`] is made from the 816-byte file header. [`Decoder::decode`] takes a sound +//! frame's flags (from its record in the file's table of contents; `craft_media::vmd` reads it) +//! and its data, and returns interleaved `i16` samples: one block of sound or silence, or, for a +//! frame with a silence mask (the first sound frame of a file), several. 8-bit samples are widened to 16 bits. Blocks do not depend +//! on each other, so decoding can start at any frame. +//! +//! Not decoded: IMA ADPCM sound (audio flag 0x10) and the external codecs of later Coktel Vision +//! files ([`Error::Unsupported`]). +//! +//! Input is treated as hostile: a block is at most 65 535 samples a channel and is decoded only +//! if all of it is there; a frame with a silence mask yields at most 32 blocks (the width of +//! the mask), any other frame as many whole blocks as its data holds. No `unsafe`, no panics. + +#![warn(missing_docs)] + +/// Bytes of the VMD file header a [`Decoder`] is made from. +pub const HEADER_LEN: usize = 816; + +/// Errors from decoding VMD sound. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The header or a frame is not valid. + #[error("invalid VMD sound: {0}")] + Invalid(&'static str), + /// Valid, but not something this decoder handles. + #[error("unsupported VMD sound: {0}")] + Unsupported(&'static str), +} + +/// The steps of the 16-bit coding: a code's low seven bits pick one, its top bit the sign. +const STEPS: [u16; 128] = [ + 0, 8, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 256, 272, 288, 304, 320, 336, 352, 368, 384, 400, 416, 432, 448, 464, + 480, 496, 512, 520, 528, 536, 544, 552, 560, 568, 576, 584, 592, 600, 608, 616, 624, 632, 640, 648, 656, 664, 672, 680, 688, 696, 704, 712, 720, + 728, 736, 744, 752, 760, 768, 776, 784, 792, 800, 808, 816, 824, 832, 840, 848, 856, 864, 872, 880, 888, 896, 904, 912, 920, 928, 936, 944, 952, + 960, 968, 976, 984, 992, 1000, 1008, 1016, 1024, 1088, 1152, 1216, 1280, 1344, 1408, 1472, 1536, 1600, 1664, 1728, 1792, 1856, 1920, 1984, 2048, + 2304, 2560, 2816, 3072, 3328, 3584, 3840, 4096, 5120, 6144, 7168, 8192, 12288, 16384, +]; + +/// A VMD sound decoder. +#[derive(Clone, Debug)] +pub struct Decoder { + sample_rate: u32, + channels: usize, + sixteen_bit: bool, + /// Samples of one block, all channels counted. + block_total: usize, +} + +impl Decoder { + /// A decoder for the file whose header is `header` (its first 816 bytes; more are ignored). + pub fn new(header: &[u8]) -> Result { + let h = header.get(..HEADER_LEN).ok_or(Error::Invalid("the header is shorter than 816 bytes"))?; + let u16_at = |at: usize| u16::from_le_bytes([h[at], h[at + 1]]); + if usize::from(u16_at(0)) != HEADER_LEN - 2 { + return Err(Error::Invalid("not a VMD header")); + } + if u16_at(16) & 0x1000 == 0 || u16_at(804) == 0 { + return Err(Error::Invalid("the file has no sound")); + } + let flags = u16_at(810); + if flags & 0x10 != 0 { + return Err(Error::Unsupported("IMA ADPCM sound")); + } + let length = u16_at(806) as i16; + let frame_length = usize::from(length.unsigned_abs()); + // old-style stereo counts both channels, new-style one + let (channels, block_total) = match flags { + f if f & 0x8000 != 0 => (2, frame_length & !1), + f if f & 0x200 != 0 => (2, frame_length * 2), + _ => (1, frame_length), + }; + Ok(Decoder { sample_rate: u32::from(u16_at(804)), channels, sixteen_bit: length < 0, block_total }) + } + + /// Samples a second. + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + /// 1 or 2. + pub fn channels(&self) -> usize { + self.channels + } + + /// Bits a sample in the file: 8 (PCM) or 16 (DPCM). The decoder returns `i16` for both. + pub fn bits(&self) -> u8 { + if self.sixteen_bit { 16 } else { 8 } + } + + /// Samples of one block for each channel. + pub fn block_samples(&self) -> usize { + self.block_total / self.channels + } + + /// Bytes of one block of sound in a frame. + pub fn block_bytes(&self) -> usize { + if self.sixteen_bit { (self.block_total + self.channels).min(self.block_total * 2) } else { self.block_total } + } + + /// Decode one sound frame: `flags` is the frame's flag byte from its record, `data` the + /// frame data. Returns interleaved samples, [`Decoder::block_samples`] for each channel and + /// block. + /// + /// - flags 1: one block of sound (every whole block, if the frame holds more); + /// - flags 2: a 32-bit mask, then blocks of sound: the sound a player loads ahead at the + /// start of a file. From bit 0 up, a set bit is a block of silence and a clear bit the next + /// block of data, while there is one. ffmpeg plays the silent blocks first instead; + /// the order here is the description's; + /// - flags 3: one block of silence. + /// + /// An empty frame gives no samples. With flags 1, a first block cut short is an error. A part + /// of a block after the last whole one is left out, with flags 1 and 2. + /// + /// The sound of a file is its sound frames decoded in file order and played end to end from + /// the first picture on: see `craft_media::vmd` for how that lines up with the pictures. + pub fn decode(&self, flags: u8, data: &[u8]) -> Result, Error> { + let mut out = Vec::new(); + match flags { + 3 => out.resize(self.block_total, 0), + 1 | 2 if data.is_empty() => {} + 1 => { + // one block; a frame that holds more whole blocks plays them all, as in ffmpeg + self.block(data, &mut out)?; + let size = self.block_bytes(); + if size > 0 { + for more in data[size..].chunks_exact(size) { + self.block(more, &mut out)?; + } + } + } + 2 => { + let (mask, mut data) = data.split_first_chunk::<4>().ok_or(Error::Invalid("the silence mask is cut short"))?; + let mask = u32::from_le_bytes(*mask); + // bit by bit: a set bit is a silent block, a clear one takes the next block of data + // while there is one. The header's buffer count is not needed: game files hold + // one block fewer than it says. + for i in 0..32 { + if mask >> i & 1 == 1 { + out.resize(out.len() + self.block_total, 0); + } else if !data.is_empty() && data.len() >= self.block_bytes() { + self.block(data, &mut out)?; + data = &data[self.block_bytes()..]; + } + } + } + _ => return Err(Error::Unsupported("unknown sound frame flags")), + } + Ok(out) + } + + /// Decode the block at the start of `data` onto `out`. + fn block(&self, data: &[u8], out: &mut Vec) -> Result<(), Error> { + let data = data.get(..self.block_bytes()).ok_or(Error::Invalid("a block of sound is cut short"))?; + if !self.sixteen_bit { + out.extend(data.iter().map(|&b| (i16::from(b) - 0x80) << 8)); + return Ok(()); + } + // each channel's first sample as it is, then a signed step for each further sample + let mut last = [0i32; 2]; + let Some((first, codes)) = data.split_at_checked(self.channels * 2) else { return Ok(()) }; + for (ch, s) in first.as_chunks::<2>().0.iter().enumerate() { + last[ch] = i32::from(i16::from_le_bytes(*s)); + out.push(last[ch] as i16); + } + for (i, &code) in codes.iter().enumerate() { + let ch = i % self.channels; + let step = i32::from(STEPS[usize::from(code & 0x7F)]); + last[ch] = (if code & 0x80 != 0 { last[ch] - step } else { last[ch] + step }).clamp(-32768, 32767); + out.push(last[ch] as i16); + } + Ok(()) + } +} diff --git a/crates/audio/src/vorbis/decoder/bits.rs b/crates/audio/src/vorbis/decoder/bits.rs new file mode 100644 index 000000000..6735d3d3d --- /dev/null +++ b/crates/audio/src/vorbis/decoder/bits.rs @@ -0,0 +1,96 @@ +//! The Vorbis bit reader (Vorbis I §2): bits are taken least significant first from each byte. + +/// Reading past the end of the packet ("end-of-packet", §2.1.8). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Eop; + +pub(super) struct BitReader<'a> { + data: &'a [u8], + /// The position of the next bit. + pos: usize, +} + +impl<'a> BitReader<'a> { + pub(super) fn new(data: &'a [u8]) -> Self { + Self { data, pos: 0 } + } + + /// The bits not yet read. + pub(super) fn remaining(&self) -> usize { + (self.data.len() * 8).saturating_sub(self.pos) + } + + /// Read `n` (at most 32) bits as an unsigned integer. A read that does not fit takes nothing. + pub(super) fn read(&mut self, n: u32) -> Result { + if n == 0 { + return Ok(0); + } + if (n as usize) > self.remaining() { + self.pos = self.data.len() * 8; + return Err(Eop); + } + let mut value = 0u64; + let mut got = 0u32; + while got < n { + let byte = u64::from(self.data[self.pos / 8]); + let shift = (self.pos % 8) as u32; + let take = (8 - shift).min(n - got); + value |= ((byte >> shift) & ((1 << take) - 1)) << got; + got += take; + self.pos += take as usize; + } + Ok(value as u32) + } + + pub(super) fn bit(&mut self) -> Result { + Ok(self.read(1)? == 1) + } +} + +/// `ilog(x)` (§9.2.1): the position of the highest set bit, 0 for values below 1. +pub(super) fn ilog(x: i64) -> u32 { + if x <= 0 { 0 } else { 64 - (x as u64).leading_zeros() } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_least_significant_bit_first() { + // Fields come out of each byte from its least significant bit. + let mut r = BitReader::new(&[0xFC, 0x08]); + assert_eq!(r.read(4), Ok(0xC)); + assert_eq!(r.read(4), Ok(0xF)); + assert_eq!(r.read(1), Ok(0)); + assert_eq!(r.read(3), Ok(4)); + assert_eq!(r.read(4), Ok(0)); + assert_eq!(r.read(1), Err(Eop)); + } + + #[test] + fn wide_reads_span_bytes_and_zero_bits_are_free() { + let mut r = BitReader::new(&[0x01, 0x02, 0x03, 0x04, 0x05]); + assert_eq!(r.read(0), Ok(0)); + assert_eq!(r.read(32), Ok(0x0403_0201)); + assert_eq!(r.read(8), Ok(5)); + assert_eq!(r.read(0), Ok(0)); + assert_eq!(r.read(1), Err(Eop)); + assert_eq!(r.remaining(), 0); + } + + #[test] + fn a_failed_read_consumes_the_rest() { + let mut r = BitReader::new(&[0xFF]); + assert_eq!(r.read(3), Ok(7)); + assert_eq!(r.read(6), Err(Eop)); + assert_eq!(r.read(1), Err(Eop)); + } + + #[test] + fn ilog_matches_the_specification_examples() { + for (x, want) in [(0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (7, 3), (-5, 0), (255, 8), (256, 9)] { + assert_eq!(ilog(x), want, "ilog({x})"); + } + } +} diff --git a/crates/audio/src/vorbis/decoder/codebook.rs b/crates/audio/src/vorbis/decoder/codebook.rs new file mode 100644 index 000000000..9d083c9e4 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/codebook.rs @@ -0,0 +1,409 @@ +//! Codebooks (Vorbis I §3): a Huffman code over entry numbers and an optional table of vectors. + +use super::Error; +use super::bits::{BitReader, Eop, ilog}; + +const NONE: u32 = u32::MAX; +const LEAF: u32 = 1 << 31; +/// Entries a codebook may declare. +const MAX_ENTRIES: u32 = 1 << 20; +/// Nodes of one codeword tree. +const MAX_NODES: usize = 1 << 22; + +#[derive(Clone, Copy)] +struct Node { + child: [u32; 2], + full: bool, +} + +pub(super) struct Codebook { + pub(super) dimensions: usize, + pub(super) entries: usize, + tree: Vec, + /// The only used entry of a single-entry book. + single: Option, + /// `entries * dimensions` values when the book has a lookup table. + vectors: Vec, +} + +/// `float32_unpack` (§9.2.2). +fn float32_unpack(x: u32) -> f64 { + let mantissa = f64::from(x & 0x001F_FFFF); + let exponent = ((x & 0x7FE0_0000) >> 21) as i32; + let m = if x & 0x8000_0000 != 0 { -mantissa } else { mantissa }; + m * 2f64.powi(exponent - 788) +} + +/// `lookup1_values` (§9.2.3): the greatest `v` with `v^dimensions <= entries`. +fn lookup1_values(entries: u32, dimensions: u32) -> u32 { + let mut v = 1u32; + loop { + let next = u128::from(v) + 1; + let mut p = 1u128; + for _ in 0..dimensions { + p *= next; + if p > u128::from(entries) { + return v; + } + } + v += 1; + } +} + +fn insert(tree: &mut Vec, at: usize, depth: u32, len: u32, entry: u32) -> bool { + for b in 0..2 { + let child = tree[at].child[b]; + if depth + 1 == len { + if child == NONE { + tree[at].child[b] = LEAF | entry; + refresh(tree, at); + return true; + } + continue; + } + if child == NONE { + if tree.len() >= MAX_NODES { + return false; + } + tree.push(Node { child: [NONE; 2], full: false }); + let new = tree.len() - 1; + tree[at].child[b] = new as u32; + if insert(tree, new, depth + 1, len, entry) { + refresh(tree, at); + return true; + } + return false; + } + if child & LEAF != 0 || tree[child as usize].full { + continue; + } + if insert(tree, child as usize, depth + 1, len, entry) { + refresh(tree, at); + return true; + } + } + false +} + +fn refresh(tree: &mut [Node], at: usize) { + let done = |c: u32, t: &[Node]| c != NONE && (c & LEAF != 0 || t[c as usize].full); + let full = done(tree[at].child[0], tree) && done(tree[at].child[1], tree); + tree[at].full = full; +} + +impl Codebook { + /// Read one codebook from a setup header. `budget` is the bytes the setup's codebooks may + /// still take in all. + pub(super) fn read(r: &mut BitReader<'_>, budget: &mut usize) -> Result { + let bad = |m: &'static str| Error::Setup(m); + let eop = |_: Eop| Error::Setup("setup header ends inside a codebook"); + if r.read(24).map_err(eop)? != 0x0056_4342 { + return Err(bad("codebook sync pattern missing")); + } + let dimensions = r.read(16).map_err(eop)?; + let entries = r.read(24).map_err(eop)?; + if dimensions == 0 || entries == 0 || entries > MAX_ENTRIES { + return Err(bad("codebook with no dimensions, no entries or too many")); + } + let mut lengths: Vec = Vec::with_capacity(entries as usize); + if r.bit().map_err(eop)? { + // Ordered: the number of codewords of each length. + let mut current = 0u32; + let mut len = r.read(5).map_err(eop)? + 1; + while current < entries { + let number = r.read(ilog(i64::from(entries - current))).map_err(eop)?; + if number > entries - current || len > 32 { + return Err(bad("ordered codebook lengths overrun the entries")); + } + lengths.extend(std::iter::repeat_n(len as u8, number as usize)); + current += number; + len += 1; + } + } else { + let sparse = r.bit().map_err(eop)?; + for _ in 0..entries { + if sparse && !r.bit().map_err(eop)? { + lengths.push(0); + } else { + lengths.push((r.read(5).map_err(eop)? + 1) as u8); + } + } + } + + // The codeword tree. + let used = lengths.iter().filter(|&&l| l != 0).count(); + let mut tree = vec![Node { child: [NONE; 2], full: false }]; + let mut single = None; + if used == 1 { + let entry = lengths.iter().position(|&l| l != 0).unwrap_or(0); + if lengths[entry] != 1 { + return Err(bad("a codebook with one used entry must give it length 1")); + } + single = Some(entry as u32); + } else if used > 1 { + for (entry, &len) in lengths.iter().enumerate() { + if len != 0 && !insert(&mut tree, 0, 0, u32::from(len), entry as u32) { + return Err(bad("overspecified codebook")); + } + } + if !tree[0].full { + return Err(bad("underspecified codebook")); + } + } + let tree_bytes = tree.len() * std::mem::size_of::(); + if tree_bytes > *budget { + return Err(Error::Limit("the codebooks are too large")); + } + *budget -= tree_bytes; + + // The lookup table. + let lookup_type = r.read(4).map_err(eop)?; + let mut vectors = Vec::new(); + if lookup_type > 2 { + return Err(bad("reserved codebook lookup type")); + } + if lookup_type != 0 { + let minimum = float32_unpack(r.read(32).map_err(eop)?); + let delta = float32_unpack(r.read(32).map_err(eop)?); + let value_bits = r.read(4).map_err(eop)? + 1; + let sequence = r.bit().map_err(eop)?; + // Check before multiplying or reading multiplicands: the product can overflow + // usize on 32-bit targets, and a type-2 table otherwise allocates before admission. + let total = (entries as usize) + .checked_mul(dimensions as usize) + .filter(|&n| n <= *budget / std::mem::size_of::()) + .ok_or(Error::Limit("the codebooks' vector tables are too large"))?; + let values = if lookup_type == 1 { lookup1_values(entries, dimensions) as usize } else { total }; + if !minimum.is_finite() || !delta.is_finite() || values > r.remaining() / value_bits as usize { + return Err(bad("codebook lookup table is damaged or truncated")); + } + let multiplicands: Vec = (0..values).map(|_| r.read(value_bits).unwrap_or(0)).collect(); + *budget -= total * std::mem::size_of::(); + vectors = vec![0f32; total]; + for e in 0..entries as usize { + let out = &mut vectors[e * dimensions as usize..(e + 1) * dimensions as usize]; + let mut last = 0f64; + let mut divisor = 1usize; + for (i, slot) in out.iter_mut().enumerate() { + let m = if lookup_type == 1 { + let at = (e / divisor) % values; + divisor = divisor.saturating_mul(values); + multiplicands[at] + } else { + multiplicands[e * dimensions as usize + i] + }; + let v = f64::from(m) * delta + minimum + last; + if sequence { + last = v; + } + *slot = v as f32; + } + } + } + Ok(Self { dimensions: dimensions as usize, entries: entries as usize, tree, single, vectors }) + } + + /// Whether the book has a lookup table. + pub(super) fn has_vectors(&self) -> bool { + !self.vectors.is_empty() + } + + /// Read a codeword; the entry number (scalar context). + pub(super) fn scalar(&self, r: &mut BitReader<'_>) -> Result { + if let Some(e) = self.single { + r.read(1)?; + return Ok(e); + } + let mut at = 0usize; + loop { + let c = self.tree[at].child[usize::from(r.bit()?)]; + if c == NONE { + return Err(Eop); + } + if c & LEAF != 0 { + return Ok(c & !LEAF); + } + at = c as usize; + } + } + + /// Read a codeword and return its vector (VQ context); `None` for a book without a table. + pub(super) fn vector(&self, r: &mut BitReader<'_>) -> Result, Eop> { + let e = self.scalar(r)? as usize; + Ok(self.vectors.get(e * self.dimensions..(e + 1) * self.dimensions)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Pack fields least significant bit first. + struct W(Vec, usize); + impl W { + fn put(&mut self, v: u64, n: u32) { + for i in 0..n { + if self.1.is_multiple_of(8) { + self.0.push(0); + } + let last = self.0.len() - 1; + self.0[last] |= (((v >> i) & 1) as u8) << (self.1 % 8); + self.1 += 1; + } + } + } + + fn book_bytes(lengths: &[u32], lookup: Option<(u32, u32, &[u32])>) -> Vec { + let mut w = W(Vec::new(), 0); + w.put(0x56_4342, 24); + w.put(1, 16); + w.put(lengths.len() as u64, 24); + w.put(0, 1); // not ordered + w.put(0, 1); // not sparse + for &l in lengths { + w.put(u64::from(l - 1), 5); + } + match lookup { + None => w.put(0, 4), + Some((ty, bits, mult)) => { + w.put(u64::from(ty), 4); + w.put(0, 32); // minimum: 0.0 + w.put(0, 32); + w.put(u64::from(bits - 1), 4); + w.put(0, 1); + for &m in mult { + w.put(u64::from(m), bits); + } + } + } + w.0 + } + + #[test] + fn the_specification_example_assigns_its_codewords() { + // §3.2.1: lengths 2 4 4 4 4 2 3 3 -> 00, 0100, 0101, 0110, 0111, 10, 110, 111. + let bytes = book_bytes(&[2, 4, 4, 4, 4, 2, 3, 3], None); + let mut budget = 1 << 26; + let book = Codebook::read(&mut BitReader::new(&bytes), &mut budget).expect("book"); + let code = |bits: &[u8]| { + let mut w = W(Vec::new(), 0); + for &b in bits { + w.put(u64::from(b), 1); + } + let mut r = BitReader::new(&w.0); + book.scalar(&mut r).expect("entry") + }; + assert_eq!(code(&[0, 0]), 0); + assert_eq!(code(&[0, 1, 0, 0]), 1); + assert_eq!(code(&[0, 1, 1, 1]), 4); + assert_eq!(code(&[1, 0]), 5); + assert_eq!(code(&[1, 1, 0]), 6); + assert_eq!(code(&[1, 1, 1]), 7); + } + + #[test] + fn over_and_underspecified_books_are_errors() { + let mut budget = 1 << 26; + let over = book_bytes(&[1, 1, 1], None); + assert!(Codebook::read(&mut BitReader::new(&over), &mut budget).is_err()); + let under = book_bytes(&[2, 2, 2], None); + assert!(Codebook::read(&mut BitReader::new(&under), &mut budget).is_err()); + } + + #[test] + fn a_single_entry_book_sinks_one_bit_of_either_value() { + let mut budget = 1 << 26; + let bytes = book_bytes(&[1], None); + let book = Codebook::read(&mut BitReader::new(&bytes), &mut budget).expect("book"); + for byte in [0u8, 1] { + let data = [byte]; + let mut r = BitReader::new(&data); + assert_eq!(book.scalar(&mut r), Ok(0)); + assert_eq!(r.remaining(), 7); + } + let bad = book_bytes(&[2], None); + assert!(Codebook::read(&mut BitReader::new(&bad), &mut budget).is_err()); + } + + #[test] + fn lookup_type_one_builds_a_lattice() { + // 4 entries, 2 dimensions, 2 values per dimension: minimum 0 and delta 1 in the packed + // float format are written below by hand (mantissa 1, exponent 788 -> 1.0). + let mut w = W(Vec::new(), 0); + w.put(0x56_4342, 24); + w.put(2, 16); + w.put(4, 24); + w.put(0, 1); + w.put(0, 1); + for _ in 0..4 { + w.put(1, 5); // length 2 each + } + w.put(1, 4); // lookup type 1 + w.put(0, 32); // minimum 0 + w.put((788u64 << 21) | 1, 32); // delta 1.0 + w.put(0, 4); // 1 bit per value + w.put(0, 1); + w.put(0b10, 2); // multiplicands 0, 1 + let mut budget = 1 << 26; + let book = Codebook::read(&mut BitReader::new(&w.0), &mut budget).expect("book"); + assert_eq!(lookup1_values(4, 2), 2); + // Entry e is (m[e % 2], m[(e / 2) % 2]). + assert_eq!(book.vectors, vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + } + + #[test] + fn vector_budget_is_checked_before_reading_lookup_values() { + // A valid single-entry tree, but two values exceed the remaining budget. + // No multiplicands follow: admission must reject it before reading them. + for lookup in [1, 2] { + let mut w = W(Vec::new(), 0); + w.put(0x56_4342, 24); + w.put(2, 16); + w.put(1, 24); + w.put(0, 1); + w.put(0, 1); + w.put(0, 5); + w.put(lookup, 4); + w.put(0, 32); + w.put(0, 32); + w.put(15, 4); + w.put(0, 1); + let mut budget = std::mem::size_of::() + 4; + assert!(matches!(Codebook::read(&mut BitReader::new(&w.0), &mut budget), Err(Error::Limit(_)))); + } + } + + #[test] + fn vector_size_that_overflows_32_bits_is_refused() { + for lookup in [1, 2] { + let mut w = W(Vec::new(), 0); + w.put(0x56_4342, 24); + w.put(65535, 16); + w.put(65538, 24); // product is above u32::MAX + w.put(0, 1); // unordered + w.put(1, 1); // sparse: only one entry is used + w.put(1, 1); + w.put(0, 5); // length 1 + for _ in 1..65538 { + w.put(0, 1); + } + w.put(lookup, 4); + w.put(0, 32); + w.put(0, 32); + w.put(0, 4); + w.put(0, 1); + w.put(0, 1); // lookup type 1's single multiplicand + let mut budget = 256 << 20; + assert!(matches!(Codebook::read(&mut BitReader::new(&w.0), &mut budget), Err(Error::Limit(_)))); + } + } + + #[test] + fn helper_functions() { + assert_eq!(float32_unpack((788u32 << 21) | 5), 5.0); + assert_eq!(float32_unpack(0x8000_0000 | (789u32 << 21) | 3), -6.0); + for (entries, dims, want) in [(8, 3, 2), (9, 2, 3), (1, 5, 1), (10, 1, 10), (1000, 3, 10), (4_000_000, 2, 2000)] { + assert_eq!(lookup1_values(entries, dims), want, "{entries} entries, {dims} dims"); + } + } +} diff --git a/crates/audio/src/vorbis/decoder/floor.rs b/crates/audio/src/vorbis/decoder/floor.rs new file mode 100644 index 000000000..bc6ce4e36 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/floor.rs @@ -0,0 +1,385 @@ +//! Floors (Vorbis I §6 and §7): the spectral envelope each channel's residue is multiplied by. + +use super::Error; +use super::bits::{BitReader, Eop, ilog}; +use super::codebook::Codebook; +use super::tables::INVERSE_DB; + +/// Why a floor could not be decoded from a packet. +pub(super) enum Fail { + /// The packet ended (a nominal event: the channel is silent). + Eop, + /// The packet names a codebook that does not exist: it cannot be decoded (§6.2.2). + Invalid, +} + +impl From for Fail { + fn from(_: Eop) -> Self { + Fail::Eop + } +} + +/// What a decoded floor gives to synthesis. +pub(super) enum FloorData { + One { y: Vec, step2: Vec }, + Zero { amplitude: u32, coefficients: Vec }, +} + +pub(super) struct Floor0 { + order: usize, + rate: u32, + bark_map_size: u32, + amplitude_bits: u32, + amplitude_offset: u32, + books: Vec, +} + +pub(super) struct Floor1 { + partition_class: Vec, + class_dimensions: Vec, + class_subclasses: Vec, + class_masterbook: Vec, + subclass_books: Vec>, + multiplier: i32, + range: i32, + xlist: Vec, + /// `(low, high)` neighbour positions of each X from index 2 on. + neighbours: Vec<(usize, usize)>, + /// Indices of `xlist` in ascending X order. + sorted: Vec, +} + +pub(super) enum Floor { + Zero(Floor0), + One(Floor1), +} + +fn eop(_: Eop) -> Error { + Error::Setup("setup header ends inside a floor") +} + +impl Floor { + pub(super) fn read(floor_type: u32, r: &mut BitReader<'_>, books: &[Codebook]) -> Result { + match floor_type { + 0 => { + let order = r.read(8).map_err(eop)? as usize; + let rate = r.read(16).map_err(eop)?; + let bark_map_size = r.read(16).map_err(eop)?; + let amplitude_bits = r.read(6).map_err(eop)?; + let amplitude_offset = r.read(8).map_err(eop)?; + let count = r.read(4).map_err(eop)? as usize + 1; + let mut list = Vec::with_capacity(count); + for _ in 0..count { + let b = r.read(8).map_err(eop)? as usize; + match books.get(b) { + Some(book) if book.has_vectors() => list.push(b), + _ => return Err(Error::Setup("floor 0 names a missing codebook or one without vectors")), + } + } + if order == 0 || rate == 0 || bark_map_size == 0 || amplitude_bits > 32 { + return Err(Error::Setup("floor 0 with a zero order, rate or map size, or more than 32 amplitude bits")); + } + Ok(Self::Zero(Floor0 { order, rate, bark_map_size, amplitude_bits, amplitude_offset, books: list })) + } + 1 => { + let partitions = r.read(5).map_err(eop)? as usize; + let mut partition_class = Vec::with_capacity(partitions); + for _ in 0..partitions { + partition_class.push(r.read(4).map_err(eop)? as usize); + } + let classes = partition_class.iter().max().map_or(0, |m| m + 1); + let (mut class_dimensions, mut class_subclasses, mut class_masterbook, mut subclass_books) = (vec![], vec![], vec![], vec![]); + for _ in 0..classes { + class_dimensions.push(r.read(3).map_err(eop)? as usize + 1); + let subs = r.read(2).map_err(eop)?; + class_subclasses.push(subs); + let master = if subs != 0 { r.read(8).map_err(eop)? as usize } else { 0 }; + if subs != 0 && master >= books.len() { + return Err(Error::Setup("floor 1 master book out of range")); + } + class_masterbook.push(master); + let mut list = Vec::new(); + for _ in 0..(1u32 << subs) { + let b = r.read(8).map_err(eop)? as i32 - 1; + if b >= books.len() as i32 { + return Err(Error::Setup("floor 1 subclass book out of range")); + } + list.push(b); + } + subclass_books.push(list); + } + let multiplier = r.read(2).map_err(eop)? as i32 + 1; + let rangebits = r.read(4).map_err(eop)?; + let mut xlist = vec![0, 1i32 << rangebits]; + for &c in &partition_class { + for _ in 0..class_dimensions[c] { + xlist.push(r.read(rangebits).map_err(eop)? as i32); + } + } + if xlist.len() > 65 { + return Err(Error::Setup("floor 1 has more than 65 points")); + } + let mut seen = xlist.clone(); + seen.sort_unstable(); + if seen.windows(2).any(|w| w[0] == w[1]) { + return Err(Error::Setup("floor 1 repeats an X position")); + } + // Low and high neighbours (§9.2.4, §9.2.5) of each point, among those before it. + let mut neighbours = Vec::new(); + for i in 2..xlist.len() { + let (mut lo, mut hi) = (0usize, 1usize); + for j in 0..i { + if xlist[j] < xlist[i] && xlist[j] > xlist[lo] { + lo = j; + } + if xlist[j] > xlist[i] && xlist[j] < xlist[hi] { + hi = j; + } + } + neighbours.push((lo, hi)); + } + let mut sorted: Vec = (0..xlist.len()).collect(); + sorted.sort_by_key(|&i| xlist[i]); + let range = [256, 128, 86, 64][multiplier as usize - 1]; + Ok(Self::One(Floor1 { + partition_class, + class_dimensions, + class_subclasses, + class_masterbook, + subclass_books, + multiplier, + range, + xlist, + neighbours, + sorted, + })) + } + _ => Err(Error::Setup("unknown floor type")), + } + } + + /// Decode one channel's floor from a packet: `None` when the channel is unused this block. + pub(super) fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook]) -> Result, Fail> { + match self { + Self::One(f) => Ok(f.decode(r, books)?), + Self::Zero(f) => f.decode(r, books), + } + } + + /// The floor curve over `n` bins (`n` is half the block size). + pub(super) fn curve(&self, data: &FloorData, n: usize) -> Vec { + match (self, data) { + (Self::One(f), FloorData::One { y, step2 }) => f.curve(y, step2, n), + (Self::Zero(f), FloorData::Zero { amplitude, coefficients }) => f.curve(*amplitude, coefficients, n), + _ => vec![0.0; n], + } + } +} + +/// `render_point` (§9.2.6). +fn render_point(x0: i32, y0: i32, x1: i32, y1: i32, x: i32) -> i32 { + let dy = i64::from(y1 - y0); + let adx = i64::from(x1 - x0); + let err = dy.abs() * i64::from(x - x0); + let off = (err / adx) as i32; + if dy < 0 { y0 - off } else { y0 + off } +} + +/// `render_line` (§9.2.7), writing the bins that fall inside `v`. +fn render_line(x0: i32, y0: i32, x1: i32, y1: i32, v: &mut [i32]) { + let dy = y1 - y0; + let adx = x1 - x0; + let base = dy / adx; + let ady = dy.abs() - base.abs() * adx; + let sy = if dy < 0 { base - 1 } else { base + 1 }; + let (mut y, mut err) = (y0, 0); + if let Some(slot) = usize::try_from(x0).ok().and_then(|x| v.get_mut(x)) { + *slot = y; + } + for x in x0 + 1..x1 { + err += ady; + if err >= adx { + err -= adx; + y += sy; + } else { + y += base; + } + match usize::try_from(x).ok().and_then(|x| v.get_mut(x)) { + Some(slot) => *slot = y, + None => break, + } + } +} + +impl Floor1 { + fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook]) -> Result, Eop> { + if !r.bit()? { + return Ok(None); + } + let bits = ilog(i64::from(self.range) - 1); + let mut y = vec![0i32; self.xlist.len()]; + y[0] = r.read(bits)? as i32; + y[1] = r.read(bits)? as i32; + let mut offset = 2usize; + for &class in &self.partition_class { + let cdim = self.class_dimensions[class]; + let cbits = self.class_subclasses[class]; + let csub = (1u32 << cbits) - 1; + let mut cval = 0u32; + if cbits > 0 { + cval = books[self.class_masterbook[class]].scalar(r)?; + } + for j in 0..cdim { + let book = self.subclass_books[class][(cval & csub) as usize]; + cval >>= cbits; + y[offset + j] = if book >= 0 { books[book as usize].scalar(r)? as i32 } else { 0 }; + } + offset += cdim; + } + + // Step 1: amplitude synthesis (§7.2.4). + let mut step2 = vec![false; self.xlist.len()]; + step2[0] = true; + step2[1] = true; + let mut fin = y.clone(); + for i in 2..self.xlist.len() { + let (lo, hi) = self.neighbours[i - 2]; + let predicted = render_point(self.xlist[lo], fin[lo], self.xlist[hi], fin[hi], self.xlist[i]); + let val = y[i]; + let highroom = self.range - predicted; + let lowroom = predicted; + let room = if highroom < lowroom { highroom * 2 } else { lowroom * 2 }; + if val != 0 { + step2[lo] = true; + step2[hi] = true; + step2[i] = true; + fin[i] = if val >= room { + if highroom > lowroom { val - lowroom + predicted } else { predicted - val + highroom - 1 } + } else if val % 2 == 1 { + predicted - (val + 1) / 2 + } else { + predicted + val / 2 + }; + } else { + fin[i] = predicted; + } + // Valid setups never leave the range; a damaged one must not carry out-of-range values on. + fin[i] = fin[i].clamp(0, self.range - 1); + } + Ok(Some(FloorData::One { y: fin, step2 })) + } + + fn curve(&self, fin: &[i32], step2: &[bool], n: usize) -> Vec { + let mut floor = vec![0i32; n]; + let (mut hx, mut hy) = (0i32, 0i32); + let (mut lx, mut ly) = (0i32, fin[self.sorted[0]] * self.multiplier); + for &i in &self.sorted[1..] { + if step2[i] { + hy = fin[i] * self.multiplier; + hx = self.xlist[i]; + render_line(lx, ly, hx, hy, &mut floor); + lx = hx; + ly = hy; + } + } + if (hx as usize) < n { + render_line(hx, hy, n as i32, hy, &mut floor); + } + floor.iter().map(|&v| INVERSE_DB[v.clamp(0, 255) as usize]).collect() + } +} + +impl Floor0 { + fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook]) -> Result, Fail> { + let amplitude = r.read(self.amplitude_bits)?; + if amplitude == 0 { + return Ok(None); + } + let book = r.read(ilog(self.books.len() as i64))? as usize; + let Some(&book) = self.books.get(book) else { return Err(Fail::Invalid) }; + let book = &books[book]; + let mut coefficients: Vec = Vec::with_capacity(self.order + book.dimensions); + let mut last = 0f32; + while coefficients.len() < self.order { + let Some(v) = book.vector(r)? else { return Err(Fail::Invalid) }; + coefficients.extend(v.iter().map(|&x| x + last)); + last = coefficients[coefficients.len() - 1]; + } + Ok(Some(FloorData::Zero { amplitude, coefficients })) + } + + fn curve(&self, amplitude: u32, coefficients: &[f32], n: usize) -> Vec { + let bark = |x: f64| 13.1 * (0.00074 * x).atan() + 2.24 * (0.000_000_018_5 * x * x).atan() + 0.0001 * x; + let scale = f64::from(self.bark_map_size) / bark(0.5 * f64::from(self.rate)); + let map: Vec = (0..n) + .map(|i| { + let foobar = (bark(f64::from(self.rate) * i as f64 / (2.0 * n as f64)) * scale).floor() as i64; + foobar.min(i64::from(self.bark_map_size) - 1) + }) + .collect(); + let cos_c: Vec = coefficients.iter().take(self.order).map(|&c| f64::from(c).cos()).collect(); + let amp = f64::from(amplitude); + let offset = f64::from(self.amplitude_offset); + let top = (2f64).powi(self.amplitude_bits as i32) - 1.0; + let mut out = vec![0f32; n]; + let mut i = 0usize; + while i < n { + let omega = std::f64::consts::PI * map[i] as f64 / f64::from(self.bark_map_size); + let cw = omega.cos(); + let (p, q); + if self.order % 2 == 1 { + let mut pp = 1.0 - cw * cw; + for j in 0..(self.order - 1) / 2 { + let d = cos_c[2 * j + 1] - cw; + pp *= 4.0 * d * d; + } + let mut qq = 0.25; + for j in 0..=(self.order - 1) / 2 { + let d = cos_c[2 * j] - cw; + qq *= 4.0 * d * d; + } + p = pp; + q = qq; + } else { + let mut pp = (1.0 - cw) / 2.0; + let mut qq = (1.0 + cw) / 2.0; + for j in 0..self.order / 2 { + let d1 = cos_c[2 * j + 1] - cw; + pp *= 4.0 * d1 * d1; + let d0 = cos_c[2 * j] - cw; + qq *= 4.0 * d0 * d0; + } + p = pp; + q = qq; + } + let linear = (0.115_129_25 * (amp * offset / (top * (p + q).sqrt()) - offset)).exp() as f32; + let key = map[i]; + while i < n && map[i] == key { + out[i] = linear; + i += 1; + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn render_line_matches_a_bresenham_walk() { + let mut v = vec![0i32; 16]; + render_line(0, 0, 8, 4, &mut v); + assert_eq!(&v[..8], &[0, 0, 1, 1, 2, 2, 3, 3]); + let mut v = vec![0i32; 16]; + render_line(2, 10, 6, 2, &mut v); + assert_eq!(&v[2..6], &[10, 8, 6, 4]); + // Lines running past the vector stop at its end. + let mut v = vec![0i32; 4]; + render_line(0, 0, 100, 100, &mut v); + assert_eq!(v, vec![0, 1, 2, 3]); + assert_eq!(render_point(0, 0, 10, 10, 5), 5); + assert_eq!(render_point(0, 10, 10, 0, 5), 5); + } +} diff --git a/crates/audio/src/vorbis/decoder/mdct.rs b/crates/audio/src/vorbis/decoder/mdct.rs new file mode 100644 index 000000000..b4eb6c8ec --- /dev/null +++ b/crates/audio/src/vorbis/decoder/mdct.rs @@ -0,0 +1,164 @@ +//! The inverse MDCT of a block (Vorbis I §4.3.7) and the window slopes. +//! +//! `y[j] = sum_k X[k] cos(2*pi/n * (j + 1/2 + n/4) * (k + 1/2))` for `n/2` coefficients and `n` +//! samples, computed as a DCT-IV of the coefficients through an `n/8`-point complex FFT, then +//! unfolded. + +use std::f64::consts::PI; + +#[derive(Clone, Copy, Default)] +struct Cpx { + re: f64, + im: f64, +} + +impl Cpx { + 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 } + } +} + +fn cis(t: f64) -> Cpx { + Cpx { re: t.cos(), im: t.sin() } +} + +pub(super) struct Imdct { + n: usize, + twiddle: Vec, + post: Vec, + fft_tw: Vec, + rev: Vec, +} + +impl Imdct { + /// For blocks of `n` samples, a power of two of at least 16. + pub(super) fn new(n: usize) -> Self { + let m = n / 2; + let h = m / 2; + let twiddle = (0..h).map(|j| cis(-PI * (4.0 * j as f64 + 1.0) / (4.0 * m as f64))).collect(); + let post = (0..h).map(|k| cis(-PI * k as f64 / m as f64)).collect(); + let fft_tw = (0..h / 2).map(|j| cis(-2.0 * PI * j as f64 / h as f64)).collect(); + let bits = h.trailing_zeros(); + let rev = (0..h).map(|i| if bits == 0 { 0 } else { i.reverse_bits() >> (usize::BITS - bits) }).collect(); + Self { n, twiddle, post, fft_tw, rev } + } + + /// `x`: `n/2` coefficients; `out`: `n` samples. + pub(super) fn inverse(&self, x: &[f32], out: &mut [f32]) { + let m = self.n / 2; + let q = self.n / 4; + let h = m / 2; + let mut z: Vec = (0..h).map(|j| Cpx { re: f64::from(x[2 * j]), im: f64::from(x[m - 1 - 2 * j]) }.mul(self.twiddle[j])).collect(); + self.fft(&mut z); + let mut v = vec![0f64; m]; + for (k, c) in z.iter().enumerate() { + let d = c.mul(self.post[k]); + v[2 * k] = d.re; + v[m - 1 - 2 * k] = -d.im; + } + // Unfold the DCT-IV output to the block. + for i in 0..q { + out[3 * q - 1 - i] = (-v[i]) as f32; + out[3 * q + i] = (-v[i]) as f32; + } + for i in q..2 * q { + out[i - q] = v[i] as f32; + out[3 * q - 1 - i] = (-v[i]) as f32; + } + } + + fn fft(&self, a: &mut [Cpx]) { + let h = a.len(); + for (i, &j) in self.rev.iter().enumerate() { + if i < j { + a.swap(i, j); + } + } + let mut len = 2; + while len <= h { + let step = h / len; + for start in (0..h).step_by(len) { + for k in 0..len / 2 { + let w = self.fft_tw[k * step]; + let u = a[start + k]; + let t = a[start + k + len / 2].mul(w); + a[start + k] = Cpx { re: u.re + t.re, im: u.im + t.im }; + a[start + k + len / 2] = Cpx { re: u.re - t.re, im: u.im - t.im }; + } + } + len *= 2; + } + } +} + +/// The rising half of the Vorbis window over `len` samples (§4.3.1): +/// `sin(pi/2 * sin^2((i + 0.5) / len * pi/2))`. +pub(super) fn slope(len: usize) -> Vec { + (0..len) + .map(|i| { + let s = (PI / 2.0 * (i as f64 + 0.5) / len as f64).sin(); + (PI / 2.0 * s * s).sin() as f32 + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_the_direct_formula() { + for n in [16usize, 64, 256, 2048] { + let x: Vec = (0..n / 2).map(|i| ((i * 7919 % 211) as f32 - 105.0) / 50.0).collect(); + let mut fast = vec![0f32; n]; + Imdct::new(n).inverse(&x, &mut fast); + for j in [0usize, 1, 2, n / 4, n / 2, n - 1] { + let direct: f64 = + (0..n / 2).map(|k| f64::from(x[k]) * (2.0 * PI / n as f64 * (j as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos()).sum(); + assert!((direct - f64::from(fast[j])).abs() < 1e-3 * (1.0 + direct.abs()), "n={n} j={j}: {direct} vs {}", fast[j]); + } + } + } + + #[test] + fn windowed_overlap_add_reconstructs_the_signal() { + // Forward MDCT by the definition with the 2/M scale an encoder uses, then this inverse. + let n = 64usize; + let m = n / 2; + let signal: Vec = (0..n * 6).map(|i| ((i * 37 % 101) as f64 - 50.0) / 50.0).collect(); + let w: Vec = slope(m).into_iter().chain(slope(m).into_iter().rev()).collect(); + let imdct = Imdct::new(n); + let mut out = vec![0f64; signal.len()]; + let mut start = 0; + while start + n <= signal.len() { + let coeffs: Vec = (0..m) + .map(|k| { + let s: f64 = (0..n) + .map(|j| { + signal[start + j] * f64::from(w[j]) * (2.0 * PI / n as f64 * (j as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos() + }) + .sum(); + (s * 2.0 / m as f64) as f32 + }) + .collect(); + let mut y = vec![0f32; n]; + imdct.inverse(&coeffs, &mut y); + for j in 0..n { + out[start + j] += f64::from(y[j]) * f64::from(w[j]); + } + start += m; + } + for i in m..signal.len() - m { + assert!((out[i] - signal[i]).abs() < 1e-4, "sample {i}: {} vs {}", out[i], signal[i]); + } + } + + #[test] + fn the_slope_is_power_complementary() { + let s = slope(1024); + for i in 0..1024 { + let sum = s[i] * s[i] + s[1023 - i] * s[1023 - i]; + assert!((sum - 1.0).abs() < 1e-5, "{i}: {sum}"); + } + } +} diff --git a/crates/audio/src/vorbis/decoder/mod.rs b/crates/audio/src/vorbis/decoder/mod.rs new file mode 100644 index 000000000..7485e34b8 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/mod.rs @@ -0,0 +1,552 @@ +//! A clean-room Vorbis I decoder (feature `vorbis-decode`), written from the Vorbis I +//! specification (Xiph.Org, 2020). +//! +//! [`Decoder`] works on packets: build it from the three header packets (identification, comment +//! and setup), then give it audio packets in order. Each call returns the PCM the packet +//! completes, planar `f32` in the nominal range -1.0 to 1.0 (not clipped), channels in the order of +//! the stream. The first packet only primes the overlap and returns nothing. [`decode_ogg`] reads a +//! whole Ogg Vorbis file. +//! +//! Codebooks, floors 0 and 1, residues 0, 1 and 2, channel coupling and both block sizes with their +//! hybrid windows are implemented. Damaged input is an error, never a panic: setup sizes are +//! bounded before anything is allocated, and the codeword trees are checked for completeness. + +mod bits; +mod codebook; +mod floor; +mod mdct; +mod residue; +mod tables; + +use bits::{BitReader, Eop, ilog}; +use codebook::Codebook; +use floor::{Fail, Floor, FloorData}; +use mdct::{Imdct, slope}; +use residue::Residue; + +/// Errors of the Vorbis decoder. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The identification or comment header is not valid Vorbis. + #[error("invalid Vorbis header: {0}")] + Header(&'static str), + /// The setup header is damaged or uses something Vorbis I does not allow. + #[error("invalid Vorbis setup: {0}")] + Setup(&'static str), + /// The setup or decoded PCM asks for more memory than the decoder allows. + #[error("Vorbis decode above the limits: {0}")] + Limit(&'static str), + /// The packet is not an audio packet (a header, or a packet with its first bit set). + #[error("not an audio packet")] + NotAudio, + /// The packet is damaged: it ends before its mode and window flags are read, or names a mode + /// that does not exist. + #[error("damaged audio packet: {0}")] + Packet(&'static str), + /// An Ogg file with no Vorbis stream, or one that cannot be read. + #[error("Ogg Vorbis file: {0}")] + Ogg(String), +} + +/// `Result` of this module. +pub type Result = std::result::Result; + +/// The identification header (§4.2.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Identification { + /// The channel count, at least 1. + pub channels: u8, + /// Samples per second per channel. + pub sample_rate: u32, + /// The maximum bit rate in bits per second, 0 or negative when not set. + pub bitrate_maximum: i32, + /// The nominal bit rate in bits per second, 0 or negative when not set. + pub bitrate_nominal: i32, + /// The minimum bit rate in bits per second, 0 or negative when not set. + pub bitrate_minimum: i32, + /// The short block size in samples. + pub blocksize_0: u32, + /// The long block size in samples. + pub blocksize_1: u32, +} + +/// The comment header (§5): a vendor string and `NAME=value` comments. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Comments { + /// The vendor string of the encoder. + pub vendor: String, + /// The user comments, each `NAME=value`. + pub comments: Vec, +} + +impl Comments { + /// The first comment named `name` (case-insensitive), its value. + #[must_use] + pub fn get(&self, name: &str) -> Option<&str> { + self.comments.iter().find_map(|c| { + let (k, v) = c.split_once('=')?; + k.eq_ignore_ascii_case(name).then_some(v) + }) + } +} + +fn header_start(packet: &[u8], kind: u8) -> Result> { + if packet.len() < 7 || packet[0] != kind || &packet[1..7] != b"vorbis" { + return Err(Error::Header("wrong packet type or missing \"vorbis\" tag")); + } + let mut r = BitReader::new(packet); + let _ = r.read(8); + for _ in 0..6 { + let _ = r.read(8); + } + Ok(r) +} + +fn read_identification(packet: &[u8]) -> Result { + let mut r = header_start(packet, 1)?; + let eop = |_: Eop| Error::Header("identification header is truncated"); + if r.read(32).map_err(eop)? != 0 { + return Err(Error::Header("unsupported Vorbis version")); + } + let channels = r.read(8).map_err(eop)? as u8; + let sample_rate = r.read(32).map_err(eop)?; + let bitrate_maximum = r.read(32).map_err(eop)? as i32; + let bitrate_nominal = r.read(32).map_err(eop)? as i32; + let bitrate_minimum = r.read(32).map_err(eop)? as i32; + let e0 = r.read(4).map_err(eop)?; + let e1 = r.read(4).map_err(eop)?; + if !r.bit().map_err(eop)? { + return Err(Error::Header("identification header framing bit is not set")); + } + if channels == 0 || sample_rate == 0 { + return Err(Error::Header("no channels or a zero sample rate")); + } + if !(6..=13).contains(&e0) || !(6..=13).contains(&e1) || e0 > e1 { + return Err(Error::Header("block sizes must be powers of two from 64 to 8192, the short one not above the long one")); + } + Ok(Identification { channels, sample_rate, bitrate_maximum, bitrate_nominal, bitrate_minimum, blocksize_0: 1 << e0, blocksize_1: 1 << e1 }) +} + +/// Comments are best effort: damage here is not fatal (§4.2.1). +fn read_comments(packet: &[u8]) -> Result { + header_start(packet, 3)?; + let mut at = 7usize; + let mut take = |n: usize| -> Option<&[u8]> { + let s = packet.get(at..at.checked_add(n)?)?; + at += n; + Some(s) + }; + let word = |b: &[u8]| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize; + let mut out = Comments::default(); + let Some(n) = take(4).map(word) else { return Ok(out) }; + let Some(vendor) = take(n) else { return Ok(out) }; + out.vendor = String::from_utf8_lossy(vendor).into_owned(); + let Some(count) = take(4).map(word) else { return Ok(out) }; + for _ in 0..count { + let Some(n) = take(4).map(word) else { break }; + let Some(c) = take(n) else { break }; + out.comments.push(String::from_utf8_lossy(c).into_owned()); + } + Ok(out) +} + +struct Mapping { + coupling: Vec<(usize, usize)>, + mux: Vec, + /// `(floor, residue)` of each submap. + submaps: Vec<(usize, usize)>, +} + +struct Mode { + long: bool, + mapping: usize, +} + +struct Setup { + books: Vec, + floors: Vec, + residues: Vec, + mappings: Vec, + modes: Vec, +} + +/// Bytes the codebooks of a setup may take in all (codeword trees and vector tables). +const CODEBOOK_BUDGET: usize = 256 << 20; + +fn read_setup(packet: &[u8], channels: usize) -> Result { + let mut r = header_start(packet, 5)?; + let eop = |_: Eop| Error::Setup("setup header is truncated"); + let count = r.read(8).map_err(eop)? as usize + 1; + let mut budget = CODEBOOK_BUDGET; + let mut books = Vec::with_capacity(count); + for _ in 0..count { + books.push(Codebook::read(&mut r, &mut budget)?); + } + // Time domain transforms: placeholders. + for _ in 0..r.read(6).map_err(eop)? + 1 { + if r.read(16).map_err(eop)? != 0 { + return Err(Error::Setup("a time domain transform is not zero")); + } + } + let count = r.read(6).map_err(eop)? as usize + 1; + let mut floors = Vec::with_capacity(count); + for _ in 0..count { + let kind = r.read(16).map_err(eop)?; + floors.push(Floor::read(kind, &mut r, &books)?); + } + let count = r.read(6).map_err(eop)? as usize + 1; + let mut residues = Vec::with_capacity(count); + for _ in 0..count { + let kind = r.read(16).map_err(eop)?; + if kind > 2 { + return Err(Error::Setup("unknown residue type")); + } + residues.push(Residue::read(kind, &mut r, &books)?); + } + let count = r.read(6).map_err(eop)? as usize + 1; + let mut mappings = Vec::with_capacity(count); + for _ in 0..count { + if r.read(16).map_err(eop)? != 0 { + return Err(Error::Setup("unknown mapping type")); + } + let submaps = if r.bit().map_err(eop)? { r.read(4).map_err(eop)? as usize + 1 } else { 1 }; + let mut coupling = Vec::new(); + if r.bit().map_err(eop)? { + let steps = r.read(8).map_err(eop)? as usize + 1; + let bits = ilog(channels as i64 - 1); + for _ in 0..steps { + let magnitude = r.read(bits).map_err(eop)? as usize; + let angle = r.read(bits).map_err(eop)? as usize; + if magnitude == angle || magnitude >= channels || angle >= channels { + return Err(Error::Setup("channel coupling names an invalid channel pair")); + } + coupling.push((magnitude, angle)); + } + } + if r.read(2).map_err(eop)? != 0 { + return Err(Error::Setup("reserved mapping bits are set")); + } + let mut mux = vec![0usize; channels]; + if submaps > 1 { + for m in &mut mux { + *m = r.read(4).map_err(eop)? as usize; + if *m >= submaps { + return Err(Error::Setup("channel multiplexed to a submap that does not exist")); + } + } + } + let mut list = Vec::with_capacity(submaps); + for _ in 0..submaps { + r.read(8).map_err(eop)?; + let floor = r.read(8).map_err(eop)? as usize; + let residue = r.read(8).map_err(eop)? as usize; + if floor >= floors.len() || residue >= residues.len() { + return Err(Error::Setup("submap names a floor or residue that does not exist")); + } + list.push((floor, residue)); + } + mappings.push(Mapping { coupling, mux, submaps: list }); + } + let count = r.read(6).map_err(eop)? as usize + 1; + let mut modes = Vec::with_capacity(count); + for _ in 0..count { + let long = r.bit().map_err(eop)?; + let window = r.read(16).map_err(eop)?; + let transform = r.read(16).map_err(eop)?; + let mapping = r.read(8).map_err(eop)? as usize; + if window != 0 || transform != 0 || mapping >= mappings.len() { + return Err(Error::Setup("a mode has a nonzero window or transform type or an unknown mapping")); + } + modes.push(Mode { long, mapping }); + } + if !r.bit().map_err(eop)? { + return Err(Error::Setup("setup header framing bit is not set")); + } + Ok(Setup { books, floors, residues, mappings, modes }) +} + +/// The previous block, windowed, kept for overlap-add. +struct Previous { + n: usize, + data: Vec>, +} + +/// A Vorbis I packet decoder. +pub struct Decoder { + id: Identification, + comments: Comments, + setup: Setup, + imdct: [Imdct; 2], + slopes: [Vec; 2], + previous: Option, +} + +impl Decoder { + /// A decoder from the three header packets, in order. A damaged comment header is tolerated + /// (its comments are then empty); the other two must be valid. + pub fn new(identification: &[u8], comment: &[u8], setup: &[u8]) -> Result { + let id = read_identification(identification)?; + let comments = read_comments(comment)?; + let setup = read_setup(setup, usize::from(id.channels))?; + let (b0, b1) = (id.blocksize_0 as usize, id.blocksize_1 as usize); + Ok(Self { id, comments, setup, imdct: [Imdct::new(b0), Imdct::new(b1)], slopes: [slope(b0 / 2), slope(b1 / 2)], previous: None }) + } + + /// The identification header. + #[must_use] + pub fn identification(&self) -> &Identification { + &self.id + } + + /// The comment header. + #[must_use] + pub fn comments(&self) -> &Comments { + &self.comments + } + + /// Forget the previous block, as after a seek: the next packet only primes the overlap again. + pub fn reset(&mut self) { + self.previous = None; + } + + /// The window of a block (§4.3.1). + fn window(&self, n: usize, long: bool, prev_long: bool, next_long: bool) -> Vec { + let half = n / 2; + let b0 = self.id.blocksize_0 as usize; + let mut w = vec![0f32; n]; + // Left half. + if long && !prev_long { + let (start, end) = (n / 4 - b0 / 4, n / 4 + b0 / 4); + w[start..end].copy_from_slice(&self.slopes[0]); + w[end..half].fill(1.0); + } else { + w[..half].copy_from_slice(&self.slopes[usize::from(long)]); + } + // Right half. + if long && !next_long { + let start = 3 * n / 4 - b0 / 4; + w[half..start].fill(1.0); + for (i, s) in self.slopes[0].iter().rev().enumerate() { + w[start + i] = *s; + } + } else { + for (i, s) in self.slopes[usize::from(long)].iter().rev().enumerate() { + w[half + i] = *s; + } + } + w + } + + /// Decode one audio packet. The result holds one `Vec` per channel, all of the same length: + /// the samples this packet completes (none for the first packet after a start or reset). + pub fn decode_packet(&mut self, packet: &[u8]) -> Result>> { + let channels = usize::from(self.id.channels); + let mut r = BitReader::new(packet); + match r.bit() { + Ok(false) => {} + Ok(true) => return Err(Error::NotAudio), + Err(_) => return Err(Error::Packet("empty packet")), + } + let mode_bits = ilog(self.setup.modes.len() as i64 - 1); + let mode_number = r.read(mode_bits).map_err(|_| Error::Packet("packet ends inside the mode number"))? as usize; + let Some(mode) = self.setup.modes.get(mode_number) else { return Err(Error::Packet("mode number out of range")) }; + let long = mode.long; + let n = if long { self.id.blocksize_1 } else { self.id.blocksize_0 } as usize; + let (mut prev_long, mut next_long) = (true, true); + if long { + prev_long = r.bit().map_err(|_| Error::Packet("packet ends inside the window flags"))?; + next_long = r.bit().map_err(|_| Error::Packet("packet ends inside the window flags"))?; + } + let window = self.window(n, long, prev_long, next_long); + let half = n / 2; + let mapping = &self.setup.mappings[mode.mapping]; + + let spectrum = self.spectrum(&mut r, mapping, half, channels)?; + // Inverse transform and window. + let which = usize::from(long); + let mut blocks: Vec> = Vec::with_capacity(channels); + for s in &spectrum { + let mut y = vec![0f32; n]; + self.imdct[which].inverse(s, &mut y); + for (v, w) in y.iter_mut().zip(&window) { + *v *= *w; + } + blocks.push(y); + } + + // Overlap-add with the previous block (§4.3.8). + let out = match &self.previous { + None => vec![Vec::new(); channels], + Some(prev) => { + let count = prev.n / 4 + n / 4; + blocks + .iter() + .zip(&prev.data) + .map(|(cur, old)| { + (0..count) + .map(|k| { + let a = old.get(prev.n / 2 + k).copied().unwrap_or(0.0); + let b = (n / 4 + k).checked_sub(prev.n / 4).and_then(|i| cur.get(i)).copied().unwrap_or(0.0); + a + b + }) + .collect() + }) + .collect() + } + }; + self.previous = Some(Previous { n, data: blocks }); + Ok(out) + } + + /// Floors, residues, coupling and the dot product: the spectrum of each channel (§4.3.2 to 4.3.6). + fn spectrum(&self, r: &mut BitReader<'_>, mapping: &Mapping, half: usize, channels: usize) -> Result>> { + let zero = || vec![vec![0f32; half]; channels]; + let setup = &self.setup; + // Floors, in channel order. + let mut floors: Vec> = Vec::with_capacity(channels); + for ch in 0..channels { + let (floor, _) = mapping.submaps[mapping.mux[ch]]; + match setup.floors[floor].decode(r, &setup.books) { + Ok(f) => floors.push(f), + Err(Fail::Eop) => return Ok(zero()), + Err(Fail::Invalid) => return Err(Error::Packet("a floor names a codebook that does not exist")), + } + } + let mut no_residue: Vec = floors.iter().map(Option::is_none).collect(); + for &(m, a) in &mapping.coupling { + if !no_residue[m] || !no_residue[a] { + no_residue[m] = false; + no_residue[a] = false; + } + } + // Residues, in submap order. + let mut residue = zero(); + for (i, &(_, res)) in mapping.submaps.iter().enumerate() { + let members: Vec = (0..channels).filter(|&c| mapping.mux[c] == i).collect(); + if members.is_empty() { + continue; + } + let skip: Vec = members.iter().map(|&c| no_residue[c]).collect(); + let mut vectors = vec![vec![0f32; half]; members.len()]; + setup.residues[res].decode(r, &setup.books, half, &skip, &mut vectors); + for (v, &c) in vectors.into_iter().zip(&members) { + residue[c] = v; + } + } + // Inverse channel coupling (§4.3.5), last step first. + for &(m, a) in mapping.coupling.iter().rev() { + let mut mag = std::mem::take(&mut residue[m]); + let mut ang = std::mem::take(&mut residue[a]); + for (mv, av) in mag.iter_mut().zip(ang.iter_mut()) { + let (big, small) = (*mv, *av); + let (new_m, new_a); + if big > 0.0 { + if small > 0.0 { + new_m = big; + new_a = big - small; + } else { + new_a = big; + new_m = big + small; + } + } else if small > 0.0 { + new_m = big; + new_a = big + small; + } else { + new_a = big; + new_m = big - small; + } + *mv = new_m; + *av = new_a; + } + residue[m] = mag; + residue[a] = ang; + } + // The floor times the residue. + for ch in 0..channels { + match &floors[ch] { + Some(data) => { + let (floor, _) = mapping.submaps[mapping.mux[ch]]; + let curve = setup.floors[floor].curve(data, half); + for (v, c) in residue[ch].iter_mut().zip(curve) { + *v *= c; + } + } + None => residue[ch].fill(0.0), + } + } + Ok(residue) + } +} + +/// A decoded Ogg Vorbis file. +#[derive(Debug, Clone, PartialEq)] +pub struct Decoded { + /// Samples per second per channel. + pub sample_rate: u32, + /// One `Vec` of samples per channel. + pub channels: Vec>, + /// The stream's comment header. + pub comments: Comments, + /// Audio packets that could not be decoded and were skipped. + pub damaged_packets: usize, +} + +/// Decode the first Vorbis stream of an Ogg file. The result is trimmed to the stream's final +/// granule position, so an encoder's padding at the end is dropped. Damaged packets are skipped +/// and counted, not fatal. Collected PCM is limited to 256 MiB; use the packet +/// decoder for longer streams without retaining the entire output. +pub fn decode_ogg(data: &[u8]) -> Result { + let ogg = craft_media::ogg::open(data).map_err(|e| Error::Ogg(e.to_string()))?; + let index = ogg.stream_of(craft_media::ogg::Codec::Vorbis).ok_or_else(|| Error::Ogg("no Vorbis stream".into()))?; + let stream = &ogg.streams[index]; + let [id, comment, setup, ..] = stream.headers.as_slice() else { return Err(Error::Ogg("the stream has fewer than three header packets".into())) }; + let mut decoder = Decoder::new(id, comment, setup)?; + let channel_count = usize::from(decoder.id.channels); + let mut channels = vec![Vec::new(); channel_count]; + let mut damaged = 0; + for i in 0..stream.packets.len() { + let packet = ogg.read_packet(data, index, i).map_err(|e| Error::Ogg(e.to_string()))?; + match decoder.decode_packet(&packet) { + Ok(pcm) => { + append_pcm(&mut channels, pcm, 256 << 20)?; + } + Err(_) => damaged += 1, + } + } + if let Some(total) = stream.last_granule.and_then(|g| usize::try_from(g).ok()) { + for c in &mut channels { + c.truncate(total); + } + } + Ok(Decoded { sample_rate: decoder.id.sample_rate, channels, comments: decoder.comments.clone(), damaged_packets: damaged }) +} + +// Admit every channel together before extending any of them. Limit retained PCM, +// not the compressed input, setup tables or the decoder's bounded packet scratch. +fn append_pcm(channels: &mut [Vec], pcm: Vec>, budget: usize) -> Result<()> { + let samples = channels.iter().chain(&pcm).try_fold(0usize, |n, c| n.checked_add(c.len())); + if samples.is_none_or(|n| n > budget / std::mem::size_of::()) { + return Err(Error::Limit("decoded PCM exceeds the whole-file budget")); + } + for (all, new) in channels.iter_mut().zip(pcm) { + all.try_reserve_exact(new.len()).map_err(|_| Error::Limit("cannot allocate decoded PCM"))?; + all.extend(new); + } + Ok(()) +} + +#[cfg(test)] +mod budget_tests { + use super::*; + + #[test] + fn pcm_budget_counts_all_channels_before_extending() { + let mut channels = vec![vec![1.0], vec![2.0]]; + append_pcm(&mut channels, vec![vec![3.0], vec![4.0]], 16).expect("exact budget"); + let before = channels.clone(); + assert!(matches!(append_pcm(&mut channels, vec![vec![5.0], vec![6.0]], 23), Err(Error::Limit(_)))); + assert_eq!(channels, before); + append_pcm(&mut channels, vec![Vec::new(), Vec::new()], 16).expect("empty packet"); + } +} diff --git a/crates/audio/src/vorbis/decoder/residue.rs b/crates/audio/src/vorbis/decoder/residue.rs new file mode 100644 index 000000000..99918d379 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/residue.rs @@ -0,0 +1,196 @@ +//! Residues (Vorbis I §8): the fine detail of the spectrum, coded as vectors in passes. + +use super::Error; +use super::bits::{BitReader, Eop}; +use super::codebook::Codebook; + +pub(super) struct Residue { + kind: u32, + begin: usize, + end: usize, + partition_size: usize, + classifications: usize, + classbook: usize, + /// `books[class][pass]`. + books: Vec<[Option; 8]>, +} + +fn eop(_: Eop) -> Error { + Error::Setup("setup header ends inside a residue") +} + +impl Residue { + pub(super) fn read(kind: u32, r: &mut BitReader<'_>, books: &[Codebook]) -> Result { + let begin = r.read(24).map_err(eop)? as usize; + let end = r.read(24).map_err(eop)? as usize; + let partition_size = r.read(24).map_err(eop)? as usize + 1; + let classifications = r.read(6).map_err(eop)? as usize + 1; + let classbook = r.read(8).map_err(eop)? as usize; + let Some(cb) = books.get(classbook) else { return Err(Error::Setup("residue class book out of range")) }; + // classifications ^ dimensions must not exceed the book's entries. + let mut reach = 1u128; + for _ in 0..cb.dimensions { + reach = reach.saturating_mul(classifications as u128); + if reach > cb.entries as u128 { + return Err(Error::Setup("residue class book has too few entries for its classifications")); + } + } + let mut cascade = Vec::with_capacity(classifications); + for _ in 0..classifications { + let low = r.read(3).map_err(eop)?; + let high = if r.bit().map_err(eop)? { r.read(5).map_err(eop)? } else { 0 }; + cascade.push(high * 8 + low); + } + let mut list = Vec::with_capacity(classifications); + for &c in &cascade { + let mut row = [None; 8]; + for (j, slot) in row.iter_mut().enumerate() { + if c & (1 << j) != 0 { + let b = r.read(8).map_err(eop)? as usize; + match books.get(b) { + Some(book) if book.has_vectors() => *slot = Some(b), + _ => return Err(Error::Setup("residue names a missing codebook or one without vectors")), + } + } + } + list.push(row); + } + Ok(Self { kind, begin, end, partition_size, classifications, classbook, books: list }) + } + + /// Decode a bundle of vectors, each `n` long (half the block size), into `out`; a vector marked + /// in `skip` is left zero. End of packet ends decoding where it is (a nominal event). + pub(super) fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook], n: usize, skip: &[bool], out: &mut [Vec]) { + let ch = out.len(); + if skip.iter().all(|&s| s) { + return; + } + if self.kind == 2 { + let mut flat = vec![vec![0f32; n * ch]]; + let _ = self.decode_vectors(r, books, n * ch, &[false], &mut flat); + for i in 0..n { + for (j, v) in out.iter_mut().enumerate() { + v[i] = flat[0][i * ch + j]; + } + } + } else { + let _ = self.decode_vectors(r, books, n, skip, out); + } + } + + fn decode_vectors(&self, r: &mut BitReader<'_>, books: &[Codebook], actual: usize, skip: &[bool], out: &mut [Vec]) -> Result<(), Eop> { + let ch = out.len(); + let begin = self.begin.min(actual); + let end = self.end.min(actual); + if end <= begin { + return Ok(()); + } + let classbook = &books[self.classbook]; + let cpw = classbook.dimensions; + let partitions = (end - begin) / self.partition_size; + // Classbook dimensions may greatly exceed the actual partition count. + // Retain only digits that this block can use, not padding per channel. + let mut classes = vec![vec![0usize; partitions]; ch]; + for pass in 0..8 { + let mut count = 0usize; + while count < partitions { + if pass == 0 { + for j in 0..ch { + if skip[j] { + continue; + } + let mut temp = classbook.scalar(r)? as usize; + for i in (0..cpw).rev() { + if i + count < partitions { + classes[j][i + count] = temp % self.classifications; + } + temp /= self.classifications; + } + } + } + let mut i = 0; + while i < cpw && count < partitions { + for j in 0..ch { + if skip[j] { + continue; + } + let Some(book) = self.books[classes[j][count]][pass] else { continue }; + let book = &books[book]; + let offset = begin + count * self.partition_size; + self.partition(r, book, &mut out[j][offset..offset + self.partition_size])?; + } + count += 1; + i += 1; + } + } + } + Ok(()) + } + + /// One partition into `v` (the slice of the vector it covers). + fn partition(&self, r: &mut BitReader<'_>, book: &Codebook, v: &mut [f32]) -> Result<(), Eop> { + let n = v.len(); + let dims = book.dimensions; + let step = n / dims; + if self.kind == 0 { + for i in 0..step { + let Some(entry) = book.vector(r)? else { return Ok(()) }; + for (j, &e) in entry.iter().enumerate() { + v[i + j * step] += e; + } + } + } else { + let mut i = 0; + for _ in 0..step { + let Some(entry) = book.vector(r)? else { return Ok(()) }; + for &e in entry { + v[i] += e; + i += 1; + } + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn huge_class_dimensions_keep_only_actual_partitions() { + let mut data = Vec::::new(); + let mut bits = 0usize; + let mut put = |value: u32, n: usize| { + for i in 0..n { + if bits.is_multiple_of(8) { + data.push(0); + } + let last = data.len() - 1; + data[last] |= (((value >> i) & 1) as u8) << (bits % 8); + bits += 1; + } + }; + put(0x56_4342, 24); + put(65535, 16); + put(1, 24); + put(0, 1); // unordered, not sparse, one length-1 entry + put(0, 1); + put(0, 5); + put(0, 4); // scalar-only classbook + let book = Codebook::read(&mut BitReader::new(&data), &mut (1 << 20)).expect("classbook"); + let books = [book]; + for kind in [0, 1] { + let residue = Residue { kind, begin: 0, end: 32, partition_size: 1, classifications: 1, classbook: 0, books: vec![[None; 8]] }; + let mut out = vec![vec![0.0; 32]; 255]; + let packet = [0u8; 32]; + let mut r = BitReader::new(&packet); + residue.decode(&mut r, &books, 32, &[false; 255], &mut out); + assert_eq!(r.remaining(), 1); // one classword per channel, not 32 + assert!(out.iter().flatten().all(|&x| x == 0.0)); + let mut r = BitReader::new(&packet); + residue.decode(&mut r, &books, 32, &[true; 255], &mut out); + assert_eq!(r.remaining(), 256); // skipped channels consume nothing + } + } +} diff --git a/crates/audio/src/vorbis/decoder/tables.rs b/crates/audio/src/vorbis/decoder/tables.rs new file mode 100644 index 000000000..49e5b97b9 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/tables.rs @@ -0,0 +1,263 @@ +//! `floor1_inverse_dB_table` (Vorbis I §10.1): the 256 linear amplitudes of the floor 1 integer values. + +// The values are printed to the digits the specification gives them. +#![allow(clippy::excessive_precision)] + +pub(super) const INVERSE_DB: [f32; 256] = [ + 1.0649863e-07, + 1.1341951e-07, + 1.2079015e-07, + 1.2863978e-07, + 1.3699951e-07, + 1.4590251e-07, + 1.5538408e-07, + 1.6548181e-07, + 1.7623575e-07, + 1.8768855e-07, + 1.9988561e-07, + 2.1287530e-07, + 2.2670913e-07, + 2.4144197e-07, + 2.5713223e-07, + 2.7384213e-07, + 2.9163793e-07, + 3.1059021e-07, + 3.3077411e-07, + 3.5226968e-07, + 3.7516214e-07, + 3.9954229e-07, + 4.2550680e-07, + 4.5315863e-07, + 4.8260743e-07, + 5.1396998e-07, + 5.4737065e-07, + 5.8294187e-07, + 6.2082472e-07, + 6.6116941e-07, + 7.0413592e-07, + 7.4989464e-07, + 7.9862701e-07, + 8.5052630e-07, + 9.0579828e-07, + 9.6466216e-07, + 1.0273513e-06, + 1.0941144e-06, + 1.1652161e-06, + 1.2409384e-06, + 1.3215816e-06, + 1.4074654e-06, + 1.4989305e-06, + 1.5963394e-06, + 1.7000785e-06, + 1.8105592e-06, + 1.9282195e-06, + 2.0535261e-06, + 2.1869758e-06, + 2.3290978e-06, + 2.4804557e-06, + 2.6416497e-06, + 2.8133190e-06, + 2.9961443e-06, + 3.1908506e-06, + 3.3982101e-06, + 3.6190449e-06, + 3.8542308e-06, + 4.1047004e-06, + 4.3714470e-06, + 4.6555282e-06, + 4.9580707e-06, + 5.2802740e-06, + 5.6234160e-06, + 5.9888572e-06, + 6.3780469e-06, + 6.7925283e-06, + 7.2339451e-06, + 7.7040476e-06, + 8.2047000e-06, + 8.7378876e-06, + 9.3057248e-06, + 9.9104632e-06, + 1.0554501e-05, + 1.1240392e-05, + 1.1970856e-05, + 1.2748789e-05, + 1.3577278e-05, + 1.4459606e-05, + 1.5399272e-05, + 1.6400004e-05, + 1.7465768e-05, + 1.8600792e-05, + 1.9809576e-05, + 2.1096914e-05, + 2.2467911e-05, + 2.3928002e-05, + 2.5482978e-05, + 2.7139006e-05, + 2.8902651e-05, + 3.0780908e-05, + 3.2781225e-05, + 3.4911534e-05, + 3.7180282e-05, + 3.9596466e-05, + 4.2169667e-05, + 4.4910090e-05, + 4.7828601e-05, + 5.0936773e-05, + 5.4246931e-05, + 5.7772202e-05, + 6.1526565e-05, + 6.5524908e-05, + 6.9783085e-05, + 7.4317983e-05, + 7.9147585e-05, + 8.4291040e-05, + 8.9768747e-05, + 9.5602426e-05, + 0.00010181521, + 0.00010843174, + 0.00011547824, + 0.00012298267, + 0.00013097477, + 0.00013948625, + 0.00014855085, + 0.00015820453, + 0.00016848555, + 0.00017943469, + 0.00019109536, + 0.00020351382, + 0.00021673929, + 0.00023082423, + 0.00024582449, + 0.00026179955, + 0.00027881276, + 0.00029693158, + 0.00031622787, + 0.00033677814, + 0.00035866388, + 0.00038197188, + 0.00040679456, + 0.00043323036, + 0.00046138411, + 0.00049136745, + 0.00052329927, + 0.00055730621, + 0.00059352311, + 0.00063209358, + 0.00067317058, + 0.00071691700, + 0.00076350630, + 0.00081312324, + 0.00086596457, + 0.00092223983, + 0.00098217216, + 0.0010459992, + 0.0011139742, + 0.0011863665, + 0.0012634633, + 0.0013455702, + 0.0014330129, + 0.0015261382, + 0.0016253153, + 0.0017309374, + 0.0018434235, + 0.0019632195, + 0.0020908006, + 0.0022266726, + 0.0023713743, + 0.0025254795, + 0.0026895994, + 0.0028643847, + 0.0030505286, + 0.0032487691, + 0.0034598925, + 0.0036847358, + 0.0039241906, + 0.0041792066, + 0.0044507950, + 0.0047400328, + 0.0050480668, + 0.0053761186, + 0.0057254891, + 0.0060975636, + 0.0064938176, + 0.0069158225, + 0.0073652516, + 0.0078438871, + 0.0083536271, + 0.0088964928, + 0.009474637, + 0.010090352, + 0.010746080, + 0.011444421, + 0.012188144, + 0.012980198, + 0.013823725, + 0.014722068, + 0.015678791, + 0.016697687, + 0.017782797, + 0.018938423, + 0.020169149, + 0.021479854, + 0.022875735, + 0.024362330, + 0.025945531, + 0.027631618, + 0.029427276, + 0.031339626, + 0.033376252, + 0.035545228, + 0.037855157, + 0.040315199, + 0.042935108, + 0.045725273, + 0.048696758, + 0.051861348, + 0.055231591, + 0.058820850, + 0.062643361, + 0.066714279, + 0.071049749, + 0.075666962, + 0.080584227, + 0.085821044, + 0.091398179, + 0.097337747, + 0.10366330, + 0.11039993, + 0.11757434, + 0.12521498, + 0.13335215, + 0.14201813, + 0.15124727, + 0.16107617, + 0.17154380, + 0.18269168, + 0.19456402, + 0.20720788, + 0.22067342, + 0.23501402, + 0.25028656, + 0.26655159, + 0.28387361, + 0.30232132, + 0.32196786, + 0.34289114, + 0.36517414, + 0.38890521, + 0.41417847, + 0.44109412, + 0.46975890, + 0.50028648, + 0.53279791, + 0.56742212, + 0.60429640, + 0.64356699, + 0.68538959, + 0.72993007, + 0.77736504, + 0.82788260, + 0.88168307, + 0.9389798, + 1.0, +]; diff --git a/crates/audio/src/vorbis/encoder/book.rs b/crates/audio/src/vorbis/encoder/book.rs new file mode 100644 index 000000000..b392cf27c --- /dev/null +++ b/crates/audio/src/vorbis/encoder/book.rs @@ -0,0 +1,287 @@ +//! Bit packing (Vorbis I §2) and codebooks (§3): Huffman lengths, the codeword assignment the +//! decoder derives from them, VQ lattices (lookup type 1) and the header encoding. + +use super::{Error, Result}; + +/// LSB-first bit packer (Vorbis I §2.1.4): bits fill each byte from its least significant end. +#[derive(Clone, Debug, Default)] +pub struct BitWriter { + buf: Vec, + bits: u64, +} + +impl BitWriter { + pub fn new() -> BitWriter { + BitWriter::default() + } + + /// Writes the low `n` bits of `v` (`n` ≤ 32). + pub fn write(&mut self, v: u32, n: u32) { + let n = n.min(32); + for i in 0..n { + let bit = (v >> i) & 1; + let at = (self.bits / 8) as usize; + if at == self.buf.len() { + self.buf.push(0); + } + if bit != 0 + && let Some(b) = self.buf.get_mut(at) + { + *b |= 1 << (self.bits % 8); + } + self.bits += 1; + } + } + + pub fn flag(&mut self, b: bool) { + self.write(b as u32, 1); + } + + /// Writes a codeword MSB first: the decoder walks the tree from its first bit. + fn codeword(&mut self, word: u32, len: u32) { + for i in (0..len).rev() { + self.write((word >> i) & 1, 1); + } + } + + pub fn bytes(&mut self, data: &[u8]) { + for &b in data { + self.write(u32::from(b), 8); + } + } + + pub fn finish(self) -> Vec { + self.buf + } +} + +/// `ilog` of the specification (§9.2.1): the position of the highest set bit, 0 for 0. +pub fn ilog(v: u32) -> u32 { + 32 - v.leading_zeros() +} + +/// The 32-bit float format of codebook headers (§9.2.2), for values it represents exactly. +pub fn float32_pack(v: f64) -> u32 { + if v == 0.0 || !v.is_finite() { + return 0; + } + let sign = if v < 0.0 { 0x8000_0000u32 } else { 0 }; + let mut m = v.abs(); + let mut exp: i32 = 0; + // a 21-bit mantissa: scale into [2^20, 2^21) + while m >= (1 << 21) as f64 { + m /= 2.0; + exp += 1; + } + while m < (1 << 20) as f64 { + m *= 2.0; + exp -= 1; + } + let mant = (m.round() as u32).min((1 << 21) - 1); + let biased = (exp + 788).clamp(0, 1023) as u32; + sign | (biased << 21) | mant +} + +/// Huffman code lengths (1..=`max_len`) for `weights`, every entry coded. +pub fn huffman_lengths(weights: &[f64], max_len: u32) -> Vec { + let n = weights.len(); + if n <= 1 { + return vec![1; n]; + } + let total: f64 = weights.iter().map(|w| if w.is_finite() { w.max(0.0) } else { 0.0 }).sum::().max(1e-300); + let mut floor = 1e-9; + loop { + let w: Vec = weights.iter().map(|&x| (if x.is_finite() { x.max(0.0) } else { 0.0 }) / total + floor).collect(); + let lens = huffman(&w); + if lens.iter().all(|&l| l <= max_len) || floor > 1.0 { + return lens.into_iter().map(|l| l.clamp(1, max_len)).collect(); + } + floor *= 4.0; + } +} + +fn huffman(w: &[f64]) -> Vec { + // nodes: (weight, children) with leaves first + let n = w.len(); + let mut parent = vec![usize::MAX; 2 * n]; + let mut weight: Vec = w.to_vec(); + let mut alive: Vec = (0..n).collect(); + while alive.len() > 1 { + alive.sort_by(|&a, &b| weight[b].partial_cmp(&weight[a]).unwrap_or(std::cmp::Ordering::Equal).then(b.cmp(&a))); + let (Some(a), Some(b)) = (alive.pop(), alive.pop()) else { break }; + let id = weight.len(); + weight.push(weight[a] + weight[b]); + if parent.len() <= id { + parent.resize(id + 1, usize::MAX); + } + parent[a] = id; + parent[b] = id; + alive.push(id); + } + (0..n) + .map(|i| { + let mut d = 0; + let mut x = i; + while let Some(&p) = parent.get(x) { + if p == usize::MAX { + break; + } + d += 1; + x = p; + } + d + }) + .collect() +} + +/// The codewords the decoder assigns to `lengths` (§3.2.1): in entry order, each entry gets the +/// lowest available codeword of its length (no prefix of an assigned codeword, and no assigned +/// codeword a prefix of it). An error when the lengths do not fit a prefix code. +pub fn assign_codewords(lengths: &[u32]) -> Result> { + // A trie of the assigned codewords: `children[node]` (0 = none), `leaf[node]`. + let mut children: Vec<[usize; 2]> = vec![[0, 0]]; + let mut leaf = vec![false]; + let mut words = Vec::with_capacity(lengths.len()); + for &len in lengths { + if len == 0 || len > 32 { + return Err(Error::Internal("codeword length")); + } + let bits = lowest_free(&children, &leaf, 0, len).ok_or(Error::Internal("over-subscribed codebook"))?; + let mut node = 0usize; + let mut word = 0u32; + for &bit in &bits { + word = (word << 1) | bit as u32; + node = match children[node][bit] { + 0 => { + children.push([0, 0]); + leaf.push(false); + let id = children.len() - 1; + children[node][bit] = id; + id + } + c => c, + }; + } + leaf[node] = true; + words.push(word); + } + Ok(words) +} + +/// The leftmost free path of `depth` bits below `node` (depth-first, 0 before 1). +fn lowest_free(children: &[[usize; 2]], leaf: &[bool], node: usize, depth: u32) -> Option> { + if leaf[node] || depth == 0 { + return None; + } + for bit in 0..2 { + let c = children[node][bit]; + if c == 0 { + let mut p = vec![bit]; + p.resize(depth as usize, 0); + return Some(p); + } + if let Some(mut rest) = lowest_free(children, leaf, c, depth - 1) { + rest.insert(0, bit); + return Some(rest); + } + } + None +} + +/// A codebook: entry lengths and codewords, and for VQ books a lattice (lookup type 1). +#[derive(Clone, Debug)] +pub struct Codebook { + pub dimensions: u32, + pub lengths: Vec, + pub words: Vec, + /// Lattice values per dimension (lookup type 1: `values^dimensions == entries`). + pub lattice: Option, +} + +#[derive(Clone, Copy, Debug)] +pub struct Lattice { + pub minimum: f64, + pub delta: f64, + /// Values per dimension. + pub values: u32, +} + +impl Codebook { + /// A scalar book (no lookup) of `weights.len()` entries. + pub fn scalar(dimensions: u32, weights: &[f64]) -> Result { + let lengths = huffman_lengths(weights, 20); + let words = assign_codewords(&lengths)?; + Ok(Codebook { dimensions, lengths, words, lattice: None }) + } + + /// A lattice VQ book: `values` integers per dimension from `minimum` in steps of `delta`; + /// `weight(v)` is the relative probability of one component `v`. + pub fn lattice(dimensions: u32, values: u32, minimum: i32, delta: i32, weight: impl Fn(i32) -> f64) -> Result { + let entries = values.checked_pow(dimensions).ok_or(Error::Internal("codebook size"))?; + let w: Vec = (0..entries) + .map(|e| { + let mut p = 1.0; + let mut rest = e; + for _ in 0..dimensions { + let t = (rest % values) as i32; + rest /= values; + p *= weight(minimum + t * delta); + } + p + }) + .collect(); + let lengths = huffman_lengths(&w, 20); + let words = assign_codewords(&lengths)?; + Ok(Codebook { dimensions, lengths, words, lattice: Some(Lattice { minimum: f64::from(minimum), delta: f64::from(delta), values }) }) + } + + pub fn entries(&self) -> usize { + self.lengths.len() + } + + /// Writes entry `e`. + pub fn put(&self, w: &mut BitWriter, e: usize) { + if let (Some(&word), Some(&len)) = (self.words.get(e), self.lengths.get(e)) { + w.codeword(word, len); + } + } + + /// The entry of the lattice vector `v` (component 0 is the least significant digit, §3.2.1). + pub fn entry_of(&self, v: &[i32]) -> usize { + let Some(l) = self.lattice else { return 0 }; + let mut e = 0usize; + let mut scale = 1usize; + for &x in v.iter().take(self.dimensions as usize) { + let t = ((f64::from(x) - l.minimum) / l.delta).round().clamp(0.0, f64::from(l.values - 1)) as usize; + e += t * scale; + scale *= l.values as usize; + } + e + } + + /// The header encoding (§3.2.1). + pub fn write_header(&self, w: &mut BitWriter) { + w.write(0x56_4342, 24); + w.write(self.dimensions, 16); + w.write(self.entries() as u32, 24); + w.flag(false); // not ordered + w.flag(false); // not sparse + for &l in &self.lengths { + w.write(l - 1, 5); + } + match self.lattice { + None => w.write(0, 4), + Some(l) => { + w.write(1, 4); + w.write(float32_pack(l.minimum), 32); + w.write(float32_pack(l.delta), 32); + let bits = ilog(l.values - 1).max(1); + w.write(bits - 1, 4); + w.flag(false); // sequence_p + for m in 0..l.values { + w.write(m, bits); + } + } + } + } +} diff --git a/crates/audio/src/vorbis/encoder/floor.rs b/crates/audio/src/vorbis/encoder/floor.rs new file mode 100644 index 000000000..503385bd3 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/floor.rs @@ -0,0 +1,207 @@ +//! Floor type 1 (Vorbis I §7): a piecewise-linear spectral envelope in the decoder's dB scale. +//! +//! The encoder picks a target value at each of the floor's X positions, codes it against the +//! decoder's prediction from its neighbours (step 2 of §7.2.4, inverted), and renders the curve +//! exactly as the decoder will (`render_line`, integer arithmetic), so the residue is computed +//! against the very floor the decoder multiplies it by. + +use super::book::{BitWriter, Codebook, ilog}; + +/// `floor1_multiplier`: 2, so values run 0..128 and step two entries of the dB table. +pub const MULTIPLIER: u32 = 2; +/// The value range for [`MULTIPLIER`] 2. +pub const RANGE: i32 = 128; +const RANGE_BITS: u32 = 10; +/// Points per partition, and partitions. +pub const CLASS_DIM: usize = 4; +pub const PARTITIONS: usize = 8; + +/// Step (in dB) between entries of `floor1_inverse_dB_table`: it runs from 1.0649863e-07 to 1 +/// over 256 entries. +fn db_step() -> f64 { + (1.0f64 / 1.064_986_3e-7).ln() / 255.0 +} + +/// `floor1_inverse_dB_table[i]`. +pub fn inverse_db(i: i32) -> f32 { + (f64::from(i.clamp(0, 255) - 255) * db_step()).exp() as f32 +} + +/// The table index whose amplitude is nearest (in dB) to `a`. +pub fn db_index(a: f32) -> i32 { + if !a.is_finite() || a <= 0.0 { + return 0; + } + ((f64::from(a)).ln() / db_step() + 255.0).round().clamp(0.0, 255.0) as i32 +} + +/// A floor 1 configuration for blocks of `n/2 = 2^RANGE_BITS` bins. +#[derive(Clone, Debug)] +pub struct Floor1 { + /// X positions: 0, 1024, then the partitions' points. + pub xs: Vec, + /// Index of the book coding the point values. + pub book: usize, + /// For each point (in coding order) its low and high neighbours. + neighbours: Vec<(usize, usize)>, + /// Point indices sorted by X. + sorted: Vec, +} + +impl Floor1 { + /// Points spaced about evenly in log frequency over 1..1024. + pub fn new(book: usize) -> Floor1 { + let count = CLASS_DIM * PARTITIONS; + let mut xs = vec![0, 1 << RANGE_BITS]; + let mut last = 0; + for i in 1..=count { + // geometric from 2 to ~1000 bins, at least one bin apart + let x = (2.0f64 * (500.0f64).powf((i - 1) as f64 / (count - 1) as f64)).round() as i32; + let x = x.max(last + 1).min((1 << RANGE_BITS) - 1); + xs.push(x); + last = x; + } + let neighbours = (0..xs.len()) + .map(|i| { + if i < 2 { + return (0, 0); + } + let (mut lo, mut hi) = (0usize, 1usize); + for j in 0..i { + if xs[j] < xs[i] && xs[j] > xs[lo] { + lo = j; + } + if xs[j] > xs[i] && xs[j] < xs[hi] { + hi = j; + } + } + (lo, hi) + }) + .collect(); + let mut sorted: Vec = (0..xs.len()).collect(); + sorted.sort_by_key(|&i| xs[i]); + Floor1 { xs, book, neighbours, sorted } + } + + /// The setup-header encoding (§7.2.2): one class of `CLASS_DIM` points, no subclasses. + pub fn write_header(&self, w: &mut BitWriter) { + w.write(PARTITIONS as u32, 5); + for _ in 0..PARTITIONS { + w.write(0, 4); + } + w.write(CLASS_DIM as u32 - 1, 3); + w.write(0, 2); // no subclasses + w.write(self.book as u32 + 1, 8); + w.write(MULTIPLIER - 1, 2); + w.write(RANGE_BITS, 4); + for &x in &self.xs[2..] { + w.write(x as u32, RANGE_BITS); + } + } + + /// Codes the target values `want` (one per point, 0..RANGE) into `w`; returns the floor curve + /// the decoder renders (`n2` amplitudes). + pub fn encode(&self, w: &mut BitWriter, book: &Codebook, want: &[i32], n2: usize) -> Vec { + let n = self.xs.len(); + let want = |i: usize| want.get(i).copied().unwrap_or(0).clamp(0, RANGE - 1); + let mut fin = vec![0i32; n]; + let mut used = vec![false; n]; + let mut coded = vec![0u32; n]; + fin[0] = want(0); + fin[1] = want(1); + used[0] = true; + used[1] = true; + for i in 2..n { + let (lo, hi) = self.neighbours[i]; + let pred = render_point(self.xs[lo], fin[lo], self.xs[hi], fin[hi], self.xs[i]); + let f = want(i); + let (highroom, lowroom) = (RANGE - pred, pred); + let room = 2 * highroom.min(lowroom); + let val = if f == pred { + 0 + } else { + let d = f - pred; + let inside = if d > 0 { 2 * d } else { -2 * d - 1 }; + if inside < room { + inside + } else if highroom > lowroom { + f - pred + lowroom + } else { + pred - f + highroom - 1 + } + }; + coded[i] = val.clamp(0, RANGE - 1) as u32; + if val != 0 { + used[lo] = true; + used[hi] = true; + used[i] = true; + fin[i] = f; + } else { + fin[i] = pred; + } + } + let bits = ilog(RANGE as u32 - 1); + w.write(fin[0] as u32, bits); + w.write(fin[1] as u32, bits); + for &c in &coded[2..] { + book.put(w, c as usize); + } + self.render(&fin, &used, n2) + } + + /// The decoder's curve (§7.2.4 step 2, `render_line`) as amplitudes. + fn render(&self, fin: &[i32], used: &[bool], n2: usize) -> Vec { + let mut v = vec![0i32; n2]; + let m = MULTIPLIER as i32; + let (mut lx, mut ly) = (0i32, fin[self.sorted[0]] * m); + let (mut hx, mut hy) = (0i32, ly); + for &i in &self.sorted[1..] { + if used[i] { + hy = fin[i] * m; + hx = self.xs[i]; + render_line(lx, ly, hx, hy, &mut v); + lx = hx; + ly = hy; + } + } + if (hx as usize) < n2 { + render_line(hx, hy, n2 as i32, hy, &mut v); + } + v.iter().map(|&i| inverse_db(i)).collect() + } +} + +fn render_point(x0: i32, y0: i32, x1: i32, y1: i32, x: i32) -> i32 { + let dy = y1 - y0; + let adx = (x1 - x0).max(1); + let err = dy.abs() * (x - x0); + let off = err / adx; + if dy < 0 { y0 - off } else { y0 + off } +} + +fn render_line(x0: i32, y0: i32, x1: i32, y1: i32, v: &mut [i32]) { + let dy = y1 - y0; + let adx = x1 - x0; + if adx <= 0 { + return; + } + let base = dy / adx; + let sy = if dy < 0 { base - 1 } else { base + 1 }; + let ady = dy.abs() - base.abs() * adx; + let (mut y, mut err) = (y0, 0); + if let Some(s) = v.get_mut(x0 as usize) { + *s = y; + } + for x in x0 + 1..x1 { + err += ady; + if err >= adx { + err -= adx; + y += sy; + } else { + y += base; + } + if let Some(s) = v.get_mut(x as usize) { + *s = y; + } + } +} diff --git a/crates/audio/src/vorbis/encoder/mdct.rs b/crates/audio/src/vorbis/encoder/mdct.rs new file mode 100644 index 000000000..3802a24d6 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/mdct.rs @@ -0,0 +1,134 @@ +//! Forward MDCT of a windowed block of `n` samples to `n/2` coefficients: +//! `X[k] = Σ x[j] cos(2π/n · (j + 1/2 + n/4)(k + 1/2))`, the transform the Vorbis decoder inverts +//! (Vorbis I §1.3.2, §4.3.9). Computed as a DCT-IV of the folded block through an `n/8`-point +//! complex FFT. + +use std::f64::consts::PI; + +#[derive(Clone, Copy, Default, Debug)] +struct Cpx { + re: f64, + im: f64, +} + +impl Cpx { + 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 } + } +} + +/// A forward MDCT for one block size (a power of two, at least 16). +#[derive(Clone, Debug)] +pub struct Mdct { + n: usize, + twiddle: Vec, + post: Vec, + fft_tw: Vec, + rev: Vec, +} + +impl Mdct { + pub fn new(n: usize) -> Mdct { + let m = n / 2; // DCT-IV length + let h = m / 2; // FFT length + let twiddle = (0..h).map(|j| cis(-PI * (4.0 * j as f64 + 1.0) / (4.0 * m as f64))).collect(); + let post = (0..h).map(|k| cis(-PI * k as f64 / m as f64)).collect(); + let fft_tw = (0..h / 2).map(|j| cis(-2.0 * PI * j as f64 / h as f64)).collect(); + let bits = h.trailing_zeros(); + let rev = (0..h).map(|i| if bits == 0 { 0 } else { i.reverse_bits() >> (usize::BITS - bits) }).collect(); + Mdct { n, twiddle, post, fft_tw, rev } + } + + /// `x`: `n` windowed samples; `out`: `n/2` coefficients (scaled by `scale`). + pub fn forward(&self, x: &[f32], out: &mut [f32], scale: f64) { + let n = self.n; + let m = n / 2; + let q = n / 4; + let at = |i: usize| f64::from(x.get(i).copied().unwrap_or(0.0)); + // fold (a, b, c, d) to the DCT-IV input (-c_r - d, a - b_r) + let mut v = vec![0f64; m]; + for (i, s) in v.iter_mut().enumerate() { + *s = if i < q { -at(3 * q - 1 - i) - at(3 * q + i) } else { at(i - q) - at(3 * q - 1 - i) }; + } + // DCT-IV through a half-length complex FFT + let h = m / 2; + let mut z: Vec = (0..h).map(|j| Cpx { re: v[2 * j], im: v[m - 1 - 2 * j] }.mul(self.twiddle[j])).collect(); + self.fft(&mut z); + for (k, c) in z.iter().enumerate() { + let d = c.mul(self.post[k]); + if let Some(o) = out.get_mut(2 * k) { + *o = (d.re * scale) as f32; + } + if let Some(o) = out.get_mut(m - 1 - 2 * k) { + *o = (-d.im * scale) as f32; + } + } + } + + /// In-place radix-2 FFT (`e^{-2πi jk/h}`). + fn fft(&self, a: &mut [Cpx]) { + let h = a.len(); + for i in 0..h { + let j = self.rev[i]; + if i < j { + a.swap(i, j); + } + } + let mut len = 2; + while len <= h { + let step = h / len; + for start in (0..h).step_by(len) { + for k in 0..len / 2 { + let w = self.fft_tw[k * step]; + let u = a[start + k]; + let t = a[start + k + len / 2].mul(w); + a[start + k] = Cpx { re: u.re + t.re, im: u.im + t.im }; + a[start + k + len / 2] = Cpx { re: u.re - t.re, im: u.im - t.im }; + } + } + len *= 2; + } + } +} + +fn cis(t: f64) -> Cpx { + Cpx { re: t.cos(), im: t.sin() } +} + +/// The Vorbis window (§4.3.1) for a block of `n` between blocks of the same size. +pub fn window(n: usize) -> Vec { + (0..n) + .map(|i| { + let s = (PI * (i as f64 + 0.5) / n as f64).sin(); + (PI / 2.0 * s * s).sin() as f32 + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_the_direct_formula() { + for n in [16usize, 64, 256, 2048] { + let x: Vec = (0..n).map(|i| ((i * 7919 % 211) as f32 - 105.0) / 50.0).collect(); + let mut fast = vec![0f32; n / 2]; + Mdct::new(n).forward(&x, &mut fast, 1.0); + for k in [0usize, 1, 2, n / 4, n / 2 - 1] { + let direct: f64 = + (0..n).map(|j| f64::from(x[j]) * (2.0 * PI / n as f64 * (j as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos()).sum(); + assert!((direct - f64::from(fast[k])).abs() < 1e-3 * (1.0 + direct.abs()), "n={n} k={k}: {direct} vs {}", fast[k]); + } + } + } + + #[test] + fn the_window_is_power_complementary() { + let w = window(2048); + for i in 0..1024 { + let s = w[i] * w[i] + w[i + 1024] * w[i + 1024]; + assert!((s - 1.0).abs() < 1e-5, "{i}: {s}"); + } + } +} diff --git a/crates/audio/src/vorbis/encoder/mod.rs b/crates/audio/src/vorbis/encoder/mod.rs new file mode 100644 index 000000000..95be88244 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/mod.rs @@ -0,0 +1,494 @@ +//! Pure-Rust Vorbis I encoder, written from the Vorbis I specification (Xiph.Org, 2020-07-04). +//! +//! No `unsafe` and no C code; builds for `wasm32-unknown-unknown`. ffmpeg is used only as an +//! external test oracle. +//! +//! The stream: one mode of 2048-sample blocks; per channel a floor 1 envelope of 34 points; one +//! residue type 2 over the interleaved channels, partitions of 32 values (a multiple of the +//! channel count for 3, 5, 6 and 7 channels) in seven classes (silent, +//! three single-pass lattice books, and two- and three-pass cascades for large values); no channel +//! coupling. Quality (-1 to 10) sets how far the floor sits from the spectral envelope (below it +//! for tonal regions, above it for noise-like ones, from the spectral flatness), and with it the +//! residue's precision: variable bit rate, like other Vorbis encoders. +//! +//! From FilmCraft's `filmcraft-vorbis` by @JordyUSA (storytold/filmcraft#4481). +//! +//! The packets go into Ogg with [`craft_media::ogg::PageWriter`] and a comment header from +//! [`craft_media::ogg::vorbis_comment`]; [`crate::encode_ogg_vorbis`] does all of it for a +//! whole buffer. +//! +//! ``` +//! use craft_audio::vorbis::encoder::{Encoder, EncoderConfig}; +//! +//! let mut enc = Encoder::new(EncoderConfig::new(48_000, 2, 5.0))?; +//! let tone: Vec = (0..4_800).map(|i| (i as f32 * 0.05).sin() * 0.5).collect(); +//! let mut packets = enc.encode(&[&tone, &tone])?; +//! packets.extend(enc.finish()?); +//! // the last granule position is the input's length, so a decoder trims the padding +//! assert_eq!(packets.last().map(|p| p.1), Some(4_800)); +//! assert_eq!(&enc.identification()[1..7], b"vorbis"); +//! # Ok::<(), craft_audio::vorbis::encoder::Error>(()) +//! ``` + +// Index loops follow the specification, as in FilmCraft (which allows this lint workspace-wide). +#![allow(clippy::needless_range_loop)] + +mod book; +mod floor; +mod mdct; + +use book::{BitWriter, Codebook}; +use floor::Floor1; +use mdct::Mdct; + +/// Why an encoder could not be created or input could not be encoded. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// A setting or the input is outside what the encoder takes. + #[error("invalid argument: {0}")] + InvalidArgument(&'static str), + /// An encoder invariant failed (a bug, reported instead of panicking). + #[error("internal error: {0}")] + Internal(&'static str), +} + +/// The encoder's result type. +pub type Result = std::result::Result; + +/// Block size (samples); the short block size of the header is never used. +pub const BLOCK: usize = 2048; +const HOP: usize = BLOCK / 2; +/// Residue values per partition for `channels` channels: 32, or for 3, 5, 6 and 7 channels a +/// multiple of the channel count (48, 40, 48, 56). libvorbis decodes each partition of an +/// interleaved (type 2) residue as if it started on channel 0, so a partition must hold whole +/// sample frames; the size also divides `channels × 1024` and is a multiple of every book's +/// dimension (4). +fn partition_size(channels: usize) -> usize { + match channels { + 3 | 6 => 48, + 5 => 40, + 7 => 56, + _ => 32, + } +} +const CLASSES: usize = 8; +/// Largest residue magnitude the cascade codes: 7·225 + 7·15 + 7. +const MAX_RESIDUE: i32 = 1687; + +/// The quality a NaN or infinite setting reads as. +pub const DEFAULT_QUALITY: f32 = 6.0; + +/// Encoder settings. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EncoderConfig { + /// Samples per second, 1 to 768 000. + pub sample_rate: u32, + /// 1 to 8, in Vorbis channel order (§4.3.9). + pub channels: usize, + /// -1 (smallest) to 10 (best); clamped. + pub quality: f32, +} + +impl EncoderConfig { + /// Settings for `channels` channels (in Vorbis order) at `sample_rate` and `quality`. + pub fn new(sample_rate: u32, channels: usize, quality: f32) -> EncoderConfig { + EncoderConfig { sample_rate, channels, quality } + } +} + +/// Book indices in the setup header. +const BOOK_CLASS: usize = 0; +const BOOK_FLOOR: usize = 1; +const BOOK_A1_SPARSE: usize = 2; +const BOOK_A1: usize = 3; +const BOOK_A2: usize = 4; +const BOOK_A4: usize = 5; +const BOOK_F: usize = 6; +const BOOK_M: usize = 7; +const BOOK_C: usize = 8; + +/// Books per class and pass (`None`: nothing coded in that pass). +const CASCADE: [[Option; 3]; CLASSES] = [ + [None, None, None], + [Some(BOOK_A1_SPARSE), None, None], + [Some(BOOK_A1), None, None], + [Some(BOOK_A2), None, None], + [Some(BOOK_A4), None, None], + [Some(BOOK_F), None, None], + [Some(BOOK_M), Some(BOOK_F), None], + [Some(BOOK_C), Some(BOOK_M), Some(BOOK_F)], +]; + +/// A Vorbis encoder for one stream: planar `f32` in, Vorbis packets with their granule +/// positions out. +pub struct Encoder { + cfg: EncoderConfig, + books: Vec, + floor: Floor1, + mdct: Mdct, + window: Vec, + /// Input not yet past a block, per channel; the next block starts at `start`. + pending: Vec>, + /// Read cursor into `pending`: consumed hops are dropped once per call, not per block. + start: usize, + samples_in: u64, + blocks: u64, + finished: bool, + /// Floor offset below the envelope (dB) for tonal and for noise-like regions. + tonal_db: f32, + noise_db: f32, + /// Residue magnitudes below this quantise to 0. + dead_zone: f32, +} + +impl Encoder { + /// An encoder for `cfg`: 1 to 8 channels, a sample rate of 1 to 768 000; the quality is + /// clamped to -1..=10, and NaN or infinite reads as [`DEFAULT_QUALITY`]. + pub fn new(cfg: EncoderConfig) -> Result { + if !(1..=8).contains(&cfg.channels) { + return Err(Error::InvalidArgument("Vorbis encoder: 1 to 8 channels")); + } + if !(1..=768_000).contains(&cfg.sample_rate) { + return Err(Error::InvalidArgument("Vorbis encoder: sample rate")); + } + let quality = if cfg.quality.is_finite() { cfg.quality.clamp(-1.0, 10.0) } else { DEFAULT_QUALITY }; + let cfg = EncoderConfig { quality, ..cfg }; + let books = vec![ + Codebook::scalar(2, &(0..CLASSES * CLASSES).map(|e| class_weight(e / CLASSES) * class_weight(e % CLASSES)).collect::>())?, + Codebook::scalar(1, &(0..floor::RANGE).map(|v| 1.0 / (1.0 + f64::from(v)).powf(1.6)).collect::>())?, + Codebook::lattice(4, 3, -1, 1, |v| if v == 0 { 0.92 } else { 0.04 })?, + Codebook::lattice(4, 3, -1, 1, |v| if v == 0 { 0.5 } else { 0.25 })?, + Codebook::lattice(2, 5, -2, 1, |v| 0.6f64.powi(v.abs()))?, + Codebook::lattice(2, 9, -4, 1, |v| 0.7f64.powi(v.abs()))?, + Codebook::lattice(2, 15, -7, 1, |v| 0.8f64.powi(v.abs()))?, + Codebook::lattice(2, 15, -105, 15, |v| 0.55f64.powi((v / 15).abs()))?, + Codebook::lattice(2, 15, -1575, 225, |v| 0.4f64.powi((v / 225).abs()))?, + ]; + Ok(Encoder { + cfg, + books, + floor: Floor1::new(BOOK_FLOOR), + mdct: Mdct::new(BLOCK), + window: mdct::window(BLOCK), + // the first block is centred on sample 0: the decoder's first output is input sample 0 + pending: vec![vec![0.0; HOP]; cfg.channels], + start: 0, + samples_in: 0, + blocks: 0, + finished: false, + // tones 4 dB (-1) to 30.4 dB (10) under their envelope; noise 14 dB above it (-1) + // to 4.1 dB (10) + tonal_db: 4.0 + 2.4 * (quality + 1.0), + noise_db: -14.0 + 0.9 * (quality + 1.0), + dead_zone: 0.8 - 0.025 * (quality + 1.0), + }) + } + + /// Channels per sample frame. + pub fn channels(&self) -> usize { + self.cfg.channels + } + + /// The quality in use, after clamping. + pub fn quality(&self) -> f32 { + self.cfg.quality + } + + /// Input samples per channel taken so far. + pub fn samples_in(&self) -> u64 { + self.samples_in + } + + /// The identification header packet (§4.2.2): the first packet of the stream. + pub fn identification(&self) -> Vec { + let mut w = BitWriter::new(); + w.write(1, 8); + w.bytes(b"vorbis"); + w.write(0, 32); + w.write(self.cfg.channels as u32, 8); + w.write(self.cfg.sample_rate, 32); + w.write(0, 32); // bit rates: unset (variable) + w.write(0, 32); + w.write(0, 32); + w.write(8, 4); // 256-sample short blocks (unused) + w.write(11, 4); // 2048-sample long blocks + w.flag(true); + w.finish() + } + + /// The setup header packet (§4.2.4): codebooks, floor, residue, mapping and mode. It follows + /// the comment header. + pub fn setup(&self) -> Vec { + let mut w = BitWriter::new(); + w.write(5, 8); + w.bytes(b"vorbis"); + w.write(self.books.len() as u32 - 1, 8); + for b in &self.books { + b.write_header(&mut w); + } + w.write(0, 6); // one time-domain transform placeholder + w.write(0, 16); + w.write(0, 6); // one floor + w.write(1, 16); + self.floor.write_header(&mut w); + w.write(0, 6); // one residue, type 2 + w.write(2, 16); + let end = (self.cfg.channels * HOP) as u32; + w.write(0, 24); + w.write(end, 24); + w.write(partition_size(self.cfg.channels) as u32 - 1, 24); + w.write(CLASSES as u32 - 1, 6); + w.write(BOOK_CLASS as u32, 8); + for c in &CASCADE { + let bits: u32 = c.iter().enumerate().map(|(j, b)| u32::from(b.is_some()) << j).sum(); + w.write(bits & 7, 3); + w.flag(bits > 7); + if bits > 7 { + w.write(bits >> 3, 5); + } + } + for c in &CASCADE { + for b in c.iter().flatten() { + w.write(*b as u32, 8); + } + } + w.write(0, 6); // one mapping, type 0 + w.write(0, 16); + w.flag(false); // one submap + w.flag(false); // no coupling + w.write(0, 2); + w.write(0, 8); // submap 0: time, floor 0, residue 0 + w.write(0, 8); + w.write(0, 8); + w.write(0, 6); // one mode: long blocks, mapping 0 + w.flag(true); + w.write(0, 16); + w.write(0, 16); + w.write(0, 8); + w.flag(true); + w.finish() + } + + /// Encodes planar samples (one slice per channel, all the same length, nominal range ±1); + /// returns the packets completed with their granule positions. NaN or infinite samples, or a + /// channel count or length mismatch, are an error. + pub fn encode(&mut self, planar: &[&[f32]]) -> Result, i64)>> { + if self.finished { + return Err(Error::InvalidArgument("Vorbis encoder: encode after finish")); + } + if planar.len() != self.cfg.channels { + return Err(Error::InvalidArgument("Vorbis encoder: one slice per channel")); + } + let len = planar.first().map_or(0, |p| p.len()); + if planar.iter().any(|p| p.len() != len) { + return Err(Error::InvalidArgument("Vorbis encoder: channels of different lengths")); + } + if planar.iter().any(|p| p.iter().any(|v| !v.is_finite())) { + return Err(Error::InvalidArgument("Vorbis encoder: NaN or infinite sample")); + } + for (b, p) in self.pending.iter_mut().zip(planar) { + b.extend_from_slice(p); + } + self.samples_in += len as u64; + self.drain() + } + + /// Encodes what remains, padded with silence; the last packet's granule position is the + /// input's length, so the decoder trims the padding (§A.2). + pub fn finish(&mut self) -> Result, i64)>> { + if self.finished { + return Ok(Vec::new()); + } + self.finished = true; + // block k ends output at k·HOP: blocks 0..=ceil(len / HOP) + let blocks = self.samples_in.div_ceil(HOP as u64) + 1; + let missing = blocks.saturating_sub(self.blocks) as usize; + self.compact(); + let need = (missing + 1) * HOP; + for b in self.pending.iter_mut() { + if b.len() < need { + b.resize(need, 0.0); + } + } + let mut out = Vec::new(); + for _ in 0..missing { + out.push(self.block()?); + } + Ok(out) + } + + fn drain(&mut self) -> Result, i64)>> { + let mut out = Vec::new(); + while self.pending.first().is_some_and(|b| b.len().saturating_sub(self.start) >= BLOCK) { + out.push(self.block()?); + } + self.compact(); + Ok(out) + } + + /// Drops the hops already encoded from the front of every channel buffer. + fn compact(&mut self) { + for b in self.pending.iter_mut() { + b.drain(..self.start.min(b.len())); + } + self.start = 0; + } + + /// Encodes the block at `start` in `pending` and advances by a hop. + fn block(&mut self) -> Result<(Vec, i64)> { + let ch = self.cfg.channels; + let mut w = BitWriter::new(); + w.write(0, 1); // audio packet; one mode, so no mode number + w.flag(true); // previous and next windows long + w.flag(true); + let mut residue = vec![0i32; ch * HOP]; + let mut any = false; + let mut x = vec![0f32; BLOCK]; + let mut coeffs = vec![0f32; HOP]; + for c in 0..ch { + let src = self.pending.get(c).and_then(|b| b.get(self.start..)).ok_or(Error::Internal("channel buffer"))?; + for (i, v) in x.iter_mut().enumerate() { + *v = src.get(i).copied().unwrap_or(0.0).clamp(-8.0, 8.0) * self.window[i]; + } + self.mdct.forward(&x, &mut coeffs, 2.0 / HOP as f64); + let peak = coeffs.iter().fold(0f32, |m, v| m.max(v.abs())); + // (a NaN peak cannot happen: samples are finite and clamped) + if peak <= 1e-7 { + w.flag(false); // floor unused: the channel is silent + continue; + } + any = true; + w.flag(true); + let want = self.floor_targets(&coeffs); + let curve = self.floor.encode(&mut w, &self.books[BOOK_FLOOR], &want, HOP); + for (k, (&v, &f)) in coeffs.iter().zip(&curve).enumerate() { + let r = if f > 0.0 { v / f } else { 0.0 }; + // a dead zone: values just past half a step are noise peaks, not worth a ±1 + let q = if r.abs() < self.dead_zone { 0.0 } else { r.round() }; + residue[k * ch + c] = if q.is_finite() { (q as i32).clamp(-MAX_RESIDUE, MAX_RESIDUE) } else { 0 }; + } + } + if any { + self.write_residue(&mut w, &residue); + } + let granule = if self.blocks == 0 { + 0 + } else { + let natural = self.blocks.saturating_mul(HOP as u64); + if self.finished { natural.min(self.samples_in) } else { natural } + }; + self.start += HOP; + self.blocks += 1; + Ok((w.finish(), i64::try_from(granule).unwrap_or(i64::MAX))) + } + + /// Floor values at the floor's points: the spectral envelope (power smoothed over a quarter of + /// the frequency, at least 8 bins, on each side) less an offset that grows with the region's tonality, from its + /// spectral flatness: noise needs a few dB of precision, tones much more. + fn floor_targets(&self, coeffs: &[f32]) -> Vec { + let n = coeffs.len(); + let mut cum = vec![0f64; n + 1]; + let mut cum_ln = vec![0f64; n + 1]; + for (i, &v) in coeffs.iter().enumerate() { + let p = f64::from(v) * f64::from(v); + cum[i + 1] = cum[i] + p; + cum_ln[i + 1] = cum_ln[i] + (p + 1e-30).ln(); + } + self.floor + .xs + .iter() + .map(|&x| { + let k = (x as usize).min(n - 1); + let half = (k / 4).max(8); + let (lo, hi) = (k.saturating_sub(half), (k + half + 1).min(n)); + let len = (hi - lo) as f64; + let am = (cum[hi] - cum[lo]) / len; + let gm = ((cum_ln[hi] - cum_ln[lo]) / len).exp(); + // spectral flatness: about -2.5 dB for noise, far below for a tone + let sfm_db = 10.0 * (gm / am.max(1e-30)).max(1e-30).log10(); + let tonality = ((-sfm_db - 2.5) / 20.0).clamp(0.0, 1.0); + let offset = tonality * f64::from(self.tonal_db) + (1.0 - tonality) * f64::from(self.noise_db); + let amp = (am.sqrt() * 10f64.powf(-offset / 20.0)).max(1e-7) as f32; + (floor::db_index(amp) + 1) / floor::MULTIPLIER as i32 + }) + .collect() + } + + /// Residue type 2 (§8.6.2 with the interleaved vector): classes per partition, then the + /// cascade's passes in the decoder's order. + fn write_residue(&self, w: &mut BitWriter, r: &[i32]) { + let partition = partition_size(self.cfg.channels); + let parts = r.len() / partition; + let classes: Vec = r.chunks(partition).map(class_of).collect(); + let per_word = self.books[BOOK_CLASS].dimensions as usize; + for pass in 0..3 { + let mut pc = 0; + while pc < parts { + if pass == 0 { + let mut e = 0usize; + for i in 0..per_word { + e = e * CLASSES + classes.get(pc + i).copied().unwrap_or(0); + } + self.books[BOOK_CLASS].put(w, e); + } + for _ in 0..per_word { + if pc >= parts { + break; + } + let class = classes[pc]; + if let Some(b) = CASCADE[class][pass] { + let book = &self.books[b]; + let dims = book.dimensions as usize; + let part = &r[pc * partition..(pc + 1) * partition]; + for chunk in part.chunks(dims) { + let v: Vec = chunk.iter().map(|&x| pass_value(x, class, pass)).collect(); + book.put(w, book.entry_of(&v)); + } + } + pc += 1; + } + } + } + } +} + +/// Relative frequency of each residue class (for the class book's code lengths). +fn class_weight(c: usize) -> f64 { + [0.3, 0.2, 0.12, 0.12, 0.1, 0.08, 0.06, 0.02].get(c).copied().unwrap_or(0.01) +} + +/// The part of residue value `v` coded in `pass` for `class`: the passes add up to `v`. +fn pass_value(v: i32, class: usize, pass: usize) -> i32 { + let split = |v: i32, step: i32| -> (i32, i32) { + let a = ((f64::from(v) / f64::from(step)).round() as i32).clamp(-7, 7); + (a * step, v - a * step) + }; + match (class, pass) { + (6, 0) => split(v, 15).0, + (6, _) => split(v, 15).1, + (7, 0) => split(v, 225).0, + (7, 1) => split(split(v, 225).1, 15).0, + (7, _) => split(split(v, 225).1, 15).1, + _ => v, + } +} + +/// The residue class of a partition: silent; ±1 with at most four nonzero values, or more; then +/// by the largest magnitude. +fn class_of(p: &[i32]) -> usize { + let m = p.iter().map(|v| v.abs()).max().unwrap_or(0); + match m { + 0 => 0, + 1 if p.iter().filter(|&&v| v != 0).count() <= 4 => 1, + 1 => 2, + 2 => 3, + 3..=4 => 4, + 5..=7 => 5, + 8..=112 => 6, + _ => 7, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/audio/src/vorbis/encoder/tests.rs b/crates/audio/src/vorbis/encoder/tests.rs new file mode 100644 index 000000000..b1ae87463 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/tests.rs @@ -0,0 +1,285 @@ +//! Unit tests, and ffmpeg (as an external oracle only) decoding the encoder's streams. + +#![allow(clippy::unwrap_used)] + +use std::path::Path; +use std::process::Command; + +use super::book::{BitWriter, assign_codewords, float32_pack}; +use super::{BLOCK, Encoder, EncoderConfig, HOP, partition_size}; + +#[test] +fn codewords_follow_the_specification_example() { + // Vorbis I §3.2.1: lengths 2 4 4 4 4 2 3 3 + let words = assign_codewords(&[2, 4, 4, 4, 4, 2, 3, 3]).unwrap(); + assert_eq!(words, [0b00, 0b0100, 0b0101, 0b0110, 0b0111, 0b10, 0b110, 0b111]); + assert!(assign_codewords(&[1, 1, 1]).is_err(), "over-subscribed"); +} + +#[test] +fn every_book_is_a_complete_prefix_code() { + let e = Encoder::new(EncoderConfig::new(48_000, 2, 5.0)).unwrap(); + for (i, b) in e.books.iter().enumerate() { + let kraft: f64 = b.lengths.iter().map(|&l| 0.5f64.powi(l as i32)).sum(); + assert!((kraft - 1.0).abs() < 1e-9, "book {i}: Kraft sum {kraft}"); + assert!(b.lengths.iter().all(|&l| (1..=20).contains(&l))); + for (a, (&wa, &la)) in b.words.iter().zip(&b.lengths).enumerate() { + for (c, (&wc, &lc)) in b.words.iter().zip(&b.lengths).enumerate() { + if a != c && la <= lc { + assert_ne!(wc >> (lc - la), wa, "book {i}: codeword {a} is a prefix of {c}"); + } + } + } + } +} + +#[test] +fn float32_pack_is_exact_for_lattice_values() { + let unpack = |x: u32| { + let mant = f64::from(x & 0x1F_FFFF); + let exp = ((x >> 21) & 0x3FF) as i32 - 788; + let v = mant * 2f64.powi(exp); + if x & 0x8000_0000 != 0 { -v } else { v } + }; + for v in [1.0, -1.0, -2.0, -4.0, -7.0, -105.0, 15.0, -1575.0, 225.0, 0.5, 3.0] { + assert_eq!(unpack(float32_pack(v)), v); + } + assert_eq!(float32_pack(0.0), 0); +} + +#[test] +fn bits_are_packed_lsb_first() { + let mut w = BitWriter::new(); + w.write(0b1, 1); + w.write(0b10, 2); + w.write(0x1F, 5); + w.write(0xABC, 12); + assert_eq!(w.finish(), [0b1111_1101, 0xBC, 0x0A]); +} + +#[test] +fn hostile_input_is_an_error_not_a_panic() { + assert!(Encoder::new(EncoderConfig::new(48_000, 0, 3.0)).is_err()); + assert!(Encoder::new(EncoderConfig::new(48_000, 9, 3.0)).is_err()); + assert!(Encoder::new(EncoderConfig::new(0, 2, 3.0)).is_err()); + assert_eq!(Encoder::new(EncoderConfig::new(48_000, 1, f32::NAN)).unwrap().cfg.quality, 6.0, "NaN quality uses the default, as the export does"); + let mut e = Encoder::new(EncoderConfig::new(44_100, 2, 3.0)).unwrap(); + assert!(e.encode(&[&[0.0; 4]]).is_err()); + assert!(e.encode(&[&[0.0; 4], &[0.0; 3]]).is_err()); + assert!(e.encode(&[&[f32::NAN; 4], &[0.0; 4]]).is_err()); + let loud = vec![1e30f32; 5000]; + assert!(!e.encode(&[&loud, &loud]).unwrap().is_empty()); + assert!(!e.finish().unwrap().is_empty()); + assert!(e.finish().unwrap().is_empty()); + assert!(e.encode(&[&[0.0; 4], &[0.0; 4]]).is_err()); +} + +#[test] +fn granules_count_the_samples_and_trim_the_end() { + for len in [0usize, 1, 1023, 1024, 1025, 48_000] { + let mut e = Encoder::new(EncoderConfig::new(48_000, 1, 3.0)).unwrap(); + let x = vec![0.1f32; len]; + let mut packets = e.encode(&[&x]).unwrap(); + packets.extend(e.finish().unwrap()); + assert_eq!(packets.len(), len.div_ceil(HOP) + 1, "len {len}"); + // packet k ends output at k·1024 samples; the last one at the input's length + let want: Vec = (0..packets.len()).map(|k| ((k * HOP) as i64).min(len as i64)).collect(); + let got: Vec = packets.iter().map(|p| p.1).collect(); + assert_eq!(got, want, "len {len}"); + } +} + +// --- ffmpeg oracle --- + +/// An Ogg Vorbis file of the three headers and the audio packets, through craft-media's writer. +fn ogg(packets: &[(Vec, i64)]) -> Vec { + let mut w = craft_media::ogg::PageWriter::new(7); + let mut out = Vec::new(); + for (i, (p, g)) in packets.iter().enumerate() { + out.extend(if i < 3 { w.header(p) } else { w.packet(p, *g) }); + } + out.extend(w.finish(None)); + out +} + +fn comment() -> Vec { + craft_media::ogg::vorbis_comment("test", &[]) +} + +/// Encodes `input` (planar) and decodes it with ffmpeg's `decoder`; returns the planar output. +/// ffmpeg's decoders to check: its own `vorbis` always, and `libvorbis` when ffmpeg has it. +fn decoders(ff: &Path) -> Vec<&'static str> { + let list = + Command::new(ff).args(["-hide_banner", "-decoders"]).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default(); + if list.lines().any(|l| l.split_whitespace().nth(1) == Some("libvorbis")) { + vec!["vorbis", "libvorbis"] + } else { + eprintln!("SKIPPED (libvorbis decoder): this ffmpeg has no libvorbis; checking its own decoder only"); + vec!["vorbis"] + } +} + +fn round_trip(input: &[Vec], rate: u32, quality: f32, decoder: &str, name: &str) -> Option<(Vec>, usize)> { + let ff = craft_media_testkit::ffmpeg_or_skip("vorbis oracle")?; + let mut e = Encoder::new(EncoderConfig::new(rate, input.len(), quality)).unwrap(); + let mut packets = vec![(e.identification(), 0), (comment(), 0), (e.setup(), 0)]; + let n = input[0].len(); + let mut at = 0; + while at < n { + let end = (at + 4410).min(n); + let s: Vec<&[f32]> = input.iter().map(|c| &c[at..end]).collect(); + packets.extend(e.encode(&s).unwrap()); + at = end; + } + packets.extend(e.finish().unwrap()); + let bytes: usize = packets[3..].iter().map(|p| p.0.len()).sum(); + let dir = craft_media_testkit::fixtures_dir("audio/vorbis-encoder"); + let path = dir.join(format!("{name}.ogg")); + std::fs::write(&path, ogg(&packets)).unwrap(); + let out = Command::new(ff) + .args(["-v", "error", "-xerror", "-c:a", decoder, "-i"]) + .arg(&path) + .args(["-f", "f32le", "-c:a", "pcm_f32le", "-"]) + .output() + .unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "{name} {decoder}: {}", String::from_utf8_lossy(&out.stderr)); + let pcm: Vec = out.stdout.as_chunks::<4>().0.iter().map(|&b| f32::from_le_bytes(b)).collect(); + let ch = input.len(); + Some(((0..ch).map(|c| pcm.iter().skip(c).step_by(ch).copied().collect()).collect(), bytes)) +} + +fn snr_db(a: &[f32], b: &[f32]) -> f64 { + let (mut s, mut e) = (0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + s += f64::from(x) * f64::from(x); + e += (f64::from(x) - f64::from(y)).powi(2); + } + 10.0 * (s.max(1e-20) / e.max(1e-20)).log10() +} + +fn music(n: usize, seed: u32) -> Vec { + let mut r = seed; + (0..n) + .map(|i| { + let t = i as f32 / 48_000.0; + r = r.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let noise = (r >> 8) as f32 / 8_388_608.0 - 1.0; + let chord: f32 = [220.0f32, 277.18, 329.63, 440.0] + .iter() + .enumerate() + .map(|(k, f)| (0.2 / (k + 1) as f32) * (2.0 * std::f32::consts::PI * f * t).sin()) + .sum(); + chord + 0.01 * noise + }) + .collect() +} + +/// Harmonic chords changing every half second, with decaying noise bursts (music-like). +fn chords(n: usize, seed: u32) -> Vec { + let mut r = seed; + let notes = [220.0f32, 277.2, 329.6, 440.0, 349.2, 523.3, 392.0, 659.3]; + (0..n) + .map(|i| { + let t = i as f32 / 48_000.0; + let chord = (t * 2.0) as usize; + let mut s = 0.0; + for k in 0..3 { + let f = notes[(chord * 3 + k * 2) % notes.len()]; + for h in 1..6 { + s += (2.0 * std::f32::consts::PI * f * h as f32 * t).sin() * 0.08 / h as f32; + } + } + r = r.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let env = (-(t * 2.0).fract() * 3.0).exp(); + s * (0.5 + 0.5 * env) + 0.02 * ((r >> 8) as f32 / 8_388_608.0 - 1.0) * env + }) + .collect() +} + +/// ffmpeg's own Vorbis decoder and libvorbis read every stream exactly as long as the input, +/// with SNR floors about 6 dB (chords 4 dB) under what the encoder measured when written, and bit +/// rates near libvorbis's for the same quality. +/// A signal, and per quality the SNR floor and the bit-rate range (kbit/s). +type Case = (&'static str, Vec>, [(f32, f64, std::ops::Range); 5]); + +#[test] +fn ffmpeg_decodes_every_quality() { + let Some(ff) = craft_media_testkit::ffmpeg_or_skip("vorbis oracle") else { return }; + let n = 48_000 * 3; + let cases: [Case; 2] = [ + ( + "music", + vec![music(n, 1), music(n, 2).iter().map(|v| v * 0.7).collect()], + [(-1.0, 3.0, 15..90), (0.0, 6.5, 20..110), (3.0, 12.0, 60..180), (6.0, 18.5, 120..280), (10.0, 25.5, 180..400)], + ), + ( + "chords", + vec![chords(n, 1), chords(n, 2).iter().map(|v| v * 0.8).collect()], + [(-1.0, 4.5, 20..90), (0.0, 6.0, 25..110), (3.0, 10.0, 70..200), (6.0, 14.0, 130..300), (10.0, 19.0, 180..420)], + ), + ]; + for (name, input, levels) in &cases { + for (q, floor, kbps) in levels { + for decoder in decoders(&ff) { + let Some((out, bytes)) = round_trip(input, 48_000, *q, decoder, &format!("{name}{q}")) else { return }; + assert!(out.iter().all(|c| c.len() == n), "{name} q{q} {decoder}: length {}", out[0].len()); + let snr = snr_db(&input[0][4096..], &out[0][4096..]); + assert!(snr >= *floor, "{name} q{q} {decoder}: {snr:.2} dB < {floor}"); + let rate = bytes * 8 / 3 / 1000; + assert!(kbps.contains(&rate), "{name} q{q}: {rate} kbit/s outside {kbps:?}"); + } + } + } +} + +/// Mono, 44.1 kHz, 3.0, 5.1 and 6.1 streams decode too, with libvorbis as well (which reads each +/// residue partition from channel 0); a silent channel costs one bit per block. +#[test] +fn channel_counts_and_rates() { + let Some(ff) = craft_media_testkit::ffmpeg_or_skip("vorbis oracle") else { return }; + let n = 44_100; + for (rate, ch) in [(44_100u32, 1usize), (22_050, 2), (48_000, 3), (48_000, 6), (48_000, 7)] { + let mut input: Vec> = (0..ch).map(|c| chords(n, c as u32 + 1).iter().map(|v| v * (1.0 - 0.1 * c as f32)).collect()).collect(); + if ch == 6 { + input[3] = vec![0.0; n]; + } + for decoder in decoders(&ff) { + let Some((mut out, _)) = round_trip(&input, rate, 5.0, decoder, &format!("ch{ch}_{rate}_{decoder}")) else { return }; + if decoder == "vorbis" { + // ffmpeg's decoder gives WAV order (5.1: FL FR FC LFE BL BR); the stream is in Vorbis + // order (L C R Ls Rs LFE), which libvorbis passes through + let wav_to_vorbis: &[usize] = match ch { + 3 => &[0, 2, 1], + 6 => &[0, 2, 1, 4, 5, 3], + 7 => &[0, 2, 1, 5, 6, 4, 3], + _ => &[0, 1], + }; + if ch > 2 { + out = wav_to_vorbis.iter().map(|&i| out[i].clone()).collect(); + } + } + assert_eq!(out.len(), ch); + for (c, (a, b)) in input.iter().zip(&out).enumerate() { + assert_eq!(b.len(), n, "{ch} ch {rate} Hz {decoder}: channel {c} length"); + if a.iter().all(|&v| v == 0.0) { + assert!(b.iter().all(|v| v.abs() < 1e-6), "silent channel {c}"); + } else { + let snr = snr_db(&a[4096..], &b[4096..]); + assert!(snr > 8.0, "{ch} ch {rate} Hz {decoder} channel {c}: {snr:.1} dB"); + } + } + } + } +} + +/// Every partition holds whole sample frames (libvorbis decodes each one from channel 0), splits +/// the interleaved residue evenly and fits every book's dimension. +#[test] +fn partitions_hold_whole_frames() { + for ch in 1..=8 { + let p = partition_size(ch); + assert_eq!(p % ch, 0, "{ch} channels"); + assert_eq!((ch * BLOCK / 2) % p, 0, "{ch} channels"); + assert_eq!(p % 4, 0, "{ch} channels"); + } +} diff --git a/crates/audio/src/vorbis/mod.rs b/crates/audio/src/vorbis/mod.rs new file mode 100644 index 000000000..15b81bb26 --- /dev/null +++ b/crates/audio/src/vorbis/mod.rs @@ -0,0 +1,7 @@ +//! Vorbis I: the pure-Rust [`decoder`] (feature `vorbis-decode`) and [`encoder`] (feature +//! `vorbis-encode`). `craft_audio::decode` still reads Vorbis files through symphonia. + +#[cfg(feature = "vorbis-decode")] +pub mod decoder; +#[cfg(feature = "vorbis-encode")] +pub mod encoder; diff --git a/crates/audio/src/wav_markers.rs b/crates/audio/src/wav_markers.rs new file mode 100644 index 000000000..0bf4e7568 --- /dev/null +++ b/crates/audio/src/wav_markers.rs @@ -0,0 +1,721 @@ +//! Markers a WAV file carries, read from its RIFF chunks. +//! +//! Two encodings are read into separate lists for the caller to map and merge: +//! - **Cue points** (the standard): a `cue ` chunk with one point per marker, named by `labl` (or +//! `note`) sub-chunks of a `LIST` `adtl` chunk, and given a length by `ltxt`. +//! - **XMP** (Adobe's tools): an `_PMX` chunk holding an XMP packet whose `xmpDM:markers` list has +//! one entry per marker (`xmpDM:startTime`, `xmpDM:duration`, `xmpDM:name`), counted in frames +//! of `xmpDM:frameRate` (`f44100` for samples at 44.1 kHz), or with an explicit +//! FrameCount rate suffix (`15f24`, `15f30000s1001`). Durations with a distinct rate +//! are converted to the marker start rate without app-specific time quantization. +//! +//! RF64 files (WAVs over 4 GB) carry a `0xFFFFFFFF` size for a chunk too big for 32 bits and give its real size in a +//! `ds64` chunk; those sizes are resolved so the chunks after the audio are still found. +//! +//! The file is untrusted input: every read is bounds-checked, sizes use checked arithmetic, and +//! the number of markers, of `adtl` sub-chunks looked at and the size of the XMP packet are capped. + +use std::collections::{HashMap, HashSet}; + +/// Marker coordinates before app-specific time quantization. Explicit XMP duration +/// rates are normalized to the start coordinate rate; bare counts retain the legacy +/// track/file-rate interpretation. +#[derive(Clone, Debug, PartialEq)] +pub struct Marker { + /// Start in frames at `rate`. + pub start: f64, + /// Duration in frames at `rate`. + pub duration: f64, + /// Frames per second; consumers decide how invalid or absent rates map to their timeline. + pub rate: f64, + /// Label text. + pub name: String, +} +/// Separate source lists: rounding, deduplication, ordering and labels belong to the caller. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Markers { + /// RIFF cue/adtl markers in file order. + pub cue: Vec, + /// XMP markers in packet order. + pub xmp: Vec, + /// A chunk-inventory or cue-label retention limit omitted metadata. Marker coordinates + /// remain available when only their label was omitted. Existing marker/XMP prefix limits + /// are separate and do not set this flag. + pub limited: bool, +} + +/// Most markers read from one file. +pub const MAX_MARKERS: usize = 10_000; +/// Largest XMP packet read (bytes). +const MAX_XMP: usize = 4 << 20; +/// Most `adtl` sub-chunks (`labl`, `note`, `ltxt`) looked at in one file: a few per cue point is plenty. +const MAX_ADTL_RECORDS: usize = 4 * MAX_MARKERS; +/// Most entries read from an RF64 file's `ds64` size table. +const MAX_DS64_TABLE: usize = 1_024; +/// Maximum retained RIFF chunk descriptors (including empty chunks). +pub const MAX_CHUNKS: usize = 100_000; +/// Maximum UTF-8 bytes in one retained cue label. +pub const MAX_LABEL_BYTES: usize = 64 * 1024; +/// Aggregate cue label bytes, enforced separately for the name map and emitted markers. +pub const MAX_LABEL_TOTAL_BYTES: usize = 4 * 1024 * 1024; + +fn u32_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_le_bytes(s.try_into().ok()?)) +} + +fn u64_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(8)?)?; + Some(u64::from_le_bytes(s.try_into().ok()?)) +} + +/// The text of a NUL-terminated label (the rest of the chunk), lossily decoded. +fn label(b: &[u8]) -> Option { + // Look only as far as one label can be retained; never copy an arbitrary chunk body. + let end = b.iter().take(MAX_LABEL_BYTES + 1).position(|&c| c == 0).unwrap_or(b.len()); + if end > MAX_LABEL_BYTES { + return None; + } + let text = String::from_utf8_lossy(b.get(..end)?); + let text = text.trim(); + (text.len() <= MAX_LABEL_BYTES).then(|| text.to_string()) +} + +/// Whether `bytes` start a RIFF/WAVE file. +pub fn is_wav(bytes: &[u8]) -> bool { + matches!(bytes.get(0..4), Some(b"RIFF" | b"RF64")) && bytes.get(8..12) == Some(b"WAVE") +} + +/// The sizes an RF64 file's `ds64` chunk gives for chunks too big for the 32-bit size field. +struct Ds64 { + /// The `data` chunk's size. + data: u64, + /// Other chunks: `(id, size)`. + table: Vec<([u8; 4], u64)>, +} + +impl Ds64 { + /// The real size of chunk `id`, when the file says. + fn size_of(&self, id: &[u8; 4]) -> Option { + if id == b"data" { Some(self.data) } else { self.table.iter().find(|(t, _)| t == id).map(|(_, size)| *size) } + } +} + +/// The `ds64` chunk of an RF64 file (`RF64`, size, `WAVE`, then `ds64`); `None` for any other file or one whose +/// `ds64` doesn't fit. +fn ds64(bytes: &[u8]) -> Option { + if bytes.get(0..4) != Some(b"RF64") || bytes.get(12..16) != Some(b"ds64") { + return None; + } + let size = usize::try_from(u32_at(bytes, 16)?).ok()?; + let body = bytes.get(20..20usize.checked_add(size)?)?; + // riff size (8), data size (8), sample count (8), table length (4), then `(id, size)` entries of 12 bytes + let data = u64_at(body, 8)?; + let entries = usize::try_from(u32_at(body, 24)?).ok()?; + let mut table = Vec::new(); + for i in 0..entries.min(MAX_DS64_TABLE) { + let at = 28usize.checked_add(i.checked_mul(12)?)?; + let id = <[u8; 4]>::try_from(body.get(at..at.checked_add(4)?)?).ok()?; + table.push((id, u64_at(body, at + 4)?)); + } + Some(Ds64 { data, table }) +} + +/// The chunks of a WAVE file as `(id, body)`, stopping at the first one that doesn't fit. +fn chunks<'a>(bytes: &'a [u8], limited: &mut bool) -> Vec<([u8; 4], &'a [u8])> { + let big = ds64(bytes); + let mut out = Vec::new(); + let mut at = 12usize; + while let Some(head) = bytes.get(at..at.saturating_add(8)) { + if out.len() == MAX_CHUNKS { + *limited = true; + break; + } + let (Ok(id), Some(field)) = (<[u8; 4]>::try_from(&head[..4]), u32_at(head, 4)) else { break }; + // In an RF64 file a size field of 0xFFFFFFFF stands for the size `ds64` gives. + let size = match &big { + Some(d) if field == u32::MAX => d.size_of(&id).unwrap_or(u64::from(field)), + _ => u64::from(field), + }; + let start = at.saturating_add(8); + let Some(end) = usize::try_from(size).ok().and_then(|n| start.checked_add(n)) else { break }; + let Some(body) = bytes.get(start..end) else { break }; + out.push((id, body)); + // Chunks are padded to an even size. + at = end.saturating_add(end & 1); + } + out +} + +/// Read bounded cue/adtl and XMP metadata without interpreting application timeline policy. +pub fn read(bytes: &[u8]) -> Markers { + if !is_wav(bytes) { + return Markers::default(); + } + let mut limited = false; + let chunks = chunks(bytes, &mut limited); + let rate = chunks.iter().find(|(id, _)| id == b"fmt ").and_then(|(_, b)| u32_at(b, 4)).map_or(0.0, f64::from); + let cue = cue_markers(&chunks, rate, &mut limited); + let xmp = chunks.iter().find(|(id, _)| id == b"_PMX").map_or_else(Vec::new, |(_, xmp)| xmp_markers(xmp, rate)); + Markers { cue, xmp, limited } +} + +/// Cue points named and sized by the `adtl` list. +fn cue_markers(chunks: &[([u8; 4], &[u8])], rate: f64, limited: &mut bool) -> Vec { + let Some((_, cue)) = chunks.iter().find(|(id, _)| id == b"cue ") else { return Vec::new() }; + let count = (u32_at(cue, 0).unwrap_or(0) as usize).min(MAX_MARKERS); + // The cue points first: `(id, offset in samples)`. + let mut points = Vec::new(); + for i in 0..count { + let Some(point) = cue.get(4usize.saturating_add(i.saturating_mul(24))..) else { break }; + let (Some(id), Some(offset)) = (u32_at(point, 0), u32_at(point, 20)) else { break }; + points.push((id, offset)); + } + // Only the names and lengths of those ids are kept, so a hostile `adtl` list cannot grow them past the cue count, + // and each record is a lookup, not a scan. + let wanted: HashSet = points.iter().map(|(id, _)| *id).collect(); + let mut names: HashMap = HashMap::new(); + let mut lengths: HashMap = HashMap::new(); + let mut name_bytes = 0usize; + let mut records = 0usize; + 'lists: for (_, list) in chunks.iter().filter(|(id, b)| id == b"LIST" && b.get(0..4) == Some(b"adtl")) { + let mut at = 4usize; + while let Some(head) = list.get(at..at.saturating_add(8)) { + let (Ok(id), Some(size)) = (<[u8; 4]>::try_from(&head[..4]), u32_at(head, 4)) else { break }; + let start = at.saturating_add(8); + let Some(end) = start.checked_add(size as usize) else { break }; + let Some(body) = list.get(start..end) else { break }; + records += 1; + if records > MAX_ADTL_RECORDS { + break 'lists; + } + if let Some(cue_id) = u32_at(body, 0).filter(|c| wanted.contains(c)) { + match &id { + // A `labl` is the name; a `note` only when there is none. + b"labl" | b"note" if id == *b"labl" || !names.contains_key(&cue_id) => { + let without_old = name_bytes.saturating_sub(names.get(&cue_id).map_or(0, String::len)); + let text = label(body.get(4..).unwrap_or_default()) + .filter(|text| text.len() <= MAX_LABEL_TOTAL_BYTES.saturating_sub(without_old)) + .unwrap_or_else(|| { + *limited = true; + String::new() + }); + name_bytes = without_old + text.len(); + names.insert(cue_id, text); + } + // The first `ltxt` of a cue point gives its length. + b"ltxt" => { + lengths.entry(cue_id).or_insert_with(|| u32_at(body, 4).unwrap_or(0)); + } + _ => {} + } + } + at = end.saturating_add(end & 1); + } + } + let mut emitted_bytes = 0usize; + points + .into_iter() + .map(|(id, offset)| { + let comment = match names.get(&id) { + Some(text) if text.len() <= MAX_LABEL_TOTAL_BYTES.saturating_sub(emitted_bytes) => { + emitted_bytes += text.len(); + text.clone() + } + Some(_) => { + *limited = true; + String::new() + } + None => String::new(), + }; + let length = lengths.get(&id).copied().unwrap_or(0); + Marker { start: f64::from(offset), duration: f64::from(length), rate, name: comment } + }) + .collect() +} + +/// The text of `name` in an XMP entry, as an attribute (`name="v"`) or an element +/// (`v`). +fn xmp_value(entry: &str, name: &str) -> Option { + // Each entry starts just after ` in_tag = true, + b'>' => in_tag = false, + b'\'' | b'"' if in_tag => { + let quote = bytes[at]; + at += 1; + while at < bytes.len() && bytes[at] != quote { + at += 1; + } + } + _ if in_tag && (at == 0 || xml_space(bytes[at - 1])) && bytes[at..].starts_with(name.as_bytes()) => { + let mut value = at + name.len(); + while value < bytes.len() && xml_space(bytes[value]) { + value += 1; + } + if bytes.get(value) == Some(&b'=') { + value += 1; + while value < bytes.len() && xml_space(bytes[value]) { + value += 1; + } + if let Some("e @ (b'\'' | b'"')) = bytes.get(value) { + let start = value + 1; + let end = bytes.get(start..)?.iter().position(|&b| b == quote)? + start; + return Some(unescape(entry.get(start..end)?)); + } + } + } + _ => {} + } + at += 1; + } + let open = format!("<{name}>"); + let i = entry.find(&open)?; + let rest = entry.get(i + open.len()..)?; + Some(unescape(rest.get(..rest.find('<')?)?)) +} + +fn xml_space(b: u8) -> bool { + matches!(b, b' ' | b'\t' | b'\r' | b'\n') +} + +fn unescape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(i) = rest.find('&') { + out.push_str(rest.get(..i).unwrap_or_default()); + let tail = rest.get(i..).unwrap_or_default(); + let Some(semi) = tail.as_bytes().iter().take(11).position(|b| *b == b';') else { + out.push('&'); + rest = tail.get(1..).unwrap_or_default(); + continue; + }; + let ent = tail.get(1..semi).unwrap_or_default(); + match ent { + "amp" => out.push('&'), + "lt" => out.push('<'), + "gt" => out.push('>'), + "quot" => out.push('"'), + "apos" => out.push('\''), + _ => { + let code = ent + .strip_prefix("#x") + .and_then(|h| u32::from_str_radix(h, 16).ok()) + .or_else(|| ent.strip_prefix('#').and_then(|d| d.parse().ok())); + match code.and_then(char::from_u32) { + Some(c) => out.push(c), + None => out.push_str(tail.get(..=semi).unwrap_or_default()), + } + } + } + rest = tail.get(semi + 1..).unwrap_or_default(); + } + out.push_str(rest); + out.trim().to_string() +} + +/// A frame rate as XMP writes it: `f44100`, or `f30000s1001` (rate over scale). +fn xmp_rate(text: &str) -> Option { + let t = text.trim().strip_prefix('f')?; + let (num, den) = t.split_once('s').unwrap_or((t, "1")); + let (n, d): (f64, f64) = (num.parse().ok()?, den.parse().ok()?); + (n.is_finite() && d.is_finite() && n > 0.0 && d > 0.0 && (n / d).is_finite() && n / d > 0.0).then_some(n / d) +} + +/// Adobe XMP FrameCount: a count optionally followed by `fRATE[sSCALE]`. +/// Bare counts retain the caller's legacy track/file-rate interpretation. +fn xmp_count(text: &str, default_rate: f64) -> Option<(f64, f64)> { + let text = text.trim(); + let (count, rate) = match text.find('f') { + Some(at) => (text.get(..at)?, xmp_rate(text.get(at..)?)?), + None => (text, default_rate), + }; + let count: f64 = count.parse().ok()?; + (count.is_finite() && rate.is_finite() && rate > 0.0).then_some((count, rate)) +} + +/// The markers of an XMP packet's `xmpDM:markers` entries. +fn xmp_markers(packet: &[u8], file_rate: f64) -> Vec { + let text = String::from_utf8_lossy(packet.get(..packet.len().min(MAX_XMP)).unwrap_or_default()); + let mut out = Vec::new(); + // The frame rate belongs to the track an entry follows. + let mut rate = file_rate; + for entry in text.split("= MAX_MARKERS { + break; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TimedMarker { + time: f64, + duration: f64, + comment: String, + } + fn read(bytes: &[u8]) -> Vec { + let metadata = super::read(bytes); + let time = |frames: f64, rate: f64| if rate > 0.0 && frames.is_finite() { (frames / rate).max(0.0) } else { 0.0 }; + let map = |m: Marker| TimedMarker { time: time(m.start, m.rate), duration: time(m.duration, m.rate), comment: m.name }; + let mut out: Vec<_> = metadata.cue.into_iter().map(map).collect(); + let mut seen: HashSet<_> = out.iter().map(|m| (m.comment.clone(), m.time.to_bits())).collect(); + for m in metadata.xmp.into_iter().map(map) { + if seen.insert((m.comment.clone(), m.time.to_bits())) { + out.push(m); + } + } + out.truncate(MAX_MARKERS); + out.sort_by(|a, b| a.time.total_cmp(&b.time)); + out + } + + fn chunk(id: &[u8; 4], body: &[u8]) -> Vec { + let mut v = id.to_vec(); + v.extend((body.len() as u32).to_le_bytes()); + v.extend(body); + if body.len() % 2 == 1 { + v.push(0); + } + v + } + + fn fmt(rate: u32) -> Vec { + let mut b = Vec::new(); + b.extend(1u16.to_le_bytes()); // PCM + b.extend(1u16.to_le_bytes()); // mono + b.extend(rate.to_le_bytes()); + b.extend((rate * 2).to_le_bytes()); + b.extend(2u16.to_le_bytes()); + b.extend(16u16.to_le_bytes()); + chunk(b"fmt ", &b) + } + + fn wav(chunks: &[Vec]) -> Vec { + let body: Vec = chunks.iter().flatten().copied().collect(); + let mut v = b"RIFF".to_vec(); + v.extend((body.len() as u32 + 4).to_le_bytes()); + v.extend(b"WAVE"); + v.extend(body); + v + } + + fn cue(points: &[(u32, u32)]) -> Vec { + let mut b = (points.len() as u32).to_le_bytes().to_vec(); + for (id, offset) in points { + b.extend(id.to_le_bytes()); + b.extend(0u32.to_le_bytes()); + b.extend(b"data"); + b.extend(0u32.to_le_bytes()); + b.extend(0u32.to_le_bytes()); + b.extend(offset.to_le_bytes()); + } + chunk(b"cue ", &b) + } + + fn labl(id: &[u8; 4], cue_id: u32, text: &str) -> Vec { + let mut b = cue_id.to_le_bytes().to_vec(); + b.extend(text.as_bytes()); + b.push(0); + chunk(id, &b) + } + + fn adtl(subs: &[Vec]) -> Vec { + let mut b = b"adtl".to_vec(); + b.extend(subs.iter().flatten()); + chunk(b"LIST", &b) + } + + #[test] + fn cue_points_are_named_by_the_adtl_list_and_timed_in_samples() { + let file = wav(&[ + fmt(44100), + chunk(b"data", &[0; 8]), + cue(&[(2, 88200), (1, 22050)]), + adtl(&[labl(b"labl", 1, "SEQ01_Prologue"), labl(b"labl", 2, "SEQ02_Vallee_P1_Agriculture")]), + ]); + let m = read(&file); + assert_eq!(m.len(), 2); + assert_eq!((m[0].comment.as_str(), m[0].time), ("SEQ01_Prologue", 0.5)); + assert_eq!((m[1].comment.as_str(), m[1].time), ("SEQ02_Vallee_P1_Agriculture", 2.0)); + } + + #[test] + fn a_note_names_a_cue_only_when_it_has_no_label_and_ltxt_gives_a_length() { + let mut ltxt = 1u32.to_le_bytes().to_vec(); + ltxt.extend(44100u32.to_le_bytes()); + ltxt.extend([0; 16]); + let file = wav(&[ + fmt(44100), + cue(&[(1, 0), (2, 44100)]), + adtl(&[labl(b"note", 1, "from note"), chunk(b"ltxt", <xt), labl(b"labl", 2, "named"), labl(b"note", 2, "ignored")]), + ]); + let m = read(&file); + assert_eq!((m[0].comment.as_str(), m[0].duration), ("from note", 1.0)); + assert_eq!(m[1].comment, "named"); + } + + const XMP_ELEMENTS: &str = r#"MarkersCuef44100441000One & Two13230022050Three"#; + + #[test] + fn xmp_markers_are_read_as_elements_in_frames_of_the_track_rate() { + let file = wav(&[fmt(48000), chunk(b"_PMX", XMP_ELEMENTS.as_bytes())]); + let m = read(&file); + assert_eq!(m.len(), 2); + // 44100 frames at f44100 is one second, whatever the file's own rate. + assert_eq!((m[0].comment.as_str(), m[0].time), ("One & Two", 1.0)); + assert_eq!((m[1].comment.as_str(), m[1].time, m[1].duration), ("Three", 3.0, 0.5)); + } + + #[test] + fn xmp_markers_are_read_as_attributes_and_use_the_file_rate_without_a_track_rate() { + let xmp = r#""#; + let m = read(&wav(&[fmt(48000), chunk(b"_PMX", xmp.as_bytes())])); + assert_eq!((m[0].comment.as_str(), m[0].time), ("Attr é", 0.5)); + } + + #[test] + fn a_marker_in_both_encodings_is_listed_once() { + let xmp = r#""#; + let file = wav(&[fmt(44100), cue(&[(1, 44100)]), adtl(&[labl(b"labl", 1, "Same")]), chunk(b"_PMX", xmp.as_bytes())]); + let names: Vec = read(&file).into_iter().map(|m| m.comment).collect(); + assert_eq!(names, ["Same", "Only XMP"]); + } + + #[test] + fn damaged_or_hostile_files_read_as_far_as_they_go_without_panicking() { + assert!(read(b"").is_empty()); + assert!(read(b"RIFF").is_empty()); + assert!(read(b"not a wav file at all").is_empty()); + let good = wav(&[fmt(44100), cue(&[(1, 44100)]), adtl(&[labl(b"labl", 1, "Kept")])]); + // Every truncation is safe. + for n in 0..good.len() { + let _ = read(&good[..n]); + } + // A cue count far beyond the chunk, and chunk sizes past the end of the file. + let mut huge = 0xFFFF_FFFFu32.to_le_bytes().to_vec(); + huge.extend([0; 24]); + let m = read(&wav(&[fmt(44100), chunk(b"cue ", &huge)])); + assert!(m.len() <= 1); + let mut lying = good.clone(); + lying.extend(b"LIST\xff\xff\xff\xffadtl"); + assert_eq!(read(&lying).len(), 1); + // No sample rate: times are zero, not a division by zero. + let m = read(&wav(&[cue(&[(1, 44100)])])); + assert_eq!(m[0].time, 0.0); + } + + /// A chunk whose size field says `field` (an RF64 file's `0xFFFFFFFF`) while its body is `body`. + fn chunk_with_size_field(id: &[u8; 4], field: u32, body: &[u8]) -> Vec { + let mut v = id.to_vec(); + v.extend(field.to_le_bytes()); + v.extend(body); + if body.len() % 2 == 1 { + v.push(0); + } + v + } + + /// An RF64 `ds64` chunk: the `data` chunk's size and a table of other chunks' sizes. + fn ds64_chunk(data_size: u64, table: &[([u8; 4], u64)]) -> Vec { + let mut b = 0u64.to_le_bytes().to_vec(); // riff size (not used) + b.extend(data_size.to_le_bytes()); + b.extend(0u64.to_le_bytes()); // sample count + b.extend((table.len() as u32).to_le_bytes()); + for (id, size) in table { + b.extend(id); + b.extend(size.to_le_bytes()); + } + chunk(b"ds64", &b) + } + + fn rf64(chunks: &[Vec]) -> Vec { + let body: Vec = chunks.iter().flatten().copied().collect(); + let mut v = b"RF64".to_vec(); + v.extend(u32::MAX.to_le_bytes()); + v.extend(b"WAVE"); + v.extend(body); + v + } + + #[test] + fn rf64_markers_after_a_data_chunk_of_sentinel_size_are_read() { + let audio = [0u8; 8]; + let file = rf64(&[ + ds64_chunk(audio.len() as u64, &[]), + fmt(44100), + chunk_with_size_field(b"data", u32::MAX, &audio), + cue(&[(1, 44100)]), + adtl(&[labl(b"labl", 1, "After the audio")]), + ]); + let m = read(&file); + assert_eq!(m.len(), 1); + assert_eq!((m[0].comment.as_str(), m[0].time), ("After the audio", 1.0)); + } + + #[test] + fn rf64_sizes_of_other_chunks_come_from_the_ds64_table() { + let junk = [7u8; 6]; + let tail = || [cue(&[(1, 8000)]), adtl(&[labl(b"labl", 1, "Found")])].concat(); + let with_entry = rf64(&[ds64_chunk(0, &[(*b"junk", junk.len() as u64)]), fmt(8000), chunk_with_size_field(b"junk", u32::MAX, &junk), tail()]); + assert_eq!(read(&with_entry)[0].comment, "Found"); + // Without the table entry the sentinel is all there is, and what follows is not reached. + let without = rf64(&[ds64_chunk(0, &[]), fmt(8000), chunk_with_size_field(b"junk", u32::MAX, &junk), tail()]); + assert!(read(&without).is_empty()); + } + + #[test] + fn hostile_rf64_size_tables_read_as_far_as_they_go_without_panicking() { + // sizes that overflow when added to an offset + for data in [u64::MAX, u64::MAX - 7, 1 << 63] { + let file = + rf64(&[ds64_chunk(data, &[(*b"junk", u64::MAX)]), fmt(8000), chunk_with_size_field(b"data", u32::MAX, &[0; 4]), cue(&[(1, 0)])]); + assert!(read(&file).is_empty()); + } + // a table that claims far more entries than its chunk holds + let mut liar = ds64_chunk(0, &[]); + liar[8 + 24..8 + 28].copy_from_slice(&u32::MAX.to_le_bytes()); + let _ = read(&rf64(&[liar, fmt(8000), cue(&[(1, 0)])])); + // every truncation of a good RF64 file is safe + let good = rf64(&[ + ds64_chunk(4, &[]), + fmt(44100), + chunk_with_size_field(b"data", u32::MAX, &[0; 4]), + cue(&[(1, 44100)]), + adtl(&[labl(b"labl", 1, "Kept")]), + ]); + assert_eq!(read(&good).len(), 1); + for n in 0..good.len() { + let _ = read(&good[..n]); + } + } + + #[test] + fn a_huge_adtl_list_is_read_in_linear_time_and_only_for_the_cue_points_that_exist() { + // Records for ids that have no cue point are skipped, not stored, and the number looked at is capped. + let junk = |n: u32| (1000..1000 + n).map(|id| labl(b"labl", id, "n")).collect::>(); + let started = std::time::Instant::now(); + // the real label comes first: read + let mut subs = vec![labl(b"labl", 1, "Real")]; + subs.extend(junk(100_000)); + let m = read(&wav(&[fmt(44100), cue(&[(1, 44100)]), adtl(&subs)])); + assert_eq!(m[0].comment, "Real"); + // it comes after more records than are looked at: not read, and the marker is still there + let mut subs = junk(MAX_ADTL_RECORDS as u32 + 10); + subs.push(labl(b"labl", 1, "Too late")); + let m = read(&wav(&[fmt(44100), cue(&[(1, 44100)]), adtl(&subs)])); + assert_eq!((m.len(), m[0].comment.as_str()), (1, "")); + assert!(started.elapsed() < std::time::Duration::from_secs(5), "took {:?}", started.elapsed()); + } + + #[test] + fn metadata_keeps_original_coordinates_and_separate_sources() { + let xmp = br#""#; + let file = wav(&[fmt(44100), cue(&[(1, 1)]), adtl(&[labl(b"labl", 1, "Same")]), chunk(b"_PMX", xmp)]); + let data = super::read(&file); + assert_eq!(data.cue[0].start, 1.0); + assert_eq!(data.cue[0].rate, 44100.0); + assert_eq!(data.xmp[0].start, 1.0); + assert_eq!(data.xmp[0].duration, 2.0); + assert_eq!(data.cue.len(), 1); + assert_eq!(data.xmp.len(), 1); + } + + #[test] + fn repeated_unterminated_entities_preserve_text_with_bounded_lookahead() { + let text = "&".repeat(100_000); + assert_eq!(unescape(&text), text); + assert_eq!(unescape("A A & &unknown;"), "A A & &unknown;"); + } + #[test] + fn repeated_cue_ids_cannot_multiply_label_storage() { + let text = "x".repeat(MAX_LABEL_BYTES); + let points: Vec<_> = (0..MAX_MARKERS).map(|i| (1, i as u32)).collect(); + let file = wav(&[fmt(44100), cue(&points), adtl(&[labl(b"labl", 1, &text)])]); + let metadata = super::read(&file); + assert_eq!(metadata.cue.len(), MAX_MARKERS); + assert_eq!(metadata.cue.iter().map(|m| m.name.len()).sum::(), MAX_LABEL_TOTAL_BYTES); + assert!(metadata.limited); + assert_eq!(metadata.cue[0].name, text); + assert!(metadata.cue[MAX_MARKERS - 1].name.is_empty()); + assert_eq!(metadata.cue[MAX_MARKERS - 1].start, (MAX_MARKERS - 1) as f64); + } + + #[test] + fn cue_name_map_and_single_label_are_bounded() { + let count = MAX_LABEL_TOTAL_BYTES / MAX_LABEL_BYTES + 2; + let text = "x".repeat(MAX_LABEL_BYTES); + let points: Vec<_> = (0..count as u32).map(|i| (i, i)).collect(); + let labels: Vec<_> = (0..count as u32).map(|i| labl(b"labl", i, &text)).collect(); + let metadata = super::read(&wav(&[fmt(44100), cue(&points), adtl(&labels)])); + assert!(metadata.limited); + assert_eq!(metadata.cue.iter().map(|m| m.name.len()).sum::(), MAX_LABEL_TOTAL_BYTES); + let oversized = "x".repeat(MAX_LABEL_BYTES + 1); + let metadata = super::read(&wav(&[fmt(44100), cue(&[(1, 3)]), adtl(&[labl(b"labl", 1, &oversized)])])); + assert!(metadata.limited); + assert_eq!(metadata.cue[0].start, 3.0); + assert!(metadata.cue[0].name.is_empty()); + } + + #[test] + fn empty_chunk_inventory_is_bounded() { + let empty = chunk(b"junk", &[]); + let many = empty.repeat(MAX_CHUNKS + 1); + let metadata = super::read(&wav(&[many, fmt(44100), cue(&[(1, 1)])])); + assert!(metadata.limited); + assert!(metadata.cue.is_empty()); + } + + #[test] + fn entity_lookahead_keeps_previous_semicolon_boundary() { + assert_eq!(unescape("A"), "A"); + assert_eq!(unescape("A"), "A"); + } + #[test] + fn xmp_quotes_spacing_and_attribute_boundaries() { + let packet = br#""#; + let markers = xmp_markers(packet, 48000.0); + assert_eq!(markers.len(), 1); + assert_eq!((markers[0].start, markers[0].duration, markers[0].rate), (24000.0, 12000.0, 48000.0)); + assert_eq!(markers[0].name, "single & quoted"); + let spoof = r#" label=" xmpDM:startTime='7'" otherxmpDM:startTime='8' xmpDM:startTime = '9'/>"#; + assert_eq!(xmp_value(spoof, "xmpDM:startTime").as_deref(), Some("9")); + assert!(xmp_value(" xmpDM:startTime='unterminated", "xmpDM:startTime").is_none()); + } + + #[test] + fn xmp_frame_counts_preserve_explicit_and_mixed_rates() { + let packet = br#""#; + let markers = xmp_markers(packet, 44100.0); + assert_eq!(markers.len(), 3); + assert_eq!((markers[0].start, markers[0].rate), (15.0, 24.0)); + assert!((markers[0].duration / markers[0].rate - 0.5005).abs() < 1e-12); + assert_eq!((markers[1].start, markers[1].duration, markers[1].rate), (48000.0, 24000.0, 48000.0)); + assert_eq!((markers[2].start, markers[2].duration, markers[2].rate), (15.0, 12.0, 24.0)); + for invalid in ["15f0", "15f24s0", "15fNaN", "15finf", "NaN", "1e999", "15f24junk"] { + assert!(xmp_count(invalid, 48000.0).is_none(), "{invalid}"); + } + } +} diff --git a/crates/audio/src/wav_range.rs b/crates/audio/src/wav_range.rs new file mode 100644 index 000000000..33762caf2 --- /dev/null +++ b/crates/audio/src/wav_range.rs @@ -0,0 +1,223 @@ +//! Range-backed PCM WAVE reader and canonical 16-bit writer. +//! +//! Reads chunk headers and only the requested sample range; it never loads a whole file. + +use crate::{AudioError, Result}; +use craft_media::ByteSource; + +/// Whether a prefix identifies a RIFF or RF64 WAVE file. +pub fn sniff(b: &[u8]) -> bool { + b.len() >= 12 && (&b[0..4] == b"RIFF" || &b[0..4] == b"RF64") && &b[8..12] == b"WAVE" +} + +const MAX_CHUNKS: usize = 1 << 16; +const IXML_MAX: u64 = 1 << 20; +/// Maximum sample data returned by a single range read. +pub const MAX_RANGE_BYTES: u64 = 4 << 20; + +fn le16(b: &[u8], o: usize) -> u16 { + b.get(o..o.saturating_add(2)).and_then(|s| s.try_into().ok()).map_or(0, u16::from_le_bytes) +} +fn le32(b: &[u8], o: usize) -> u32 { + b.get(o..o.saturating_add(4)).and_then(|s| s.try_into().ok()).map_or(0, u32::from_le_bytes) +} +fn read_range(source: &impl ByteSource, off: u64, len: usize) -> Result> { + let mut bytes = vec![0; len]; + source.read_at(off, &mut bytes)?; + Ok(bytes) +} + +/// A PCM WAVE file held by an arbitrary random-access source. +pub struct WavRange { + source: S, + /// Number of complete sample frames. + pub frames: u64, + /// Channel count. + pub channels: u16, + /// Sample rate in Hz. + pub rate: u32, + /// Container bits per sample. + pub bits: u16, + /// Whether samples are floating point. + pub float: bool, + /// BWF time reference in samples, from bext or iXML. + pub time_reference: Option, + data_off: u64, +} + +impl WavRange { + /// Open with caller-selected bounds on channel count and sample rate. + pub fn open(source: S, max_channels: u32, max_rate: u32) -> Result { + let len = source.len(); + let mut pos: u64 = 12; + let mut fmt = None; + let mut data = None; + let mut bext_tr = None; + let mut ixml_tr = None; + let mut ds64_data = None; + for _ in 0..MAX_CHUNKS { + let Some(body) = pos.checked_add(8).filter(|&b| b <= len) else { break }; + let mut hdr = [0u8; 8]; + source.read_at(pos, &mut hdr)?; + let id = &hdr[0..4]; + let mut clen = u64::from(le32(&hdr, 4)); + let rest = len - body; + if id == b"data" { + if clen == 0xFFFF_FFFF { + clen = ds64_data.unwrap_or(rest); + } + clen = clen.min(rest); + } + if clen > rest { + break; + } + match id { + b"fmt " if clen >= 16 => { + let b = read_range(&source, body, clen.min(40) as usize)?; + let mut tag = le16(&b, 0); + if tag == 0xFFFE && clen >= 40 { + tag = le16(&b, 24); + } + fmt = Some((tag, le16(&b, 2), le32(&b, 4), le16(&b, 14))); + } + b"ds64" if clen >= 16 => { + let b = read_range(&source, body + 8, 8)?; + ds64_data = Some(u64::from(le32(&b, 0)) | u64::from(le32(&b, 4)) << 32); + } + b"data" => data = Some((body, clen)), + b"bext" if clen >= 346 => { + let b = read_range(&source, body + 338, 8)?; + bext_tr = Some(u64::from(le32(&b, 0)) | u64::from(le32(&b, 4)) << 32); + } + b"iXML" => { + let b = read_range(&source, body, clen.min(IXML_MAX) as usize)?; + ixml_tr = ixml_time_reference(&b); + } + _ => {} + } + pos = body.saturating_add(clen).saturating_add(clen & 1); + } + let (tag, channels, rate, bits) = fmt.ok_or_else(|| AudioError::Malformed("missing fmt chunk".into()))?; + let (data_off, dlen) = data.ok_or_else(|| AudioError::Malformed("missing data chunk".into()))?; + let float = tag == 3; + if !(tag == 1 || float) + || channels == 0 + || rate == 0 + || u32::from(channels) > max_channels + || rate > max_rate + || !matches!(bits, 8 | 16 | 24 | 32 | 64) + { + return Err(AudioError::Unsupported(format!("WAV format tag {tag}, {bits} bits"))); + } + let frames = dlen / (u64::from(channels) * u64::from(bits / 8)); + Ok(Self { source, frames, channels, rate, bits, float, time_reference: bext_tr.or(ixml_tr), data_off }) + } + /// Bytes in one whole frame. + pub fn frame_bytes(&self) -> usize { + usize::from(self.channels) * usize::from(self.bits / 8) + } + /// Read the inclusive range of frames, capped to prevent unbounded allocation. + pub fn read_frames(&self, first: u64, last: u64) -> Result> { + if first > last || last >= self.frames { + return Err(AudioError::Malformed("WAV frame range outside data".into())); + } + let n = (last - first + 1).saturating_mul(self.frame_bytes() as u64); + if n > MAX_RANGE_BYTES { + return Err(AudioError::TooLarge("WAV frame range".into())); + } + let off = self.data_off.saturating_add(first.saturating_mul(self.frame_bytes() as u64)); + read_range(&self.source, off, n as usize) + } + /// Decode a channel from a buffer returned by `read_frames`. + pub fn sample(&self, block: &[u8], frame: usize, ch: usize) -> f32 { + if ch >= usize::from(self.channels) { + return 0.0; + } + let bps = usize::from(self.bits / 8); + let Some(o) = frame.checked_mul(usize::from(self.channels)).and_then(|v| v.checked_add(ch)).and_then(|v| v.checked_mul(bps)) else { + return 0.0; + }; + let Some(b) = block.get(o..o.saturating_add(bps)) else { return 0.0 }; + match (self.bits, self.float, b) { + (8, _, &[a]) => (a as f32 - 128.0) / 128.0, + (16, _, &[a, b]) => i16::from_le_bytes([a, b]) as f32 / 32768.0, + (24, _, &[a, b, c]) => (i32::from_le_bytes([0, a, b, c]) >> 8) as f32 / 8_388_608.0, + (32, false, &[a, b, c, d]) => i32::from_le_bytes([a, b, c, d]) as f32 / 2_147_483_648.0, + (32, true, &[a, b, c, d]) => f32::from_le_bytes([a, b, c, d]), + (64, true, b) => f64::from_le_bytes(b.try_into().unwrap_or([0; 8])) as f32, + _ => 0.0, + } + } +} + +fn ixml_time_reference(x: &[u8]) -> Option { + let text = String::from_utf8_lossy(x); + let field = |tag: &str| -> Option { + let open = format!("<{tag}>"); + let a = text.find(&open)? + open.len(); + let b = a + text[a..].find('<')?; + text[a..b].trim().parse().ok() + }; + let low = field("BWF_TIME_REFERENCE_LOW")?; + Some(low | field("BWF_TIME_REFERENCE_HIGH").unwrap_or(0) << 32) +} + +/// Write interleaved samples as 16-bit PCM WAVE, using symmetric 32767 scaling. +#[cfg(feature = "pcm-encode")] +pub fn write_wav16(samples: &[f32], channels: u16, rate: u32) -> Vec { + let data_len = samples.len().saturating_mul(2); + let mut v = crate::pcm_wav_header(u32::try_from(data_len).unwrap_or(u32::MAX), channels, rate, 16); + v.reserve(data_len); + for s in samples { + v.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes()); + } + v +} + +#[cfg(all(test, feature = "pcm-encode"))] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + struct Source { + bytes: Vec, + reads: Arc>>, + } + impl ByteSource for Source { + fn len(&self) -> u64 { + self.bytes.len() as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + self.reads.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((offset, buf.len())); + self.bytes.read_at(offset, buf) + } + } + #[test] + fn bounded_reads_and_pcm_values() { + let bytes = write_wav16(&[-1.0, -0.5, 0.0, 0.5, 1.0], 1, 48_000); + let reads = Arc::new(Mutex::new(Vec::new())); + let wav = WavRange::open(Source { bytes, reads: reads.clone() }, 64, 384_000).unwrap(); + assert_eq!((wav.frames, wav.channels, wav.rate, wav.bits), (5, 1, 48_000, 16)); + assert!(reads.lock().unwrap().iter().all(|(_, n)| *n <= 40)); + let data = wav.read_frames(1, 3).unwrap(); + assert_eq!(wav.sample(&data, 0, 0), -0.5); + assert_eq!(wav.sample(&data, 2, 0), 0.5); + assert!(wav.read_frames(0, 5).is_err()); + assert!(wav.read_frames(3, 1).is_err()); + assert_eq!(reads.lock().unwrap().last(), Some(&(46, 6))); + } + #[test] + fn ixml_fallback_accepts_flat_fields() { + let base = write_wav16(&[0.0], 1, 48_000); + let mut bytes = base[..36].to_vec(); + let xml = b"51"; + bytes.extend_from_slice(b"iXML"); + bytes.extend_from_slice(&(xml.len() as u32).to_le_bytes()); + bytes.extend_from_slice(xml); + if xml.len() & 1 != 0 { + bytes.push(0); + } + bytes.extend_from_slice(&base[36..]); + assert_eq!(WavRange::open(bytes.as_slice(), 64, 384_000).unwrap().time_reference, Some((1 << 32) + 5)); + } +} diff --git a/crates/audio/src/wav_stream.rs b/crates/audio/src/wav_stream.rs new file mode 100644 index 000000000..9da2bdcc9 --- /dev/null +++ b/crates/audio/src/wav_stream.rs @@ -0,0 +1,119 @@ +//! Canonical RIFF/WAVE header and interleaved sample blocks for non-seekable sinks. +//! +//! Extracted from AniCraft's WAV writer, preserving its byte-level compatibility. +//! Unlike `FileEncoder`, these primitives do not require `Seek` and leave final lengths, +//! chunk padding and sink error handling to the caller. The caller must supply a complete +//! frame count and append exactly that many frames. For odd-length data, append a pad byte +//! (the header includes that padding in the RIFF size); current AniCraft output is always stereo (even). +//! Non-finite samples become silence, including float output. This deliberately differs +//! from the general encoder's infinity handling. Prefer `FileEncoder` for new seekable sinks. + +/// Sample formats written. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Bits { + /// Signed 16-bit PCM. + Int16, + /// Signed 24-bit PCM. + Int24, + /// IEEE 754 32-bit float. + Float32, +} + +impl Bits { + fn bytes(self) -> u16 { + match self { + Bits::Int16 => 2, + Bits::Int24 => 3, + Bits::Float32 => 4, + } + } +} + +const PCM: u16 = 1; +const FLOAT: u16 = 3; + +/// A WAV header for `frames` frames of `channels` channels. +/// Returns `None` for zero rate/channels or any size/byte-rate field overflow. +pub fn header(rate: u32, channels: u16, bits: Bits, frames: u64) -> Option> { + if rate == 0 || channels == 0 { + return None; + } + let b = bits.bytes(); + let data = u32::try_from(frames.checked_mul(u64::from(b) * u64::from(channels))?).ok()?; + let riff = data.checked_add(36)?.checked_add(data & 1)?; + let block = channels.checked_mul(b)?; + let byte_rate = rate.checked_mul(u32::from(block))?; + let tag = if bits == Bits::Float32 { FLOAT } else { PCM }; + let mut h = Vec::with_capacity(44); + h.extend_from_slice(b"RIFF"); + h.extend_from_slice(&riff.to_le_bytes()); + h.extend_from_slice(b"WAVEfmt "); + h.extend_from_slice(&16u32.to_le_bytes()); + h.extend_from_slice(&tag.to_le_bytes()); + h.extend_from_slice(&channels.to_le_bytes()); + h.extend_from_slice(&rate.to_le_bytes()); + h.extend_from_slice(&byte_rate.to_le_bytes()); + h.extend_from_slice(&block.to_le_bytes()); + h.extend_from_slice(&(b * 8).to_le_bytes()); + h.extend_from_slice(b"data"); + h.extend_from_slice(&data.to_le_bytes()); + Some(h) +} + +/// Appends samples in `bits` format. Integers are rounded and clipped to range; `x · 32768` +/// for 16-bit, so 16-bit sources read by [`crate::decode`] come back bit-identical. +pub fn append(out: &mut Vec, samples: &[f32], bits: Bits) { + out.reserve(samples.len() * usize::from(bits.bytes())); + for &s in samples { + let s = if s.is_finite() { s } else { 0.0 }; + match bits { + Bits::Int16 => out.extend_from_slice(&((s * 32_768.0).round().clamp(-32_768.0, 32_767.0) as i16).to_le_bytes()), + Bits::Int24 => { + let v = (f64::from(s) * 8_388_608.0).round().clamp(-8_388_608.0, 8_388_607.0) as i32; + out.extend_from_slice(v.to_le_bytes().get(..3).unwrap_or(&[0, 0, 0])); + } + Bits::Float32 => out.extend_from_slice(&s.to_le_bytes()), + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + + #[test] + fn canonical_header_and_odd_padding() { + let h = header(48_000, 2, Bits::Int16, 1).unwrap(); + assert_eq!(h.len(), 44); + assert_eq!(&h[..12], b"RIFF\x28\0\0\0WAVE"); + assert_eq!(&h[28..36], &[0, 238, 2, 0, 4, 0, 16, 0]); + let h = header(8_000, 1, Bits::Int24, 1).unwrap(); + assert_eq!(&h[4..8], &40u32.to_le_bytes()); + assert_eq!(&h[40..44], &3u32.to_le_bytes()); + assert!(header(0, 2, Bits::Int16, 1).is_none()); + assert!(header(48_000, 0, Bits::Int16, 1).is_none()); + assert!(header(u32::MAX, 2, Bits::Int16, 1).is_none()); + assert!(header(48_000, 2, Bits::Float32, u64::MAX).is_none()); + assert!(header(48_000, u16::MAX, Bits::Float32, 0).is_none()); + } + + #[test] + fn samples_preserve_rounding_clipping_silence_and_chunk_boundaries() { + let samples = [-2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY]; + let mut pcm = Vec::new(); + append(&mut pcm, &samples, Bits::Int16); + let expected = [-32768i16, -32768, -16384, 0, 16384, 32767, 32767, 0, 0, 0]; + assert_eq!(pcm, expected.iter().flat_map(|s| s.to_le_bytes()).collect::>()); + for bits in [Bits::Int16, Bits::Int24, Bits::Float32] { + let mut whole = Vec::new(); + append(&mut whole, &samples, bits); + let mut blocks = Vec::new(); + for block in samples.chunks(3) { + append(&mut blocks, block, bits); + } + assert_eq!(whole, blocks); + assert_eq!(&whole[whole.len() - 3 * usize::from(bits.bytes())..], vec![0; 3 * usize::from(bits.bytes())]); + } + } +} diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 0de55c394..a2043d279 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -9,6 +9,10 @@ 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, OggVorbisOptions, encode as encode_ogg, encode_ogg_vorbis, quality_for_bitrate}; #[cfg(feature = "pcm-encode")] mod raw; #[cfg(feature = "pcm-encode")] @@ -17,6 +21,15 @@ 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 the file `opts.format` names. Integer depths clamp samples to [-1, 1]; float @@ -51,6 +64,25 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { 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 => { + let count = u16::try_from(buf.channels.len()).unwrap_or(u16::MAX); + let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(count)); + if layout.channels() != count { + return Err(AudioError::Unsupported(format!("a {}-channel layout for {count} channels", layout.channels()))); + } + let map = vorbis::vorbis_map(&layout)?; + let quality = match opts.rate_control { + None => vorbis::quality_for_bitrate(192, buf.channels.len()), + Some(crate::RateControl::Bitrate(bps)) => { + vorbis::quality_for_bitrate((bps / 1000).clamp(OGG_BITRATES.0, OGG_BITRATES.1), buf.channels.len()) + } + Some(crate::RateControl::Quality(q)) if q.is_nan() => return Err(AudioError::Encode("the Vorbis quality is NaN".into())), + Some(crate::RateControl::Quality(q)) => -1.0 + 11.0 * q.clamp(0.0, 1.0), + }; + let planar: Vec<&[f32]> = map.iter().filter_map(|&i| buf.channels.get(i).map(Vec::as_slice)).collect(); + vorbis::encode_planar(buf.sample_rate, &planar, &OggVorbisOptions::new(quality)) + } #[allow(unreachable_patterns)] f => Err(AudioError::Unsupported(format!("writing {f:?}"))), } @@ -62,8 +94,8 @@ fn check_built(format: EncodeFormat) -> Result<()> { } /// Every extension [`ENCODE_EXTENSIONS`] can list, and how many of them the features built give. -const fn extensions() -> ([&'static str; 12], usize) { - let mut all = [""; 12]; +const fn extensions() -> ([&'static str; 13], usize) { + let mut all = [""; 13]; let mut n = 0; macro_rules! add { ($built:expr, $($extension:literal),+) => { @@ -81,10 +113,11 @@ const fn extensions() -> ([&'static str; 12], usize) { add!(cfg!(feature = "mp3-encode"), "mp3"); add!(cfg!(feature = "ac3-encode"), "ac3"); add!(cfg!(feature = "eac3-encode"), "eac3", "ec3"); + add!(cfg!(feature = "vorbis-encode"), "ogg"); (all, n) } -const EXTENSIONS: ([&str; 12], usize) = extensions(); +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; @@ -99,7 +132,7 @@ pub const ENCODE_EXTENSIONS: &[&str] = EXTENSIONS.0.split_at(EXTENSIONS.1).0; /// use craft_audio::{EncodeFormat, encode_format_for}; /// /// assert_eq!(encode_format_for(".AIFF"), Some(EncodeFormat::Aiff)); -/// assert_eq!(encode_format_for("ogg"), None); +/// assert_eq!(encode_format_for("unknown"), None); /// # } /// ``` pub fn encode_format_for(name: &str) -> Option { @@ -122,6 +155,8 @@ pub fn encode_format_for(name: &str) -> Option { "ac3" => Some(EncodeFormat::Ac3), #[cfg(feature = "eac3-encode")] "eac3" | "ec3" => Some(EncodeFormat::Eac3), + #[cfg(feature = "vorbis-encode")] + "ogg" => Some(EncodeFormat::Ogg), _ => None, } } @@ -138,6 +173,15 @@ 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()) } @@ -163,12 +207,30 @@ 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 { f.debug_struct("FileEncoder").field("format", &self.format).finish_non_exhaustive() @@ -177,6 +239,15 @@ impl std::fmt::Debug for FileEncoder { // 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), @@ -188,6 +259,15 @@ enum Writer { 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. @@ -317,9 +397,39 @@ impl EncodeOptions { /// 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. - Ok(FileEncoder::new(std::io::Cursor::new(Vec::new()), self, sample_rate, channels)?.bitrate()) + #[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())) + } } } diff --git a/crates/audio/src/write/vorbis.rs b/crates/audio/src/write/vorbis.rs new file mode 100644 index 000000000..6c19ada77 --- /dev/null +++ b/crates/audio/src/write/vorbis.rs @@ -0,0 +1,267 @@ +//! Ogg Vorbis files (Vorbis I §A, RFC 5334) from the pure-Rust [`crate::vorbis::encoder`] and +//! craft-media's Ogg page writer: 1 to 8 channels in Vorbis channel order, a quality from -1 to +//! 10 (variable bit rate), and the tags in the comment header. Builds for every target. + +use craft_media::ogg::{PageWriter, vorbis_comment}; + +use crate::vorbis::encoder::{DEFAULT_QUALITY, Encoder, EncoderConfig, Error as VorbisError}; +use crate::{AudioBuffer, AudioError, ChannelLayout, Result}; + +/// The bit rates [`encode_ogg`](crate::encode_ogg) takes, in kbit/s. Vorbis is variable: the bit rate picks a +/// quality ([`quality_for_bitrate`]), and the file comes out near it for typical music. +pub const OGG_BITRATES: (u32, u32) = (64, 500); + +/// The serial number of the stream when the options do not set one (`LCRF`): one stream per file, +/// so a constant keeps files byte-for-byte reproducible. +const SERIAL: u32 = 0x4C43_5246; + +/// Samples per channel fed to the encoder at a time. +const CHUNK: usize = 4096; + +/// What [`encode_ogg_vorbis`] writes besides the audio. +/// +/// `#[non_exhaustive]`: build it with `OggVorbisOptions::default()` or +/// [`OggVorbisOptions::new`] and the `with_*` methods. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct OggVorbisOptions { + /// -1 (smallest) to 10 (best); clamped, and NaN or infinite reads as + /// [`DEFAULT_QUALITY`] (6). + pub quality: f32, + /// The comment header's vendor string. + pub vendor: String, + /// `NAME=value` comments (Vorbis I §5), in order. A name that is empty, or holds `=` or a byte + /// outside 0x20–0x7D, is left out. + pub tags: Vec<(String, String)>, + /// The logical stream's serial number. + pub serial: u32, +} + +impl Default for OggVorbisOptions { + fn default() -> Self { + OggVorbisOptions { quality: DEFAULT_QUALITY, vendor: "craft-audio".into(), tags: Vec::new(), serial: SERIAL } + } +} + +impl OggVorbisOptions { + /// The defaults at `quality`. + pub fn new(quality: f32) -> Self { + OggVorbisOptions { quality, ..Self::default() } + } + + /// Sets [`quality`](Self::quality). + pub fn with_quality(mut self, quality: f32) -> Self { + self.quality = quality; + self + } + + /// Sets [`vendor`](Self::vendor). + pub fn with_vendor(mut self, vendor: impl Into) -> Self { + self.vendor = vendor.into(); + self + } + + /// Adds a comment ([`tags`](Self::tags)). + pub fn with_tag(mut self, name: impl Into, value: impl Into) -> Self { + self.tags.push((name.into(), value.into())); + self + } + + /// Sets [`serial`](Self::serial). + pub fn with_serial(mut self, serial: u32) -> Self { + self.serial = serial; + self + } +} + +fn encode_error(e: VorbisError) -> AudioError { + AudioError::Encode(format!("Vorbis: {e}")) +} + +/// Encode `buf` as an Ogg Vorbis file with `opts`. The channels are in Vorbis channel order +/// (Vorbis I §4.3.9: L C R for three, L C R Ls Rs LFE for 5.1, L C R Ls Rs Rl Rr LFE for 7.1). +/// The last granule position is the buffer's length, so a decoder returns exactly its frames. +/// +/// ``` +/// use craft_audio::{AudioBuffer, OggVorbisOptions, encode_ogg_vorbis}; +/// +/// let buf = AudioBuffer::new(48_000, 6, 4_800); // 0.1 s of 5.1 silence +/// let opts = OggVorbisOptions::new(4.0).with_tag("TITLE", "Silence"); +/// let ogg = encode_ogg_vorbis(&buf, &opts).unwrap(); +/// assert!(ogg.starts_with(b"OggS")); +/// ``` +pub fn encode_ogg_vorbis(buf: &AudioBuffer, opts: &OggVorbisOptions) -> Result> { + let planar: Vec<&[f32]> = buf.channels.iter().map(Vec::as_slice).collect(); + encode_planar(buf.sample_rate, &planar, opts) +} + +/// [`encode_ogg_vorbis`] over channels already in Vorbis order. +pub(crate) fn encode_planar(sample_rate: u32, planar: &[&[f32]], opts: &OggVorbisOptions) -> Result> { + if !(1..=8).contains(&planar.len()) { + return Err(AudioError::Unsupported(format!("Ogg Vorbis holds 1 to 8 channels, not {}", planar.len()))); + } + let frames = planar.first().map_or(0, |c| c.len()); + if planar.iter().any(|c| c.len() != frames || c.iter().any(|s| !s.is_finite())) { + return Err(AudioError::Encode("Vorbis samples must be finite and channels equally long".into())); + } + if sample_rate == 0 { + return Err(AudioError::Encode("there is no audio to encode".into())); + } + let mut enc = Encoder::new(EncoderConfig::new(sample_rate, planar.len(), opts.quality)).map_err(encode_error)?; + let mut pages = PageWriter::new(opts.serial); + let tags: Vec<(&str, &str)> = opts.tags.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); + let mut out = pages.header(&enc.identification()); + out.extend(pages.header(&vorbis_comment(&opts.vendor, &tags))); + out.extend(pages.header(&enc.setup())); + // The first audio packet (which outputs nothing) gets a page of its own: a stream whose first + // audio page is also its last would leave decoders to choose between start and end trimming + // (Vorbis I §A.2), and ffmpeg then plays the padding. + let mut first = true; + let mut add = |packets: Vec<(Vec, i64)>, out: &mut Vec| { + for (packet, granule) in packets { + out.extend(pages.packet(&packet, granule)); + if std::mem::take(&mut first) { + out.extend(pages.flush()); + } + } + }; + let mut at = 0; + loop { + let end = (at + CHUNK).min(frames); + let chunk: Vec<&[f32]> = planar.iter().map(|c| c.get(at..end).unwrap_or_default()).collect(); + add(enc.encode(&chunk).map_err(encode_error)?, &mut out); + at = end; + if at >= frames { + break; + } + } + add(enc.finish().map_err(encode_error)?, &mut out); + out.extend(pages.finish(None)); + Ok(out) +} + +/// Nominal kbit/s per channel at each whole quality from -1 to 10: this encoder's rate on +/// music-like test signals at 48 kHz (harmonic chords with noise), averaged. +const KBPS_PER_CHANNEL: [f32; 12] = [18.0, 23.0, 31.0, 43.0, 58.0, 75.0, 89.0, 100.0, 111.0, 121.0, 130.0, 140.0]; + +/// The quality whose nominal bit rate is `kbps` kbit/s for `channels` channels (clamped to -1..=10). +/// Vorbis is variable: the bit rate of a file depends on the audio. +pub fn quality_for_bitrate(kbps: u32, channels: usize) -> f32 { + let per = kbps as f32 / channels.max(1) as f32; + let mut q = -1.0; + for pair in KBPS_PER_CHANNEL.windows(2) { + if let [lo, hi] = *pair + && per <= hi + { + return q + ((per - lo) / (hi - lo)).clamp(0.0, 1.0); + } + q += 1.0; + } + 10.0 +} + +/// Encode `buf` as an Ogg Vorbis stream near `kbps` kbit/s ([`OGG_BITRATES`], clamped): the +/// quality [`quality_for_bitrate`] gives, no tags. 1 to 8 channels in Vorbis channel order. +/// `Err` says why there is nothing. +pub fn encode(buf: &AudioBuffer, kbps: u32) -> Result> { + let kbps = kbps.clamp(OGG_BITRATES.0, OGG_BITRATES.1); + encode_ogg_vorbis(buf, &OggVorbisOptions::new(quality_for_bitrate(kbps, buf.channels.len()))) +} + +/// WAV-order speakers ([`crate::EncodeFormat::layout_masks`]) to Vorbis order, per channel count. +const VORBIS_ORDER: [&[usize]; 8] = + [&[0], &[0, 1], &[0, 2, 1], &[0, 1, 2, 3], &[0, 2, 1, 3, 4], &[0, 2, 1, 4, 5, 3], &[0, 2, 1, 5, 6, 4, 3], &[0, 2, 1, 6, 7, 4, 5, 3]]; + +/// For each Vorbis channel, the channel of audio in `layout` it comes from. +pub(crate) fn vorbis_map(layout: &ChannelLayout) -> Result> { + let n = layout.channels(); + let mask = crate::EncodeFormat::Ogg.layout_masks(n).first().copied(); + let order = usize::from(n).checked_sub(1).and_then(|i| VORBIS_ORDER.get(i)).copied(); + match (mask, order) { + (Some(mask), Some(order)) => crate::layout::channel_map(mask, Some(order), layout) + .ok_or_else(|| AudioError::Unsupported(format!("Vorbis has no layout of {n} channels with these speakers"))), + _ => Err(AudioError::Unsupported(format!("Ogg Vorbis holds 1 to 8 channels, not {n}"))), + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::{OGG_BITRATES, OggVorbisOptions, encode, encode_ogg_vorbis, quality_for_bitrate, vorbis_map}; + use crate::{AudioBuffer, AudioError, ChannelLayout}; + + #[test] + fn rejects_unsupported_or_malformed_channels_without_dropping_audio() { + for channels in [0, 9] { + 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()); + let infinite = AudioBuffer { sample_rate: 48_000, channels: vec![vec![f32::INFINITY]] }; + assert!(encode(&infinite, 192).is_err()); + } + + #[test] + fn generic_and_direct_encoders_write_one_to_eight_channels() { + for channels in 1..=8 { + 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(); + assert!(direct.starts_with(b"OggS")); + // silence: the channel order changes nothing, so the generic path writes the same file + let generic = crate::encode(&audio, &opts.with_bitrate(192_000)).unwrap(); + assert_eq!(direct, generic, "{channels} channels"); + #[cfg(feature = "decode")] + { + let (info, decoded) = crate::decode(&generic, Some("ogg")).unwrap(); + assert_eq!(info.channels, channels); + assert_eq!(decoded.frames(), audio.frames()); + } + } + } + + #[test] + fn the_quality_follows_the_bit_rate() { + assert_eq!(quality_for_bitrate(0, 2), -1.0); + assert_eq!(quality_for_bitrate(10_000, 2), 10.0); + assert!((quality_for_bitrate(200, 2) - 6.0).abs() < 1e-6); + assert!((quality_for_bitrate(600, 6) - 6.0).abs() < 1e-6); + let mut last = -2.0; + for kbps in OGG_BITRATES.0..=OGG_BITRATES.1 { + let q = quality_for_bitrate(kbps, 2); + assert!(q >= last && (-1.0..=10.0).contains(&q)); + last = q; + } + assert!(quality_for_bitrate(192, 0).is_finite()); + } + + #[test] + fn layouts_map_to_vorbis_order() { + // 5.1 in WAV order (L R C LFE Ls Rs) is written L C R Ls Rs LFE + assert_eq!(vorbis_map(&ChannelLayout::SURROUND_5_1).unwrap(), [0, 2, 1, 4, 5, 3]); + assert_eq!(vorbis_map(&ChannelLayout::SURROUND_5_1_SIDE).unwrap(), [0, 2, 1, 4, 5, 3]); + assert_eq!(vorbis_map(&ChannelLayout::from_mask(0x63F)).unwrap(), [0, 2, 1, 6, 7, 4, 5, 3]); + assert_eq!(vorbis_map(&ChannelLayout::from_mask(0x7)).unwrap(), [0, 2, 1]); + assert_eq!(vorbis_map(&ChannelLayout::STEREO).unwrap(), [0, 1]); + assert!(vorbis_map(&ChannelLayout::from_mask(0xC)).is_err()); + assert!(vorbis_map(&ChannelLayout::unordered(9)).is_err()); + assert!(vorbis_map(&ChannelLayout::unordered(0)).is_err()); + } + + #[test] + fn options_build_and_tags_reach_the_comment_header() { + let opts = OggVorbisOptions::default().with_quality(2.0).with_vendor("v").with_tag("TITLE", "t").with_tag("bad=name", "x").with_serial(9); + assert_eq!((opts.quality, opts.vendor.as_str(), opts.serial, opts.tags.len()), (2.0, "v", 9, 2)); + let ogg = encode_ogg_vorbis(&AudioBuffer::new(44_100, 1, 100), &opts).unwrap(); + let file = craft_media::ogg::open(&ogg).unwrap(); + let s = &file.streams[0]; + assert_eq!((s.serial, s.saw_eos, s.headers.len()), (9, true, 3)); + assert_eq!(s.headers[1], craft_media::ogg::vorbis_comment("v", &[("TITLE", "t")])); + assert_eq!(s.last_granule, Some(100)); + } +} diff --git a/crates/audio/tests/adpcm_oracle.rs b/crates/audio/tests/adpcm_oracle.rs new file mode 100644 index 000000000..c89fe6444 --- /dev/null +++ b/crates/audio/tests/adpcm_oracle.rs @@ -0,0 +1,516 @@ +//! ADPCM (feature `adpcm`): every family decodes what ffmpeg's encoder writes to ffmpeg's own +//! samples, and ffmpeg decodes what our encoder writes to our own decoder's samples (oracle; +//! skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`); plus the +//! round trip through our own encoder and decoder, and damaged input. + +use craft_audio::adpcm::{ima, ms, swf, yamaha}; +use std::path::Path; +use std::process::Command; + +const RATE: u32 = 22_050; + +/// Interleaved test audio: tones, a sweep, noise bursts, silence and a full-scale square. +fn signal(channels: usize, frames: usize) -> Vec { + let mut seed = 0x2545_F491u32; + let mut out = Vec::with_capacity(frames * channels); + for i in 0..frames { + for c in 0..channels { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let t = i as f64; + let v = match (i / 1500) % 5 { + 0 => (t * (0.03 + 0.011 * c as f64)).sin() * 9000.0, + 1 => (t * 0.002 * (1.0 + t / 3000.0)).sin() * 14000.0, + 2 => f64::from(seed % 12000) - 6000.0, + 3 => 0.0, + _ => { + if (i / 40) % 2 == 0 { + 20000.0 + } else { + -20000.0 + } + } + }; + out.push(v as i16); + } + } + out +} + +fn snr(a: &[i16], b: &[i16]) -> f64 { + let (mut s, mut n) = (0f64, 0f64); + for (x, y) in a.iter().zip(b) { + s += f64::from(*x).powi(2); + n += (f64::from(*x) - f64::from(*y)).powi(2); + } + 10.0 * (s / n.max(1.0)).log10() +} + +fn max_diff(a: &[i16], b: &[i16]) -> i32 { + a.iter().zip(b).map(|(x, y)| (i32::from(*x) - i32::from(*y)).abs()).max().unwrap_or(0) +} + +#[test] +fn encode_then_decode_is_close_to_the_input() { + for channels in [1usize, 2] { + let x = signal(channels, 20_000); + // (name, decoded, minimum SNR dB, a few dB under what each reaches): the signal has noise bursts + // and full-scale square waves, which codes this small follow loosely + let cases: Vec<(&str, Vec, f64)> = vec![ + ("ima", ima::decode(&ima::encode(&x, channels, 512).unwrap(), channels, 512).unwrap(), 5.0), + ("ms", ms::decode(&ms::encode(&x, channels, 512).unwrap(), channels, 512).unwrap(), 18.0), + ("yamaha", yamaha::decode(&yamaha::encode(&x, channels).unwrap(), channels).unwrap(), 5.0), + ("swf2", swf::decode(&swf::encode(&x, channels, 2).unwrap(), channels).unwrap(), 1.0), + ("swf3", swf::decode(&swf::encode(&x, channels, 3).unwrap(), channels).unwrap(), 3.0), + ("swf4", swf::decode(&swf::encode(&x, channels, 4).unwrap(), channels).unwrap(), 5.0), + ("swf5", swf::decode(&swf::encode(&x, channels, 5).unwrap(), channels).unwrap(), 7.0), + ]; + for (name, y, min) in cases { + assert!(y.len() >= x.len(), "{name}: {} samples for {}", y.len(), x.len()); + let s = snr(&x, &y[..x.len()]); + println!("{name} {channels}ch: SNR {s:.1} dB"); + assert!(s >= min, "{name} {channels}ch: SNR {s:.1} dB under {min}"); + } + } +} + +#[test] +fn damaged_input_is_an_error_or_decodes_never_panics() { + let x = signal(2, 4000); + let streams: Vec<(&str, Vec)> = vec![ + ("ima", ima::encode(&x, 2, 256).unwrap()), + ("ms", ms::encode(&x, 2, 256).unwrap()), + ("yamaha", yamaha::encode(&x, 2).unwrap()), + ("swf", swf::encode(&x, 2, 4).unwrap()), + ]; + let mut seed = 99u32; + for (name, s) in &streams { + for cut in (0..s.len()).step_by(7) { + let part = &s[..cut]; + let _ = match *name { + "ima" => ima::decode(part, 2, 256).map(drop), + "ms" => ms::decode(part, 2, 256).map(drop), + "yamaha" => yamaha::decode(part, 2).map(drop), + _ => swf::decode(part, 2).map(drop), + }; + } + for _ in 0..300 { + let mut d = s.clone(); + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let at = seed as usize % d.len(); + d[at] ^= (seed >> 8) as u8 | 1; + let _ = match *name { + "ima" => ima::decode(&d, 2, 256).map(drop), + "ms" => ms::decode(&d, 2, 256).map(drop), + "yamaha" => yamaha::decode(&d, 2).map(drop), + _ => swf::decode(&d, 2).map(drop), + }; + } + } + // the impossible layouts + assert!(ima::decode(&[0; 10], 2, 10).is_err()); + assert!(ima::decode(&[0; 8], 9, 8).is_err()); + assert!(ms::decode(&[0; 8], 3, 8).is_err()); + assert!(ima::encode(&[0; 3], 2, 256).is_err()); + assert!(ima::encode_block(&[0; 3], 1, 256).is_err()); + assert!(ms::encode_block(&[0; 3], 1, 256).is_err()); + // a block whose step index or predictor is out of range + let mut bad = ima::encode_block(&vec![0; 505], 1, 256).unwrap(); + bad[2] = 200; + assert!(ima::decode_block(&bad, 1, &mut Vec::new()).is_err()); + let mut bad = swf::encode(&[0; 10], 1, 4).unwrap(); + bad[2] = 0xFF; + let _ = swf::decode(&bad, 1); +} + +#[test] +fn huge_layouts_and_big_jumps_are_handled() { + // block sizes whose sample counts do not fit in a usize + assert_eq!(ima::samples_per_block(usize::MAX - 3, 1), None); + assert_eq!(ms::samples_per_block(usize::MAX, 1), None); + assert!(ima::encode(&[], 1, usize::MAX - 3).is_err()); + assert!(ms::encode(&[], 1, usize::MAX).is_err()); + // a Flash stream's header holds the step index in six bits: a jump from silence to full scale + // still decodes to what the encoder's own state says + for bits in [2u32, 3, 4, 5] { + let x = [0i16, 32767, -32768, 0, 0]; + let y = swf::decode(&swf::encode(&x, 1, bits).unwrap(), 1).unwrap(); + // the stream has no length: up to seven padding bits can read as one more code + assert!((x.len()..=x.len() + 3).contains(&y.len()), "{bits} bits: {} samples", y.len()); + assert!(y[1] > 0 && y[2] < y[1], "{bits} bits: {y:?}"); + } + // padding bits at the end of a stream are not a code: no incomplete stereo frame + for bits in [2u32, 3, 4, 5] { + let y = swf::decode(&swf::encode(&[0, 0, 5, -5, 9, 9], 2, bits).unwrap(), 2).unwrap(); + assert_eq!(y.len() % 2, 0, "{bits} bits: {y:?}"); + assert!((6..=8).contains(&y.len()), "{bits} bits: {} samples", y.len()); + } +} + +#[test] +fn partial_final_blocks_are_handled() { + let x = signal(1, 1000); + // IMA: 256-byte blocks hold 505 samples; 1000 samples is two blocks, the second padded + let enc = ima::encode(&x, 1, 256).unwrap(); + assert_eq!(enc.len(), 2 * 256); + assert_eq!(ima::decode(&enc, 1, 256).unwrap().len(), 1010); + // a stream cut inside the last block decodes as far as it goes + let cut = ima::decode(&enc[..256 + 4 + 40], 1, 256).unwrap(); + assert_eq!(cut.len(), 505 + 1 + 80); + let enc = ms::encode(&x, 1, 256).unwrap(); + assert_eq!(ms::decode(&enc, 1, 256).unwrap().len(), 1000); + assert!(ima::encode(&[], 1, 256).unwrap().is_empty()); + assert!(ms::encode(&[], 1, 256).unwrap().is_empty()); + assert!(yamaha::encode(&[], 1).unwrap().is_empty()); + assert_eq!(yamaha::decode(&yamaha::encode(&[5, 6, 7], 1).unwrap(), 1).unwrap().len(), 4); +} + +// ---- the other rounding some ffmpeg versions use for IMA and Flash ADPCM +// +// The IMA recommended practices build the step difference from `step >> 3` and the shifted steps +// of the magnitude bits that are set; some decoders (including older ffmpeg releases) compute +// `((2 * magnitude + 1) * step) >> (bits - 1)` instead, which rounds differently by a few units +// and so drifts apart through the predictor. A stream decodes to ours or to this one. + +fn alt_diff(mag: i32, step: i32, bits: u32) -> i32 { + ((2 * mag + 1) * step) >> (bits - 1) +} + +const INDEX_4: [i32; 8] = [-1, -1, -1, -1, 2, 4, 6, 8]; +const INDEX_5: [i32; 16] = [-1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16]; +const STEPS: [i32; 89] = [ + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, + 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, + 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, + 22385, 24623, 27086, 29794, 32767, +]; + +fn index_table(bits: u32) -> &'static [i32] { + match bits { + 2 => &[-1, 2], + 3 => &[-1, -1, 2, 4], + 4 => &INDEX_4, + _ => &INDEX_5, + } +} + +/// `ima::decode` with the other rounding. +fn alt_ima_decode(data: &[u8], channels: usize, block_align: usize) -> Vec { + let per = ima::samples_per_block(block_align, channels).expect("layout"); + let mut out = Vec::new(); + for block in data.chunks_exact(block_align) { + let mut pred = vec![0i32; channels]; + let mut idx = vec![0i32; channels]; + let base = out.len(); + out.resize(base + per * channels, 0); + for ch in 0..channels { + pred[ch] = i32::from(i16::from_le_bytes([block[4 * ch], block[4 * ch + 1]])); + idx[ch] = i32::from(block[4 * ch + 2]); + out[base + ch] = pred[ch] as i16; + } + for (g, group) in block[4 * channels..].chunks_exact(4 * channels).enumerate() { + for (ch, bytes) in group.as_chunks::<4>().0.iter().enumerate() { + for (k, b) in bytes.iter().enumerate() { + for (half, nib) in [b & 0xF, b >> 4].into_iter().enumerate() { + let step = STEPS[idx[ch] as usize]; + let d = alt_diff(i32::from(nib & 7), step, 4); + pred[ch] = (pred[ch] + if nib & 8 != 0 { -d } else { d }).clamp(-32768, 32767); + idx[ch] = (idx[ch] + INDEX_4[usize::from(nib & 7)]).clamp(0, 88); + out[base + (1 + g * 8 + k * 2 + half) * channels + ch] = pred[ch] as i16; + } + } + } + } + } + out +} + +/// `swf::decode` with the other rounding (one stream). +fn alt_swf_decode(data: &[u8], channels: usize) -> Vec { + let mut bitpos = 0usize; + let mut get = |n: usize| -> Option { + let mut v = 0u32; + for _ in 0..n { + let byte = *data.get(bitpos / 8)?; + v = (v << 1) | u32::from((byte >> (7 - bitpos % 8)) & 1); + bitpos += 1; + } + Some(v) + }; + let bits = get(2).expect("header") + 2; + let mut out = Vec::new(); + loop { + let mut pred = Vec::new(); + let mut idx = Vec::new(); + for _ in 0..channels { + let (Some(p), Some(i)) = (get(16), get(6)) else { return out }; + out.push(p as u16 as i16); + pred.push(i32::from(p as u16 as i16)); + idx.push(i as i32); + } + for _ in 1..4096 { + for ch in 0..channels { + let Some(code) = get(bits as usize) else { return out }; + let mag = (code & ((1 << (bits - 1)) - 1)) as i32; + let d = alt_diff(mag, STEPS[idx[ch] as usize], bits); + pred[ch] = (pred[ch] + if code >> (bits - 1) != 0 { -d } else { d }).clamp(-32768, 32767); + idx[ch] = (idx[ch] + index_table(bits)[mag as usize]).clamp(0, 88); + out.push(pred[ch] as i16); + } + } + } +} + +/// Assert `theirs` is `ours` or `alt` over their common length (and say which). +fn same_as_either(what: &str, ours: &[i16], alt: &[i16], theirs: &[i16]) { + let n = ours.len().min(theirs.len()); + let (a, b) = (max_diff(&ours[..n], &theirs[..n]), max_diff(&alt[..n.min(alt.len())], &theirs[..n.min(alt.len())])); + println!("{what}: largest difference from ours {a}, from the other rounding {b}"); + assert!(a == 0 || b == 0, "{what}: ffmpeg's decode is neither ours ({a}) nor the other rounding ({b})"); +} + +/// A name, the WAV file around our stream, our decode of it and the other rounding's. +type Stream = (&'static str, Vec, Vec, Vec); + +// ---- ffmpeg as the reference + +fn ffmpeg(ff: &Path, args: &[&str]) { + let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +fn s(p: &Path) -> String { + p.to_str().expect("path").to_string() +} + +fn write_pcm(path: &Path, x: &[i16]) { + std::fs::write(path, x.iter().flat_map(|v| v.to_le_bytes()).collect::>()).expect("write"); +} + +fn read_pcm(path: &Path) -> Vec { + std::fs::read(path).expect("read").as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect() +} + +/// The `fmt ` chunk's fields and the `data` chunk of a WAV file. +fn wav_parts(bytes: &[u8]) -> (u16, usize, usize, Vec) { + let mut at = 12; + let (mut tag, mut channels, mut align) = (0, 0, 0); + while at + 8 <= bytes.len() { + let id = &bytes[at..at + 4]; + let len = u32::from_le_bytes([bytes[at + 4], bytes[at + 5], bytes[at + 6], bytes[at + 7]]) as usize; + let body = &bytes[at + 8..(at + 8 + len).min(bytes.len())]; + if id == b"fmt " { + tag = u16::from_le_bytes([body[0], body[1]]); + channels = usize::from(u16::from_le_bytes([body[2], body[3]])); + align = usize::from(u16::from_le_bytes([body[12], body[13]])); + } else if id == b"data" { + return (tag, channels, align, body.to_vec()); + } + at += 8 + len + (len & 1); + } + panic!("no data chunk"); +} + +/// A WAV file around `data`. +fn wav(tag: u16, channels: usize, align: usize, bits: u16, extra: &[u8], data: &[u8]) -> Vec { + let mut fmt = Vec::new(); + fmt.extend(tag.to_le_bytes()); + fmt.extend((channels as u16).to_le_bytes()); + fmt.extend(RATE.to_le_bytes()); + fmt.extend((RATE * align as u32 / 500).to_le_bytes()); + fmt.extend((align as u16).to_le_bytes()); + fmt.extend(bits.to_le_bytes()); + if !extra.is_empty() || tag == 0x11 || tag == 2 { + fmt.extend((extra.len() as u16).to_le_bytes()); + fmt.extend(extra); + } + let mut out = b"RIFF".to_vec(); + out.extend((4 + 8 + fmt.len() as u32 + 8 + data.len() as u32).to_le_bytes()); + out.extend(b"WAVEfmt "); + out.extend((fmt.len() as u32).to_le_bytes()); + out.extend(fmt); + out.extend(b"data"); + out.extend((data.len() as u32).to_le_bytes()); + out.extend(data); + out +} + +#[test] +fn we_decode_what_ffmpeg_encodes_to_the_samples_ffmpeg_decodes() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("adpcm"); + for channels in [1usize, 2] { + let x = signal(channels, 30_000); + let pcm = dir.join(format!("in{channels}.pcm")); + write_pcm(&pcm, &x); + let input = ["-f", "s16le", "-ar", "22050", "-ac", if channels == 1 { "1" } else { "2" }, "-i"]; + for (name, codec, align) in [("ima", "adpcm_ima_wav", 512usize), ("ms", "adpcm_ms", 512), ("yamaha", "adpcm_yamaha", 0)] { + let file = dir.join(format!("{name}{channels}.wav")); + let mut args: Vec = input.iter().map(|a| a.to_string()).collect(); + args.extend([s(&pcm), "-c:a".into(), codec.into()]); + if align > 0 { + args.extend(["-block_size".into(), align.to_string()]); + } + args.push(s(&file)); + ffmpeg(&ff, &args.iter().map(String::as_str).collect::>()); + let back = dir.join(format!("{name}{channels}.out.pcm")); + ffmpeg(&ff, &["-i", &s(&file), "-f", "s16le", "-acodec", "pcm_s16le", &s(&back)]); + let theirs = read_pcm(&back); + let (tag, ch, block, data) = wav_parts(&std::fs::read(&file).expect("read")); + assert_eq!(ch, channels); + let ours = match name { + "ima" => { + assert_eq!(tag, 0x11); + ima::decode(&data, ch, block).expect("decode") + } + "ms" => { + assert_eq!(tag, 2); + ms::decode(&data, ch, block).expect("decode") + } + _ => yamaha::decode(&data, ch).expect("decode"), + }; + let n = ours.len().min(theirs.len()); + assert!(n >= 29_000 * channels, "{name} {channels}ch: {} ours, {} theirs", ours.len(), theirs.len()); + if name == "ima" { + same_as_either(&format!("{name} {channels}ch"), &ours, &alt_ima_decode(&data, ch, block), &theirs); + } else { + let d = max_diff(&ours[..n], &theirs[..n]); + println!("{name} {channels}ch: {n} samples, largest difference from ffmpeg's decode {d}"); + assert_eq!(d, 0, "{name} {channels}ch"); + } + // our encoder is as good as ffmpeg's on the same audio, to within 3 dB + let mine = match name { + "ima" => ima::decode(&ima::encode(&x, ch, block).expect("encode"), ch, block).expect("decode"), + "ms" => ms::decode(&ms::encode(&x, ch, block).expect("encode"), ch, block).expect("decode"), + _ => yamaha::decode(&yamaha::encode(&x, ch).expect("encode"), ch).expect("decode"), + }; + let m = x.len().min(mine.len()).min(theirs.len()); + let (a, b) = (snr(&x[..m], &mine[..m]), snr(&x[..m], &theirs[..m])); + println!("{name} {channels}ch: SNR {a:.1} dB ours, {b:.1} dB ffmpeg's"); + assert!(a + 3.0 >= b, "{name} {channels}ch: our encoder {a:.1} dB against ffmpeg's {b:.1} dB"); + } + } +} + +#[test] +fn ffmpeg_decodes_what_we_encode_to_the_samples_we_decode() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("adpcm"); + for channels in [1usize, 2] { + let x = signal(channels, 12_000); + let coefs: Vec = ms::COEFFICIENTS.iter().flat_map(|&(a, b)| [a as i16, b as i16].into_iter().flat_map(i16::to_le_bytes)).collect(); + let streams: Vec = { + let e = ima::encode(&x, channels, 512).unwrap(); + let per = ima::samples_per_block(512, channels).unwrap() as u16; + let d = ima::decode(&e, channels, 512).unwrap(); + let d_alt = alt_ima_decode(&e, channels, 512); + let ima_wav = wav(0x11, channels, 512, 4, &per.to_le_bytes(), &e); + let e = ms::encode(&x, channels, 512).unwrap(); + let per = ms::samples_per_block(512, channels).unwrap() as u16; + let d2 = ms::decode(&e, channels, 512).unwrap(); + let mut extra = per.to_le_bytes().to_vec(); + extra.extend(7u16.to_le_bytes()); + extra.extend(&coefs); + let ms_wav = wav(2, channels, 512, 4, &extra, &e); + let e = yamaha::encode(&x, channels).unwrap(); + let d3 = yamaha::decode(&e, channels).unwrap(); + let y_wav = wav(0x20, channels, 512 * channels, 4, &[], &e); + vec![("ima", ima_wav, d, d_alt), ("ms", ms_wav, d2.clone(), d2), ("yamaha", y_wav, d3.clone(), d3)] + }; + for (name, bytes, ours, alt) in streams { + let file = dir.join(format!("our_{name}{channels}.wav")); + std::fs::write(&file, bytes).expect("write"); + let back = dir.join(format!("our_{name}{channels}.pcm")); + ffmpeg(&ff, &["-i", &s(&file), "-f", "s16le", "-acodec", "pcm_s16le", &s(&back)]); + let theirs = read_pcm(&back); + let n = ours.len().min(theirs.len()); + assert!(n + 2048 >= ours.len(), "{name} {channels}ch: ffmpeg decoded {} of {}", theirs.len(), ours.len()); + same_as_either(&format!("{name} {channels}ch, our stream"), &ours, &alt, &theirs); + } + } +} + +/// The audio tags of an FLV file: each tag's body without its flags byte. +fn flv_audio(bytes: &[u8]) -> Vec> { + let mut at = 13; + let mut out = Vec::new(); + while at + 11 <= bytes.len() { + let kind = bytes[at]; + let len = (usize::from(bytes[at + 1]) << 16) | (usize::from(bytes[at + 2]) << 8) | usize::from(bytes[at + 3]); + let body = &bytes[at + 11..(at + 11 + len).min(bytes.len())]; + if kind == 8 && body.len() > 1 { + assert_eq!(body[0] >> 4, 1, "SWF ADPCM tag"); + out.push(body[1..].to_vec()); + } + at += 11 + len + 4; + } + out +} + +/// An FLV file of 44.1 kHz audio tags with these ADPCM bodies. +fn flv(stereo: bool, tags: &[Vec]) -> Vec { + let mut out = b"FLV\x01\x04\0\0\0\x09\0\0\0\0".to_vec(); + let flags = (1u8 << 4) | (3 << 2) | (1 << 1) | u8::from(stereo); + for (i, t) in tags.iter().enumerate() { + let len = t.len() + 1; + let ts = (i * 4096 * 1000 / 44_100) as u32; + out.extend([ + 8, + (len >> 16) as u8, + (len >> 8) as u8, + len as u8, + (ts >> 16) as u8, + (ts >> 8) as u8, + ts as u8, + (ts >> 24) as u8, + 0, + 0, + 0, + flags, + ]); + out.extend(t); + out.extend((len as u32 + 11).to_be_bytes()); + } + out +} + +#[test] +fn flash_adpcm_matches_ffmpeg_in_both_directions() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("adpcm"); + for channels in [1usize, 2] { + let x = signal(channels, 4096 * 3); + let pcm = dir.join(format!("swf_in{channels}.pcm")); + write_pcm(&pcm, &x); + // ffmpeg encodes (it needs 44.1 kHz for FLV) + let file = dir.join(format!("swf{channels}.flv")); + ffmpeg(&ff, &["-f", "s16le", "-ar", "44100", "-ac", &channels.to_string(), "-i", &s(&pcm), "-c:a", "adpcm_swf", "-f", "flv", &s(&file)]); + let tags = flv_audio(&std::fs::read(&file).expect("read")); + assert!(tags.len() >= 3, "{} tags", tags.len()); + let back = dir.join(format!("swf{channels}.out.pcm")); + ffmpeg(&ff, &["-i", &s(&file), "-f", "s16le", "-acodec", "pcm_s16le", &s(&back)]); + let theirs = read_pcm(&back); + let ours: Vec = tags.iter().flat_map(|t| swf::decode(t, channels).expect("decode")).collect(); + assert_eq!(ours.len(), 4096 * 3 * channels); + assert_eq!(theirs.len(), 4096 * 3 * channels); + let alt: Vec = tags.iter().flat_map(|t| alt_swf_decode(t, channels)).collect(); + same_as_either(&format!("swf {channels}ch"), &ours, &alt, &theirs); + // ffmpeg decodes ours, one 4096-sample stream per tag + for bits in [2u32, 3, 4, 5] { + let tags: Vec> = x.chunks(4096 * channels).map(|c| swf::encode(c, channels, bits).expect("encode")).collect(); + let ours: Vec = tags.iter().flat_map(|t| swf::decode(t, channels).expect("decode")).collect(); + let file = dir.join(format!("our_swf{channels}_{bits}.flv")); + std::fs::write(&file, flv(channels == 2, &tags)).expect("write"); + let back = dir.join(format!("our_swf{channels}_{bits}.pcm")); + ffmpeg(&ff, &["-i", &s(&file), "-f", "s16le", "-acodec", "pcm_s16le", &s(&back)]); + let theirs = read_pcm(&back); + assert_eq!(ours.len(), 4096 * 3 * channels); + assert_eq!(theirs.len(), 4096 * 3 * channels); + let alt: Vec = tags.iter().flat_map(|t| alt_swf_decode(t, channels)).collect(); + same_as_either(&format!("swf {channels}ch {bits} bits, our stream"), &ours, &alt, &theirs); + } + } +} diff --git a/crates/audio/tests/audio/decode_extensions.rs b/crates/audio/tests/audio/decode_extensions.rs index 27a5573de..fc961cc39 100644 --- a/crates/audio/tests/audio/decode_extensions.rs +++ b/crates/audio/tests/audio/decode_extensions.rs @@ -77,6 +77,6 @@ fn every_encode_format_has_an_extension_it_is_written_and_read_under() { assert!(format.mime_type().starts_with("audio/"), "{format:?}"); } let extensions: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.extension()).collect(); - assert_eq!(extensions, ["wav", "aif", "flac", "m4a", "m4a", "mp3", "ac3", "eac3"]); + 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 7713f37a5..72749df04 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 ["ogg", "opus", "aac", "mp4", "xyz", ""] { + for other in ["opus", "aac", "mp4", "xyz", ""] { assert_eq!(encode_format_for(other), None, "{other}"); } } + +#[test] +fn ogg_names_follow_the_feature() { + let built = cfg!(feature = "vorbis-encode"); + 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 index 53947df12..82edf72aa 100644 --- a/crates/audio/tests/codecs/file_formats.rs +++ b/crates/audio/tests/codecs/file_formats.rs @@ -397,12 +397,15 @@ fn the_formats_are_named() { for name in ENCODE_EXTENSIONS { assert!(encode_format_for(name).is_some(), "{name}"); } - assert_eq!(ENCODE_EXTENSIONS.len(), 12); + 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"]); + 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. @@ -495,6 +498,10 @@ fn the_format_queries_agree_with_the_writer() { 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 { @@ -520,7 +527,7 @@ fn the_format_queries_agree_with_the_writer() { // 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]); + assert_eq!(most, [32_767, 32_767, 8, 8, 8, 2, 6, 8, 8]); for &format in EncodeFormat::ALL { let most = format.max_channels(); match format.fixed_layouts(most) { @@ -569,3 +576,16 @@ fn the_bit_rate_used_can_be_asked_for() { 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 c1c9e2131..41829be5c 100644 --- a/crates/audio/tests/codecs/main.rs +++ b/crates/audio/tests/codecs/main.rs @@ -20,3 +20,5 @@ mod opus; mod opusenc; mod routing_oracle; mod track_decoder; +#[cfg(feature = "vorbis-encode")] +mod vorbis_encoder_oracle; diff --git a/crates/audio/tests/codecs/vorbis_encoder_oracle.rs b/crates/audio/tests/codecs/vorbis_encoder_oracle.rs new file mode 100644 index 000000000..342f4fd9a --- /dev/null +++ b/crates/audio/tests/codecs/vorbis_encoder_oracle.rs @@ -0,0 +1,131 @@ +//! ffmpeg as an external oracle for the pure-Rust Vorbis encoder: both of its decoders (its own +//! and libvorbis) read every file exactly as long as the input, surround comes out on the right +//! speakers, and the tags reach ffprobe. Skipped when ffmpeg is not installed. + +use std::path::Path; +use std::process::Command; + +use craft_audio::{AudioBuffer, ChannelLayout, EncodeFormat, EncodeOptions, OggVorbisOptions, encode, encode_ogg_vorbis}; + +/// A different tone on every channel, so each output channel can be traced to its input. +fn tones(rate: u32, channels: usize, frames: usize) -> AudioBuffer { + let channels = (0..channels) + .map(|c| { + let f = 220.0 * (c + 1) as f32; + (0..frames).map(|i| (std::f32::consts::TAU * f * i as f32 / rate as f32).sin() * 0.3).collect() + }) + .collect(); + AudioBuffer { sample_rate: rate, channels } +} + +/// Decodes `file` with ffmpeg's `decoder`; planar output in ffmpeg's (WAV) channel order. +fn ffmpeg_decode(ff: &Path, decoder: &str, file: &[u8], channels: usize, tag: &str) -> Vec> { + let path = crate::testkit::fixtures_dir("vorbis-encoder").join(format!("{tag}.ogg")); + std::fs::write(&path, file).unwrap(); + let out = Command::new(ff) + .args(["-v", "error", "-xerror", "-c:a", decoder, "-i"]) + .arg(&path) + .args(["-f", "f32le", "-c:a", "pcm_f32le", "-"]) + .output() + .unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "{tag} {decoder}: {}", String::from_utf8_lossy(&out.stderr)); + let pcm: Vec = out.stdout.as_chunks::<4>().0.iter().map(|&b| f32::from_le_bytes(b)).collect(); + (0..channels).map(|c| pcm.iter().skip(c).step_by(channels).copied().collect()).collect() +} + +/// ffmpeg's decoders to check: its own `vorbis` always, and `libvorbis` when ffmpeg has it. +fn decoders(ff: &Path) -> Vec<&'static str> { + let list = + Command::new(ff).args(["-hide_banner", "-decoders"]).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default(); + if list.lines().any(|l| l.split_whitespace().nth(1) == Some("libvorbis")) { + vec!["vorbis", "libvorbis"] + } else { + eprintln!("SKIPPED (libvorbis decoder): this ffmpeg has no libvorbis; checking its own decoder only"); + vec!["vorbis"] + } +} + +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + ab += f64::from(x) * f64::from(y); + aa += f64::from(x) * f64::from(x); + bb += f64::from(y) * f64::from(y); + } + ab / (aa * bb).sqrt().max(1e-20) +} + +/// Vorbis order (§4.3.9) of the WAV-order layouts the test writes, per channel count. +const VORBIS_ORDER: [&[usize]; 8] = + [&[0], &[0, 1], &[0, 2, 1], &[0, 1, 2, 3], &[0, 2, 1, 3, 4], &[0, 2, 1, 4, 5, 3], &[0, 2, 1, 5, 6, 4, 3], &[0, 2, 1, 6, 7, 4, 5, 3]]; + +/// 1 to 8 channels through `encode` with a WAV-order layout, at exactly the input's length out of +/// both decoders: ffmpeg's own puts every channel back on its WAV speaker, and libvorbis (through +/// ffmpeg, which passes its order through) gives the file's Vorbis order. +#[test] +fn every_channel_count_decodes_on_the_right_speakers() { + let ff = require_ffmpeg!(); + for channels in 1..=8u16 { + let layout = if channels == 7 { ChannelLayout::from_mask(0x70F) } else { ChannelLayout::default_for(channels) }; + let buf = tones(48_000, channels.into(), 24_000 + 77); + let opts = EncodeOptions::new(EncodeFormat::Ogg).with_layout(layout).with_quality(0.6); + let file = encode(&buf, &opts).unwrap(); + for decoder in decoders(&ff) { + let out = ffmpeg_decode(&ff, decoder, &file, channels.into(), &format!("tones{channels}-{decoder}")); + for (j, got) in out.iter().enumerate() { + let c = if decoder == "libvorbis" { VORBIS_ORDER[usize::from(channels) - 1][j] } else { j }; + assert_eq!(got.len(), buf.frames(), "{channels} ch {decoder}: channel {j} length"); + let best = (0..buf.channels.len()).max_by(|&a, &b| { + correlation(&buf.channels[a][2048..], &got[2048..]).total_cmp(&correlation(&buf.channels[b][2048..], &got[2048..])) + }); + assert_eq!(best, Some(c), "{channels} ch {decoder}: output channel {c} carries input {best:?}"); + let r = correlation(&buf.channels[c][2048..], &got[2048..]); + assert!(r > 0.95, "{channels} ch {decoder}: channel {c} correlation {r:.3}"); + } + } + } +} + +/// The comment header's tags, UTF-8 values included, are what ffprobe reports; a name that is not +/// a valid field name is left out. +#[test] +fn tags_reach_ffprobe() { + let Some(probe) = crate::common::tool("ffprobe").or_else(|| crate::common::skip("ffprobe not found")) else { return }; + let opts = OggVorbisOptions::new(3.0) + .with_tag("TITLE", "Smörgåsbord ✓") + .with_tag("ARTIST", "Craft") + .with_tag("bad=name", "dropped") + .with_vendor("craft-audio test"); + let file = encode_ogg_vorbis(&tones(44_100, 2, 44_100), &opts).unwrap(); + let path = crate::testkit::fixtures_dir("vorbis-encoder").join("tags.ogg"); + std::fs::write(&path, &file).unwrap(); + let out = Command::new(probe).args(["-v", "error", "-of", "json", "-show_streams", "-show_format"]).arg(&path).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let j: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + let s = &j["streams"][0]; + assert_eq!((s["codec_name"].as_str(), s["channels"].as_u64(), s["sample_rate"].as_str()), (Some("vorbis"), Some(2), Some("44100"))); + let tags = &s["tags"]; + assert_eq!((tags["TITLE"].as_str(), tags["ARTIST"].as_str()), (Some("Smörgåsbord ✓"), Some("Craft"))); + assert!(tags.as_object().unwrap().keys().all(|k| !k.contains("bad")), "{tags}"); + assert_eq!(j["format"]["duration"].as_str().map(|d| d.parse::().unwrap()), Some(1.0)); +} + +/// The lowest and highest qualities and the bit-rate path decode at the exact length, mono at +/// 44.1 kHz and stereo at 22.05 kHz. +#[test] +fn quality_extremes_and_rates_decode_exactly() { + let ff = require_ffmpeg!(); + for (rate, channels, quality) in [(44_100u32, 1usize, -1.0f32), (44_100, 1, 10.0), (22_050, 2, -1.0), (22_050, 2, 10.0), (96_000, 2, 5.0)] { + let buf = tones(rate, channels, rate as usize / 2 + 13); + let file = encode_ogg_vorbis(&buf, &OggVorbisOptions::new(quality)).unwrap(); + for decoder in decoders(&ff) { + let out = ffmpeg_decode(&ff, decoder, &file, channels, &format!("q{quality}-{rate}-{channels}-{decoder}")); + assert!(out.iter().all(|c| c.len() == buf.frames()), "q{quality} {rate} Hz {decoder}: {}", out[0].len()); + let r = correlation(&buf.channels[0][2048..], &out[0][2048..]); + assert!(r > 0.9, "q{quality} {rate} Hz {decoder}: correlation {r:.3}"); + } + } + let low = craft_audio::encode_ogg(&tones(48_000, 2, 48_000), craft_audio::OGG_BITRATES.0).unwrap(); + let high = craft_audio::encode_ogg(&tones(48_000, 2, 48_000), craft_audio::OGG_BITRATES.1).unwrap(); + assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len()); +} diff --git a/crates/audio/tests/dsd_bounds.rs b/crates/audio/tests/dsd_bounds.rs new file mode 100644 index 000000000..5388f2aa4 --- /dev/null +++ b/crates/audio/tests/dsd_bounds.rs @@ -0,0 +1,208 @@ +//! Hostile container sizes must return errors, never wrap offsets or panic. +use craft_audio::dsd::{BitOrder, Error, RawAudio, encode_dsdiff, encode_dsf, read_metadata, read_raw}; + +#[test] +fn dsf_untrusted_sizes_are_checked() { + let original = encode_dsf(2_822_400, &[&[0x69; 8]], 64, 8).unwrap(); + for offset in [32, 84] { + // fmt and data chunk sizes + for size in [u64::MAX, u64::MAX - 31, 1 << 32] { + let mut bytes = original.clone(); + bytes[offset..offset + 8].copy_from_slice(&size.to_le_bytes()); + assert!(read_metadata(&bytes).is_err()); + assert!(read_raw(&bytes).is_err()); + } + } + let mut bytes = original; + bytes[64..72].copy_from_slice(&u64::MAX.to_le_bytes()); + assert_eq!(read_raw(&bytes), Err(Error::MemoryLimitExceeded)); +} + +#[test] +fn dsdiff_untrusted_top_level_and_property_sizes_are_checked() { + let original = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap(); + let prop = original.windows(4).position(|w| w == b"PROP").unwrap(); + for offset in [4, 20, prop + 20] { + // FRM8, FVER, nested FS + for size in [u64::MAX, u64::MAX - 31, 1 << 32] { + let mut bytes = original.clone(); + bytes[offset..offset + 8].copy_from_slice(&size.to_be_bytes()); + assert!(read_metadata(&bytes).is_err()); + assert!(read_raw(&bytes).is_err()); + } + } +} + +#[test] +fn dsdiff_invalid_optional_disc_info_is_ignored_without_overflow() { + let mut bytes = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap(); + let expected = read_metadata(&bytes).unwrap(); + bytes.extend_from_slice(b"DIIN"); + bytes.extend_from_slice(&12u64.to_be_bytes()); + bytes.extend_from_slice(b"DITI"); + bytes.extend_from_slice(&u64::MAX.to_be_bytes()); + let size = (bytes.len() - 12) as u64; + bytes[4..12].copy_from_slice(&size.to_be_bytes()); + // Optional malformed text is ignored on 64-bit; unrepresentable sizes may + // be rejected on narrower targets, but must never wrap or panic. + match read_metadata(&bytes) { + Ok(actual) => assert_eq!(actual, expected), + Err(Error::MemoryLimitExceeded) => {} + other => panic!("unexpected result: {other:?}"), + } +} + +#[test] +fn empty_raw_audio_rejects_invalid_decimation_factors() { + let bytes = encode_dsf(2_822_400, &[&[]], 0, 8).unwrap(); + let raw = RawAudio { metadata: read_metadata(&bytes).unwrap(), bit_order: BitOrder::LsbFirst, channel_bytes: Vec::new() }; + for factor in [0, 1, 7, 9, u32::MAX] { + assert!(matches!(raw.to_pcm_with_factor(factor), Err(Error::Unsupported(_)))); + } + for factor in [8, 16, 32, 64] { + assert_eq!(raw.to_pcm_with_factor(factor).unwrap().sample_rate, 2_822_400 / factor); + } +} + +#[test] +fn writers_reject_unbounded_output_before_allocating() { + let channels: [&[u8]; 8] = [&[]; 8]; + for count in [u64::MAX, (craft_audio::dsd::MAX_ENCODE_BYTES as u64 + 1) * 8] { + assert_eq!(encode_dsf(2_822_400, &channels, count, 8), Err(Error::MemoryLimitExceeded)); + assert_eq!(encode_dsdiff(2_822_400, &channels, count), Err(Error::MemoryLimitExceeded)); + } + assert!(matches!(encode_dsf(2_822_400, &[&[]], 0, u32::MAX), Err(Error::InvalidData(_)))); +} + +#[test] +fn encoded_sizes_match_actual_bytes_for_odd_and_even_payloads() { + for channels in 1..=8 { + for len in 0..=9 { + let data = vec![0x69; len]; + let planes = vec![data.as_slice(); channels]; + for block in [0, 1, 3, 8] { + // DSF has channel types for 1 to 6 channels only. + if channels > 6 { + assert!(matches!(encode_dsf(2_822_400, &planes, len as u64 * 8, block), Err(Error::Unsupported(_)))); + continue; + } + let dsf = encode_dsf(2_822_400, &planes, len as u64 * 8, block).unwrap(); + assert_eq!(u64::from_le_bytes(dsf[12..20].try_into().unwrap()), dsf.len() as u64); + assert_eq!(read_raw(&dsf).unwrap().channel_bytes, vec![data.clone(); channels]); + } + let dff = encode_dsdiff(2_822_400, &planes, len as u64 * 8).unwrap(); + assert_eq!(u64::from_be_bytes(dff[4..12].try_into().unwrap()) + 12, dff.len() as u64); + assert_eq!(read_raw(&dff).unwrap().channel_bytes, vec![data; channels]); + } + } +} + +#[test] +fn dsf_audio_stops_at_the_declared_data_chunk() { + for channels in 1..=2 { + let input = vec![&[0x33u8; 8][..]; channels]; + let mut bytes = encode_dsf(2_822_400, &input, 64, 8).unwrap(); + // Ask for an additional block without extending the data chunk. + bytes[64..72].copy_from_slice(&128u64.to_le_bytes()); + let expected = read_raw(&bytes).unwrap(); + for c in &expected.channel_bytes { + assert_eq!(&c[..8], &[0x33; 8]); + assert_eq!(&c[8..], &[0x69; 8]); + } + let metadata_offset = bytes.len() as u64; + bytes[20..28].copy_from_slice(&metadata_offset.to_le_bytes()); + bytes.extend_from_slice(b"ID3\x04\x00\x00\x00\x00\x00\x00"); + bytes.extend_from_slice(&[0xff; 32]); + let file_size = bytes.len() as u64; + bytes[12..20].copy_from_slice(&file_size.to_le_bytes()); + assert_eq!(read_raw(&bytes).unwrap().channel_bytes, expected.channel_bytes); + } +} + +#[test] +fn dsdiff_odd_payload_receives_pad_byte() { + let input = [&[0xaau8; 3][..]]; + let bytes = encode_dsdiff(2_822_400, &input, 24).unwrap(); + let raw = read_raw(&bytes).unwrap(); + assert_eq!(raw.channel_bytes[0].len(), 3); +} + +#[test] +fn dsf_declared_file_size_and_metadata_pointer_bounds() { + let valid = encode_dsf(2_822_400, &[&[0x69; 8]], 64, 8).unwrap(); + + // Undersized file size declaration (e.g. 28) + let mut undersized = valid.clone(); + undersized[12..20].copy_from_slice(&28u64.to_le_bytes()); + assert!(read_metadata(&undersized).is_err()); + assert!(read_raw(&undersized).is_err()); + + // Oversized file size declaration beyond buffer + let mut oversized = valid.clone(); + let big_size = valid.len() as u64 + 100; + oversized[12..20].copy_from_slice(&big_size.to_le_bytes()); + assert!(read_metadata(&oversized).is_err()); + assert!(read_raw(&oversized).is_err()); + + // Metadata pointer outside the declared file bounds + let mut outside_meta = valid.clone(); + let outside_offset = valid.len() as u64 + 10; + outside_meta[20..28].copy_from_slice(&outside_offset.to_le_bytes()); + assert!(read_metadata(&outside_meta).is_err()); + assert!(read_raw(&outside_meta).is_err()); + + // Metadata pointer overlapping data chunk + let mut overlap_meta = valid.clone(); + overlap_meta[20..28].copy_from_slice(&32u64.to_le_bytes()); + assert!(read_metadata(&overlap_meta).is_err()); + assert!(read_raw(&overlap_meta).is_err()); +} + +#[test] +fn dsdiff_channel_count_and_duplicate_chunks_are_validated() { + let base = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap(); + + // Locate PROP chunk payload and CHNL subchunk + let prop_idx = base.windows(4).position(|w| w == b"PROP").unwrap(); + let chnl_idx = base.windows(4).position(|w| w == b"CHNL").unwrap(); + + // 1. Oversized channel count (e.g. 65535 or 9) + let mut bad_count = base.clone(); + bad_count[chnl_idx + 12..chnl_idx + 14].copy_from_slice(&65535u16.to_be_bytes()); + assert!(matches!(read_metadata(&bad_count), Err(Error::Unsupported(_)))); + assert!(matches!(read_raw(&bad_count), Err(Error::Unsupported(_)))); + + let mut zero_count = base.clone(); + zero_count[chnl_idx + 12..chnl_idx + 14].copy_from_slice(&0u16.to_be_bytes()); + assert!(matches!(read_metadata(&zero_count), Err(Error::Unsupported(_)))); + + // 2. Conflicting duplicate CHNL chunk in PROP + let mut dup_chnl = base.clone(); + let chnl_chunk = dup_chnl[chnl_idx..chnl_idx + 18].to_vec(); + dup_chnl.splice(chnl_idx..chnl_idx, chnl_chunk); + // Adjust PROP size and FRM8 size + let prop_size = u64::from_be_bytes(dup_chnl[prop_idx + 4..prop_idx + 12].try_into().unwrap()) + 18; + dup_chnl[prop_idx + 4..prop_idx + 12].copy_from_slice(&prop_size.to_be_bytes()); + let frm8_size = (dup_chnl.len() - 12) as u64; + dup_chnl[4..12].copy_from_slice(&frm8_size.to_be_bytes()); + assert_eq!(read_metadata(&dup_chnl), Err(Error::InvalidHeader("duplicate CHNL chunk"))); + + // 3. Duplicate FS chunk in PROP + let fs_idx = base.windows(4).position(|w| w == b"FS ").unwrap(); + let mut dup_fs = base.clone(); + let fs_chunk = dup_fs[fs_idx..fs_idx + 16].to_vec(); + dup_fs.splice(fs_idx..fs_idx, fs_chunk); + let prop_size = u64::from_be_bytes(dup_fs[prop_idx + 4..prop_idx + 12].try_into().unwrap()) + 16; + dup_fs[prop_idx + 4..prop_idx + 12].copy_from_slice(&prop_size.to_be_bytes()); + let frm8_size = (dup_fs.len() - 12) as u64; + dup_fs[4..12].copy_from_slice(&frm8_size.to_be_bytes()); + assert_eq!(read_metadata(&dup_fs), Err(Error::InvalidHeader("duplicate FS chunk"))); +} + +#[test] +#[cfg(target_pointer_width = "32")] +fn dsdiff_32bit_padding_overflow_is_rejected() { + let dummy = [&[][..]]; + let result = encode_dsdiff(2_822_400, &dummy, 34_359_738_360); + assert_eq!(result, Err(Error::MemoryLimitExceeded)); +} diff --git a/crates/audio/tests/dsd_metadata.rs b/crates/audio/tests/dsd_metadata.rs new file mode 100644 index 000000000..74fd16f31 --- /dev/null +++ b/crates/audio/tests/dsd_metadata.rs @@ -0,0 +1,155 @@ +//! Channel labels, text metadata and padding in the DSF and DSDIFF readers and writers. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use craft_audio::dsd::{encode_dsdiff, encode_dsf, read_metadata, read_raw}; + +const RATE: u32 = 2_822_400; + +fn planes(channels: usize, len: usize) -> Vec> { + vec![vec![0x69; len]; channels] +} + +fn refs(p: &[Vec]) -> Vec<&[u8]> { + p.iter().map(Vec::as_slice).collect() +} + +#[test] +fn dsdiff_names_surround_channels_by_layout() { + for (n, names) in [ + (5, vec!["Mono/Left", "Right", "Center", "LeftSurround", "RightSurround"]), + (6, vec!["Mono/Left", "Right", "Center", "LFE", "LeftSurround", "RightSurround"]), + ] { + let p = planes(n, 4); + let bytes = encode_dsdiff(RATE, &refs(&p), 32).unwrap(); + assert_eq!(read_metadata(&bytes).unwrap().channel_names, names, "{n} channels"); + } +} + +#[test] +fn dsdiff_odd_audio_is_padded_and_counted_in_the_file_size() { + let p = planes(1, 1); + let bytes = encode_dsdiff(RATE, &refs(&p), 8).unwrap(); + assert_eq!(bytes.len() % 2, 0); + assert_eq!(u64::from_be_bytes(bytes[4..12].try_into().unwrap()) + 12, bytes.len() as u64); + assert_eq!(*bytes.last().unwrap(), 0, "pad byte"); + assert_eq!(read_raw(&bytes).unwrap().channel_bytes, vec![vec![0x69]]); +} + +fn with_diin(mut bytes: Vec, sub: &[u8; 4], payload: &[u8]) -> Vec { + let mut sub_chunk = Vec::new(); + sub_chunk.extend_from_slice(sub); + sub_chunk.extend_from_slice(&(payload.len() as u64).to_be_bytes()); + sub_chunk.extend_from_slice(payload); + if payload.len() % 2 == 1 { + sub_chunk.push(0); + } + bytes.extend_from_slice(b"DIIN"); + bytes.extend_from_slice(&(sub_chunk.len() as u64).to_be_bytes()); + bytes.extend_from_slice(&sub_chunk); + let size = (bytes.len() - 12) as u64; + bytes[4..12].copy_from_slice(&size.to_be_bytes()); + bytes +} + +#[test] +fn dsdiff_title_and_artist_skip_the_character_count() { + let p = planes(2, 4); + let base = encode_dsdiff(RATE, &refs(&p), 32).unwrap(); + let mut payload = 4u32.to_be_bytes().to_vec(); + payload.extend_from_slice(b"Test"); + let bytes = with_diin(base.clone(), b"DITI", &payload); + assert_eq!(read_metadata(&bytes).unwrap().title.as_deref(), Some("Test")); + let bytes = with_diin(base.clone(), b"DIAR", &payload); + assert_eq!(read_metadata(&bytes).unwrap().artist.as_deref(), Some("Test")); + // A count longer than the chunk is not text. + let mut bad = 99u32.to_be_bytes().to_vec(); + bad.extend_from_slice(b"Test"); + assert_eq!(read_metadata(&with_diin(base, b"DITI", &bad)).unwrap().title, None); +} + +#[test] +fn dsf_channel_types_match_the_channel_count() { + for (n, expect) in [(1, 1), (2, 2), (3, 3), (4, 4), (5, 6), (6, 7)] { + let p = planes(n, 4); + let bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + assert_eq!(u32::from_le_bytes(bytes[48..52].try_into().unwrap()), expect, "{n} channels"); + assert_eq!(read_metadata(&bytes).unwrap().channel_names.len(), n); + } + let p = planes(7, 4); + assert!(encode_dsf(RATE, &refs(&p), 32, 4096).is_err()); +} + +#[test] +fn dsf_type_5_names_the_fourth_channel_lfe() { + let p = planes(4, 4); + let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + bytes[48..52].copy_from_slice(&5u32.to_le_bytes()); + assert_eq!(read_metadata(&bytes).unwrap().channel_names, ["FrontLeft", "FrontRight", "Center", "LFE"]); +} + +fn id3(version: u8, frames: &[u8]) -> Vec { + let n = frames.len(); + let mut tag = vec![b'I', b'D', b'3', version, 0, 0]; + tag.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]); + tag.extend_from_slice(frames); + tag +} + +fn frame(version: u8, id: &[u8; 4], body: &[u8]) -> Vec { + let n = body.len(); + let mut f = id.to_vec(); + if version >= 4 { + f.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]); + } else { + f.extend_from_slice(&(n as u32).to_be_bytes()); + } + f.extend_from_slice(&[0, 0]); + f.extend_from_slice(body); + f +} + +fn dsf_with_tag(tag: &[u8]) -> Vec { + let p = planes(2, 4); + let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + let offset = bytes.len() as u64; + bytes[20..28].copy_from_slice(&offset.to_le_bytes()); + bytes.extend_from_slice(tag); + let file_size = bytes.len() as u64; + bytes[12..20].copy_from_slice(&file_size.to_le_bytes()); + bytes +} + +#[test] +fn id3v24_frame_sizes_are_synchsafe() { + // A 128-byte frame has the synchsafe size 00 00 01 00; read as plain big-endian it is 256. + let mut frames = frame(4, b"APIC", &[0u8; 128]); + let mut title = vec![3]; + title.extend_from_slice(b"After art"); + frames.extend(frame(4, b"TIT2", &title)); + let m = read_metadata(&dsf_with_tag(&id3(4, &frames))).unwrap(); + assert_eq!(m.title.as_deref(), Some("After art")); +} + +#[test] +fn id3v23_frame_sizes_stay_big_endian() { + let mut frames = frame(3, b"APIC", &[0u8; 128]); + let mut title = vec![3]; + title.extend_from_slice(b"Three"); + frames.extend(frame(3, b"TIT2", &title)); + let m = read_metadata(&dsf_with_tag(&id3(3, &frames))).unwrap(); + assert_eq!(m.title.as_deref(), Some("Three")); +} + +#[test] +fn id3_text_encodings() { + let cases: [(&[u8], &str); 5] = [ + (b"\x00Caf\xe9", "Café"), + (b"\x03Caf\xc3\xa9", "Café"), + (b"\x02\x00A\x00B", "AB"), + (b"\x01\xFF\xFEA\x00B\x00", "AB"), + (b"\x01\xFE\xFF\x00A\x00B", "AB"), + ]; + for (body, expect) in cases { + let m = read_metadata(&dsf_with_tag(&id3(4, &frame(4, b"TIT2", body)))).unwrap(); + assert_eq!(m.title.as_deref(), Some(expect), "{body:?}"); + } +} diff --git a/crates/audio/tests/dsd_oracle.rs b/crates/audio/tests/dsd_oracle.rs new file mode 100644 index 000000000..94334485b --- /dev/null +++ b/crates/audio/tests/dsd_oracle.rs @@ -0,0 +1,347 @@ +//! DSD (DSF and DSDIFF) decoding and decimation tests, including oracle tests against FFmpeg +//! (skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). + +use craft_audio::dsd::{BitOrder, Format, decode, decode_with_factor, encode_dsdiff, encode_dsf, filter::SILENCE_LSBF, read_metadata, read_raw}; +use std::process::Command; + +/// Generates a test DSD 1-bit stream with various features (silence, alternating tones, noise). +fn make_test_stream(num_bytes: usize, seed: u8) -> Vec { + let mut out = Vec::with_capacity(num_bytes); + let mut s = seed as u32; + for i in 0..num_bytes { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + let byte = match (i / 128) % 4 { + 0 => SILENCE_LSBF, // DSD silence + 1 => 0x55, // Alternate silence pattern + 2 => (s & 0xFF) as u8, + _ => { + if (i / 16) % 2 == 0 { + 0xFF // full positive level + } else { + 0x00 // full negative level + } + } + }; + out.push(byte); + } + out +} + +#[test] +fn roundtrip_dsf() { + let sample_rate = 2_822_400; + let block_size = 4096; + let ch0 = make_test_stream(8192, 42); + let ch1 = make_test_stream(8192, 99); + let sample_count = 8192 * 8; + + let dsf_bytes = encode_dsf(sample_rate, &[&ch0, &ch1], sample_count, block_size).expect("encode_dsf"); + + let meta = read_metadata(&dsf_bytes).expect("read_metadata"); + assert_eq!(meta.format, Format::Dsf); + assert_eq!(meta.sample_rate, sample_rate); + assert_eq!(meta.channels, 2); + assert_eq!(meta.sample_count, sample_count); + + let raw = read_raw(&dsf_bytes).expect("read_raw"); + assert_eq!(raw.bit_order, BitOrder::LsbFirst); + assert_eq!(raw.channel_bytes.len(), 2); + assert_eq!(raw.channel_bytes[0], ch0); + assert_eq!(raw.channel_bytes[1], ch1); + + let decoded = decode(&dsf_bytes).expect("decode"); + assert_eq!(decoded.sample_rate, sample_rate / 8); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 8192); + assert_eq!(decoded.channels[1].len(), 8192); +} + +#[test] +fn roundtrip_dsdiff() { + let sample_rate = 2_822_400; + let ch0 = make_test_stream(4096, 17); + let ch1 = make_test_stream(4096, 73); + let sample_count = 4096 * 8; + + let dff_bytes = encode_dsdiff(sample_rate, &[&ch0, &ch1], sample_count).expect("encode_dsdiff"); + + let meta = read_metadata(&dff_bytes).expect("read_metadata"); + assert_eq!(meta.format, Format::Dsdiff); + assert_eq!(meta.sample_rate, sample_rate); + assert_eq!(meta.channels, 2); + assert_eq!(meta.sample_count, sample_count); + + let raw = read_raw(&dff_bytes).expect("read_raw"); + assert_eq!(raw.bit_order, BitOrder::MsbFirst); + assert_eq!(raw.channel_bytes.len(), 2); + assert_eq!(raw.channel_bytes[0], ch0); + assert_eq!(raw.channel_bytes[1], ch1); + + let decoded = decode(&dff_bytes).expect("decode"); + assert_eq!(decoded.sample_rate, sample_rate / 8); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 4096); + assert_eq!(decoded.channels[1].len(), 4096); +} + +#[test] +fn decimation_factors() { + let sample_rate = 2_822_400; + let ch0 = make_test_stream(2048, 123); + let dsf_bytes = encode_dsf(sample_rate, &[&ch0], 2048 * 8, 4096).expect("encode_dsf"); + + // Factor 8 -> 352,800 Hz + let dec8 = decode_with_factor(&dsf_bytes, 8).expect("factor 8"); + assert_eq!(dec8.sample_rate, 352_800); + assert_eq!(dec8.channels[0].len(), 2048); + + // Factor 16 -> 176,400 Hz + let dec16 = decode_with_factor(&dsf_bytes, 16).expect("factor 16"); + assert_eq!(dec16.sample_rate, 176_400); + assert_eq!(dec16.channels[0].len(), 1024); + + // Factor 32 -> 88,200 Hz + let dec32 = decode_with_factor(&dsf_bytes, 32).expect("factor 32"); + assert_eq!(dec32.sample_rate, 88_200); + assert_eq!(dec32.channels[0].len(), 512); + + // Factor 64 -> 44,100 Hz + let dec64 = decode_with_factor(&dsf_bytes, 64).expect("factor 64"); + assert_eq!(dec64.sample_rate, 44_100); + assert_eq!(dec64.channels[0].len(), 256); + + // Invalid factor + assert!(decode_with_factor(&dsf_bytes, 12).is_err()); +} + +#[test] +fn silence_and_dc_levels() { + let sample_rate = 2_822_400; + // Pure silence + let silence = vec![SILENCE_LSBF; 1024]; + let dsf_bytes = encode_dsf(sample_rate, &[&silence], 1024 * 8, 4096).expect("encode"); + let dec = decode(&dsf_bytes).expect("decode"); + for &sample in &dec.channels[0][12..] { + assert!(sample.abs() < 1e-4, "silence sample should be ~0.0, got {sample}"); + } + + // Full positive level + let ones = vec![0xFF; 1024]; + let dsf_ones = encode_dsf(sample_rate, &[&ones], 1024 * 8, 4096).expect("encode"); + let dec_ones = decode(&dsf_ones).expect("decode"); + for &sample in &dec_ones.channels[0][12..] { + assert!((sample - 1.0).abs() < 1e-4, "ones sample should be ~1.0, got {sample}"); + } + + // Full negative level + let zeros = vec![0x00; 1024]; + let dsf_zeros = encode_dsf(sample_rate, &[&zeros], 1024 * 8, 4096).expect("encode"); + let dec_zeros = decode(&dsf_zeros).expect("decode"); + for &sample in &dec_zeros.channels[0][12..] { + assert!((sample - (-1.0)).abs() < 1e-4, "zeros sample should be ~-1.0, got {sample}"); + } +} + +#[test] +fn multichannel_dsf_and_dsdiff() { + let sample_rate = 2_822_400; + // Test 6-channel (5.1 surround) + let channels: Vec> = (0..6).map(|c| make_test_stream(1024, (c * 23 + 5) as u8)).collect(); + let ch_refs: Vec<&[u8]> = channels.iter().map(Vec::as_slice).collect(); + + let dsf = encode_dsf(sample_rate, &ch_refs, 1024 * 8, 512).expect("encode 5.1 dsf"); + let dsf_meta = read_metadata(&dsf).expect("meta 5.1 dsf"); + assert_eq!(dsf_meta.channels, 6); + let dsf_dec = decode(&dsf).expect("decode 5.1 dsf"); + assert_eq!(dsf_dec.channels.len(), 6); + assert_eq!(dsf_dec.channels[0].len(), 1024); + + let dff = encode_dsdiff(sample_rate, &ch_refs, 1024 * 8).expect("encode 5.1 dsdiff"); + let dff_meta = read_metadata(&dff).expect("meta 5.1 dsdiff"); + assert_eq!(dff_meta.channels, 6); + let dff_dec = decode(&dff).expect("decode 5.1 dsdiff"); + assert_eq!(dff_dec.channels.len(), 6); + assert_eq!(dff_dec.channels[0].len(), 1024); +} + +#[test] +fn dst_compression_rejected() { + // Construct a minimal DSDIFF with CMPR = 'DST ' + let mut dff = encode_dsdiff(2_822_400, &[&[0xAA; 64]], 512).expect("encode"); + // Find 'DSD ' in CMPR chunk and replace with 'DST ' + let mut replaced = false; + for i in 0..dff.len().saturating_sub(8) { + if &dff[i..i + 4] == b"CMPR" && &dff[i + 12..i + 16] == b"DSD " { + dff[i + 12..i + 16].copy_from_slice(b"DST "); + replaced = true; + break; + } + } + assert!(replaced, "should find CMPR DSD chunk"); + assert!(read_metadata(&dff).is_err(), "DST compression should be rejected as unsupported"); + assert!(decode(&dff).is_err(), "DST compression should be rejected as unsupported"); +} + +#[test] +fn id3v2_tag_in_dsf() { + let sample_rate = 2_822_400; + let mut dsf = encode_dsf(sample_rate, &[&[0x69; 128]], 1024, 512).expect("encode"); + let metadata_offset = dsf.len() as u64; + + // Append simple ID3v2.3 tag with TIT2="Test Title" and TPE1="Test Artist" + let mut id3 = Vec::new(); + id3.extend_from_slice(b"ID3"); + id3.push(3); // v2.3 + id3.push(0); // revision + id3.push(0); // flags + + let mut frames = Vec::new(); + // TIT2 frame + frames.extend_from_slice(b"TIT2"); + let title_bytes = b"\x03DSD Master"; // UTF-8 + frames.extend_from_slice(&(title_bytes.len() as u32).to_be_bytes()); + frames.extend_from_slice(&[0, 0]); // flags + frames.extend_from_slice(title_bytes); + + // TPE1 frame + frames.extend_from_slice(b"TPE1"); + let artist_bytes = b"\x03The Audiophiles"; + frames.extend_from_slice(&(artist_bytes.len() as u32).to_be_bytes()); + frames.extend_from_slice(&[0, 0]); // flags + frames.extend_from_slice(artist_bytes); + + // synchsafe size + let tag_len = frames.len(); + id3.push(((tag_len >> 21) & 0x7F) as u8); + id3.push(((tag_len >> 14) & 0x7F) as u8); + id3.push(((tag_len >> 7) & 0x7F) as u8); + id3.push((tag_len & 0x7F) as u8); + id3.extend_from_slice(&frames); + + dsf.extend_from_slice(&id3); + // Update file size and metadata_offset of 'DSD ' chunk + let file_size = dsf.len() as u64; + dsf[12..20].copy_from_slice(&file_size.to_le_bytes()); + dsf[20..28].copy_from_slice(&metadata_offset.to_le_bytes()); + + let meta = read_metadata(&dsf).expect("read metadata with ID3"); + assert_eq!(meta.title.as_deref(), Some("DSD Master")); + assert_eq!(meta.artist.as_deref(), Some("The Audiophiles")); +} + +#[test] +fn raw_audio_bit_order_conversion() { + let ch0 = vec![0b00000001, 0b10000000]; + let dsf = encode_dsf(2_822_400, &[&ch0], 16, 512).expect("encode"); + let mut raw = read_raw(&dsf).expect("read raw"); + assert_eq!(raw.bit_order, BitOrder::LsbFirst); + assert_eq!(raw.channel_bytes[0], ch0); + + raw.convert_bit_order(BitOrder::MsbFirst); + assert_eq!(raw.bit_order, BitOrder::MsbFirst); + assert_eq!(raw.channel_bytes[0], vec![0b10000000, 0b00000001]); +} + +#[test] +fn hostile_inputs() { + // Truncated headers + assert!(read_metadata(b"").is_err()); + assert!(read_metadata(b"DSD ").is_err()); + assert!(read_metadata(b"FRM8").is_err()); + + // Bad magic + assert!(read_metadata(b"RIFF\x00\x00\x00\x00WAVE").is_err()); + + // Truncated DSF chunk + let mut bad_dsf = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode"); + bad_dsf.truncate(50); + assert!(decode(&bad_dsf).is_err()); + + // Corrupted fmt chunk size + let mut bad_fmt = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode"); + bad_fmt[32] = 0; // bits_per_sample = 0 + assert!(decode(&bad_fmt).is_err()); + + // Absurd channels + let mut bad_ch = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode"); + bad_ch[28 + 24] = 99; // channel_count = 99 + assert!(decode(&bad_ch).is_err()); +} + +#[test] +fn ffmpeg_dsf_oracle() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("dsd"); + + let sample_rate = 2_822_400; + let block_size = 4096; + let ch0 = make_test_stream(16384, 11); + let ch1 = make_test_stream(16384, 88); + let sample_count = 16384 * 8; + + let dsf_bytes = encode_dsf(sample_rate, &[&ch0, &ch1], sample_count, block_size).expect("encode_dsf"); + let dsf_path = dir.join("test_oracle.dsf"); + std::fs::write(&dsf_path, &dsf_bytes).expect("write fixture"); + + let raw_out_path = dir.join("ffmpeg_dsf.raw"); + let status = Command::new(&ffmpeg).arg("-y").arg("-i").arg(&dsf_path).arg("-f").arg("f32le").arg(&raw_out_path).output().expect("run ffmpeg"); + assert!(status.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&status.stderr)); + + let raw_bytes = std::fs::read(&raw_out_path).expect("read raw"); + let ffmpeg_floats: Vec = raw_bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); + + let decoded = decode(&dsf_bytes).expect("our decode"); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 16384); + assert_eq!(decoded.channels[1].len(), 16384); + + // FFmpeg interleaves L0, R0, L1, R1... + // Compare samples after filter startup (sample 12 onwards). + for i in 12..16000 { + let ff_l = ffmpeg_floats[i * 2]; + let ff_r = ffmpeg_floats[i * 2 + 1]; + let our_l = decoded.channels[0][i]; + let our_r = decoded.channels[1][i]; + + assert!((ff_l - our_l).abs() < 1e-4, "sample {i} left mismatch: ffmpeg={ff_l}, ours={our_l}"); + assert!((ff_r - our_r).abs() < 1e-4, "sample {i} right mismatch: ffmpeg={ff_r}, ours={our_r}"); + } +} + +#[test] +fn ffmpeg_dsdiff_oracle() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("dsd"); + + let sample_rate = 2_822_400; + let ch0 = make_test_stream(8192, 33); + let ch1 = make_test_stream(8192, 77); + let sample_count = 8192 * 8; + + let dff_bytes = encode_dsdiff(sample_rate, &[&ch0, &ch1], sample_count).expect("encode_dsdiff"); + let dff_path = dir.join("test_oracle.dff"); + std::fs::write(&dff_path, &dff_bytes).expect("write fixture"); + + let raw_out_path = dir.join("ffmpeg_dff.raw"); + let status = Command::new(&ffmpeg).arg("-y").arg("-i").arg(&dff_path).arg("-f").arg("f32le").arg(&raw_out_path).output().expect("run ffmpeg"); + assert!(status.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&status.stderr)); + + let raw_bytes = std::fs::read(&raw_out_path).expect("read raw"); + let ffmpeg_floats: Vec = raw_bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); + + let decoded = decode(&dff_bytes).expect("our decode"); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 8192); + + for i in 12..8000 { + let ff_l = ffmpeg_floats[i * 2]; + let ff_r = ffmpeg_floats[i * 2 + 1]; + let our_l = decoded.channels[0][i]; + let our_r = decoded.channels[1][i]; + + assert!((ff_l - our_l).abs() < 1e-4, "sample {i} left mismatch: ffmpeg={ff_l}, ours={our_l}"); + assert!((ff_r - our_r).abs() < 1e-4, "sample {i} right mismatch: ffmpeg={ff_r}, ours={our_r}"); + } +} diff --git a/crates/audio/tests/flac_decode.rs b/crates/audio/tests/flac_decode.rs new file mode 100644 index 000000000..a1895789b --- /dev/null +++ b/crates/audio/tests/flac_decode.rs @@ -0,0 +1,211 @@ +//! The native FLAC decoder: round trips through this crate's encoder over bit depths, channel +//! counts, block sizes and effort levels; hostile input; and ffmpeg as the reference (oracle; +//! skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`) for files +//! ffmpeg's encoder writes at every compression level. + +use craft_audio::flac::{DecodeError, Decoder, Encoder, EncoderConfig, STREAMINFO_OFFSET, StreamInfo, decode}; +use std::process::Command; + +fn signal(channels: usize, frames: usize, bits: u32, seed: u32) -> Vec> { + let max = if bits == 32 { i32::MAX as f64 } else { ((1i64 << (bits - 1)) - 1) as f64 }; + let mut s = seed; + (0..channels) + .map(|c| { + (0..frames) + .map(|i| { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + let t = i as f64; + let v = match (i / 3000) % 4 { + 0 => (t * (0.01 + 0.007 * c as f64)).sin() * 0.6 + (t * 0.31).sin() * 0.1, + 1 => (f64::from(s) / f64::from(u32::MAX) - 0.5) * 1.8, + 2 => 0.0, + _ => { + if (i / 40) % 2 == 0 { + 0.99 + } else { + -0.99 + } + } + }; + (v * max).round() as i32 + }) + .collect() + }) + .collect() +} + +fn encode(channels: &[Vec], rate: u32, bits: u8, block: u16, level: u8) -> Vec { + let mut cfg = EncoderConfig::new(rate, channels.len() as u8, bits); + cfg.block_size = block; + cfg.level = level; + let mut enc = Encoder::new(cfg).expect("encoder"); + let mut file = enc.header(&[]); + let refs: Vec<&[i32]> = channels.iter().map(Vec::as_slice).collect(); + file.extend(enc.encode(&refs).expect("encode")); + file.extend(enc.finish()); + let at = STREAMINFO_OFFSET as usize; + file[at..at + 34].copy_from_slice(&enc.streaminfo()); + file +} + +#[test] +fn round_trips_through_the_encoder() { + for (channels, bits) in [(1usize, 8u8), (2, 8), (1, 12), (2, 16), (2, 20), (3, 24), (6, 24), (8, 16), (2, 32), (1, 32)] { + for (block, level) in [(4096u16, 5u8), (16, 0), (1000, 8), (65535, 3), (576, 1)] { + let frames = 9000 + usize::from(block % 97); + let src = signal(channels, frames, u32::from(bits), 0x1234_5679 + u32::from(bits)); + let file = encode(&src, 44_100, bits, block, level); + let got = decode(&file).unwrap_or_else(|e| panic!("{channels}ch {bits}-bit block {block} level {level}: {e}")); + assert_eq!((got.info.channels as usize, got.info.bits_per_sample, got.info.sample_rate), (channels, bits, 44_100)); + assert_eq!(got.channels, src, "{channels}ch {bits}-bit block {block} level {level}"); + } + } +} + +#[test] +fn frames_decode_one_at_a_time() { + let src = signal(2, 10_000, 16, 7); + let file = encode(&src, 48_000, 16, 4096, 5); + let info = StreamInfo::parse(&file[STREAMINFO_OFFSET as usize..]).expect("streaminfo"); + let dec = Decoder::new(info); + // The first frame follows the metadata blocks; find the first position a frame decodes at. + let at = (42..file.len()).find(|&p| dec.decode_frame(&file[p..]).is_ok()).expect("a frame"); + let first = dec.decode_frame(&file[at..]).expect("frame"); + assert_eq!((first.block_size, first.number, first.sample_rate, first.bits_per_sample), (4096, 0, 48_000, 16)); + assert_eq!(first.channels[0], src[0][..4096]); + // Without the STREAMINFO a frame that spells out its own rate and depth still decodes. + let _ = Decoder::without_streaminfo().decode_frame(&file[at..]); +} + +#[test] +fn hostile_input_is_an_error_not_a_panic() { + let src = signal(2, 6000, 16, 11); + let file = encode(&src, 44_100, 16, 1152, 5); + for n in 0..file.len().min(3000) { + let _ = decode(&file[..n]); + } + // A cut file is truncated, not silently shorter. + assert!(decode(&file[..file.len() - 5]).is_err()); + // Every bit flip in the first frames is caught by a CRC or another check, never a panic. + for i in 0..file.len().min(2500) { + for bit in 0..8 { + let mut c = file.clone(); + c[i] ^= 1 << bit; + let _ = decode(&c); + } + } + // A sample limit stops a stream that claims too much. + assert_eq!(craft_audio::flac::decode_with_limit(&file, 1000), Err(DecodeError::TooLarge)); + assert!(decode(b"nope").is_err()); + assert!(decode(b"fLaC").is_err()); +} + +// ---- ffmpeg ---- + +/// Little-endian 16- or 32-bit samples of raw PCM. +fn pcm_values(raw: &[u8], bytes: usize) -> Vec { + if bytes == 2 { + raw.as_chunks::<2>().0.iter().map(|b| i32::from(i16::from_le_bytes(*b))).collect() + } else { + raw.as_chunks::<4>().0.iter().map(|b| i32::from_le_bytes(*b)).collect() + } +} + +/// Planar channels as interleaved samples. +fn interleave(channels: &[Vec]) -> Vec { + let frames = channels.first().map_or(0, Vec::len); + (0..frames).flat_map(|i| channels.iter().map(move |c| c[i])).collect() +} + +fn ffmpeg_run(ff: &std::path::Path, args: &[&str]) -> Vec { + let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); + out.stdout +} + +#[test] +fn ffmpeg_files_decode_to_ffmpegs_samples() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("flac_decode"); + let tones = "aevalsrc=exprs=0.4*sin(2*PI*441*t)+0.2*sin(2*PI*3100*t)|0.3*sin(2*PI*660*t)*sin(2*PI*3*t):s=44100:d=1.3"; + let noise = "anoisesrc=d=1.3:c=white:r=44100:a=0.5:s=3"; + for (src, name) in [(tones, "tones"), (noise, "noise")] { + for channels in [1usize, 2, 6] { + for (fmt, bytes, bits) in [("s16", 2usize, 16u32), ("s32", 4, 24)] { + for level in [0, 3, 5, 8, 12] { + let file = dir.join(format!("ffmpeg_{name}_{channels}ch_{bits}_l{level}.flac")); + let f = file.to_str().expect("path"); + let (ch, lv) = (channels.to_string(), level.to_string()); + ffmpeg_run(&ff, &["-f", "lavfi", "-i", src, "-ac", &ch, "-sample_fmt", fmt, "-compression_level", &lv, "-c:a", "flac", f]); + let theirs = ffmpeg_run(&ff, &["-i", f, "-f", if bits == 16 { "s16le" } else { "s32le" }, "-"]); + let got = + decode(&std::fs::read(&file).expect("read")).unwrap_or_else(|e| panic!("{name} {channels}ch {bits}-bit level {level}: {e}")); + assert_eq!(got.info.channels as usize, channels); + let frames = got.channels[0].len(); + assert_eq!(theirs.len(), frames * channels * bytes, "{name} {channels}ch {bits} l{level}: length"); + // ffmpeg returns 24-bit audio left-aligned in 32 bits. + let shift = if bits == 24 { 8 } else { 0 }; + let mine: Vec = interleave(&got.channels).into_iter().map(|v| v << shift).collect(); + let ok = mine == pcm_values(&theirs, bytes); + assert!(ok, "{name} {channels}ch {bits}-bit level {level}: samples differ from ffmpeg's decode"); + } + } + } + } +} + +#[test] +fn ffmpeg_decodes_our_files_to_our_samples() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("flac_decode"); + for (channels, bits) in [(1usize, 16u8), (2, 16), (2, 24), (6, 16)] { + let src = signal(channels, 20_000, u32::from(bits), 99); + let file = dir.join(format!("ours_{channels}ch_{bits}.flac")); + std::fs::write(&file, encode(&src, 44_100, bits, 4096, 5)).expect("write"); + let theirs = ffmpeg_run(&ff, &["-i", file.to_str().expect("path"), "-f", if bits == 16 { "s16le" } else { "s32le" }, "-"]); + let got = decode(&std::fs::read(&file).expect("read")).expect("decode"); + let bytes = if bits == 16 { 2 } else { 4 }; + let shift = if bytes == 4 { 8 } else { 0 }; + let want: Vec = pcm_values(&theirs, bytes).into_iter().map(|v| v >> shift).collect(); + assert!(interleave(&got.channels) == want, "{channels}ch {bits}-bit: samples differ from ffmpeg's decode"); + } +} + +#[test] +fn rejects_unknown_length_corruption_and_streaminfo_format_mismatch() { + let src = signal(1, 100, 16, 7); + let original = encode(&src, 44_100, 16, 4096, 5); + let at = STREAMINFO_OFFSET as usize; + // STREAMINFO is not CRC-covered. Clear only the 36-bit total sample count. + let mut unknown = original.clone(); + unknown[at + 13] &= 0xf0; + unknown[at + 14..at + 18].fill(0); + assert_eq!(decode(&unknown).unwrap().channels, src); + for tail in [vec![0xff], vec![0x00, 0x00]] { + let mut broken = unknown.clone(); + broken.extend(tail); + assert!(decode(&broken).is_err()); + } + // The encoder spells these in frame headers, independent of STREAMINFO. + let mut wrong_rate = original.clone(); + let mut packed = u64::from_be_bytes(wrong_rate[at + 10..at + 18].try_into().unwrap()); + packed = (packed & ((1u64 << 44) - 1)) | (48_000u64 << 44); + wrong_rate[at + 10..at + 18].copy_from_slice(&packed.to_be_bytes()); + assert!(decode(&wrong_rate).is_err()); + let mut wrong_depth = original; + wrong_depth[at + 12] = (wrong_depth[at + 12] & !1) | 1; + wrong_depth[at + 13] = (wrong_depth[at + 13] & 0x0f) | 0x70; + assert!(decode(&wrong_depth).is_err()); +} + +#[test] +fn caller_constructed_streaminfo_is_validated_before_decoding() { + let file = encode(&signal(1, 100, 16, 9), 44_100, 16, 4096, 5); + let info = StreamInfo::parse(&file[STREAMINFO_OFFSET as usize..]).unwrap(); + for bits in [0, 1, 3, 33, 64, 255] { + let invalid = StreamInfo { bits_per_sample: bits, ..info }; + assert!(matches!(Decoder::new(invalid).decode_frame(&[]), Err(DecodeError::Invalid(_)))); + } +} diff --git a/crates/audio/tests/g722_oracle.rs b/crates/audio/tests/g722_oracle.rs new file mode 100644 index 000000000..3da059011 --- /dev/null +++ b/crates/audio/tests/g722_oracle.rs @@ -0,0 +1,201 @@ +//! ITU-T G.722 SB-ADPCM tests and FFmpeg oracle comparisons. +//! +//! Skipped when FFmpeg is not found, unless `CRAFT_MEDIA_REQUIRE_ORACLES=1` is set. + +use craft_audio::g722::{Decoder, Encoder, Error, decode, decode_interleaved, encode, encode_interleaved}; +use std::process::Command; + +fn generate_signal(samples: usize, freq: f64) -> Vec { + (0..samples) + .map(|i| { + let t = i as f64 / 16000.0; + let val = (2.0 * std::f64::consts::PI * freq * t).sin() * 10000.0; + val as i16 + }) + .collect() +} + +#[test] +fn test_silence_roundtrip() { + let pcm = vec![0i16; 640]; + let encoded = encode(&pcm).expect("encode"); + assert_eq!(encoded.len(), 320); + let decoded = decode(&encoded).expect("decode"); + assert_eq!(decoded.len(), 640); + for &s in &decoded[40..] { + assert!(s.abs() <= 6, "silence sample out of bounds: {s}"); + } +} + +#[test] +fn test_sine_wave_roundtrip_fidelity() { + let pcm = generate_signal(1600, 1000.0); + let encoded = encode(&pcm).expect("encode"); + let decoded = decode(&encoded).expect("decode"); + assert_eq!(decoded.len(), pcm.len()); + + // Compute normalized cross-correlation accounting for filter group delay (approx 22 samples) + let delay = 22; + let mut num = 0.0; + let mut den_orig = 0.0; + let mut den_dec = 0.0; + for i in 0..(pcm.len() - delay) { + let o = pcm[i] as f64; + let d = decoded[i + delay] as f64; + num += o * d; + den_orig += o * o; + den_dec += d * d; + } + let corr = num / (den_orig.sqrt() * den_dec.sqrt()); + assert!(corr > 0.98, "reconstructed sine wave correlation too low: {corr}"); +} + +#[test] +fn test_stereo_multichannel_roundtrip() { + let left = generate_signal(800, 440.0); + let right = generate_signal(800, 880.0); + let mut interleaved = Vec::with_capacity(1600); + for i in 0..800 { + interleaved.push(left[i]); + interleaved.push(right[i]); + } + let encoded = encode_interleaved(&interleaved, 2).expect("encode stereo"); + assert_eq!(encoded.len(), 800); + let decoded = decode_interleaved(&encoded, 2).expect("decode stereo"); + assert_eq!(decoded.len(), 1600); +} + +#[test] +fn test_hostile_inputs_do_not_crash() { + let garbage = [0xFF, 0x00, 0xAA, 0x55, 0x12, 0x34, 0x89, 0xFE]; + let decoded = decode(&garbage).expect("decode garbage"); + assert_eq!(decoded.len(), 16); + + assert_eq!(encode(&[1, 2, 3]), Err(Error::OddSampleCount(3))); + assert_eq!(decode_interleaved(&[0; 8], 0), Err(Error::InvalidChannels(0))); + assert_eq!(decode_interleaved(&[0; 8], 9), Err(Error::InvalidChannels(9))); +} + +#[test] +fn test_encoder_and_decoder_reset() { + let mut enc = Encoder::new(); + let mut dec = Decoder::new(); + let pcm = generate_signal(200, 1000.0); + + let mut out1 = Vec::new(); + enc.encode(&pcm, &mut out1).expect("enc 1"); + let mut dec1 = Vec::new(); + dec.decode(&out1, &mut dec1).expect("dec 1"); + + enc.reset(); + dec.reset(); + + let mut out2 = Vec::new(); + enc.encode(&pcm, &mut out2).expect("enc 2"); + let mut dec2 = Vec::new(); + dec.decode(&out2, &mut dec2).expect("dec 2"); + + assert_eq!(out1, out2); + assert_eq!(dec1, dec2); +} + +#[test] +fn test_ffmpeg_g722_oracle_encoder_and_decoder() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("g722_oracle"); + + // 1. Generate test 1000 Hz tone at 16 kHz mono (800 samples = 0.05s) + let pcm = generate_signal(800, 1000.0); + let pcm_path = dir.join("input.s16le"); + let mut pcm_bytes = Vec::with_capacity(pcm.len() * 2); + for &s in &pcm { + pcm_bytes.extend_from_slice(&s.to_le_bytes()); + } + std::fs::write(&pcm_path, &pcm_bytes).expect("write pcm"); + + // 2. FFmpeg encodes the PCM to G.722 + let ff_g722_path = dir.join("ffmpeg.g722"); + let out = Command::new(&ff) + .args(["-y", "-f", "s16le", "-ar", "16000", "-ac", "1", "-i"]) + .arg(&pcm_path) + .args(["-f", "g722"]) + .arg(&ff_g722_path) + .output() + .expect("ffmpeg encode"); + assert!(out.status.success(), "ffmpeg encode failed: {}", String::from_utf8_lossy(&out.stderr)); + let ff_g722_bytes = std::fs::read(&ff_g722_path).expect("read ff g722"); + + // 3. FFmpeg decodes its own G.722 back to PCM + let ff_pcm_back_path = dir.join("ff_back.s16le"); + let out = Command::new(&ff) + .args(["-y", "-f", "g722", "-i"]) + .arg(&ff_g722_path) + .args(["-f", "s16le", "-ar", "16000", "-ac", "1"]) + .arg(&ff_pcm_back_path) + .output() + .expect("ffmpeg decode"); + assert!(out.status.success(), "ffmpeg decode failed: {}", String::from_utf8_lossy(&out.stderr)); + let ff_back_bytes = std::fs::read(&ff_pcm_back_path).expect("read ff back pcm"); + let ff_back_samples: Vec = ff_back_bytes.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect(); + + // 4. Our decoder decodes FFmpeg's G.722 stream + let our_decoded_from_ff = decode(&ff_g722_bytes).expect("our decode of ff stream"); + assert_eq!(our_decoded_from_ff.len(), ff_back_samples.len()); + + // Verify sample-by-sample match against FFmpeg decoder: within ±1 LSB tolerance + let mut max_diff: i32 = 0; + for (i, (&ours, &theirs)) in our_decoded_from_ff.iter().zip(&ff_back_samples).enumerate() { + let diff = (ours as i32 - theirs as i32).abs(); + if diff > max_diff { + max_diff = diff; + } + assert!(diff <= 1, "sample {i} mismatch between our decoder and FFmpeg decoder: ours {ours}, theirs {theirs}"); + } + assert!(max_diff <= 1, "max diff {max_diff} exceeded tolerance"); + + // 5. Our encoder encodes the PCM to G.722 + let our_encoded_bytes = encode(&pcm).expect("our encode"); + let our_g722_path = dir.join("ours.g722"); + std::fs::write(&our_g722_path, &our_encoded_bytes).expect("write our g722"); + + // 6. FFmpeg decodes our encoded G.722 stream + let our_decoded_by_ff_path = dir.join("our_by_ff.s16le"); + let out = Command::new(&ff) + .args(["-y", "-f", "g722", "-i"]) + .arg(&our_g722_path) + .args(["-f", "s16le", "-ar", "16000", "-ac", "1"]) + .arg(&our_decoded_by_ff_path) + .output() + .expect("ffmpeg decode of our stream"); + assert!(out.status.success(), "ffmpeg decode of our stream failed: {}", String::from_utf8_lossy(&out.stderr)); + let our_by_ff_bytes = std::fs::read(&our_decoded_by_ff_path).expect("read our by ff pcm"); + let our_by_ff_samples: Vec = our_by_ff_bytes.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect(); + + // Verify that our decoder and FFmpeg decoder produce identical samples on our stream + let our_decoded_from_ours = decode(&our_encoded_bytes).expect("our decode of our stream"); + assert_eq!(our_decoded_from_ours.len(), our_by_ff_samples.len()); + let mut max_diff_ours: i32 = 0; + for (i, (&ours, &theirs)) in our_decoded_from_ours.iter().zip(&our_by_ff_samples).enumerate() { + let diff = (ours as i32 - theirs as i32).abs(); + if diff > max_diff_ours { + max_diff_ours = diff; + } + assert!(diff <= 1, "sample {i} on our stream mismatch between our decoder and FFmpeg decoder: ours {ours}, theirs {theirs}"); + } + assert!(max_diff_ours <= 1, "max diff {max_diff_ours} exceeded tolerance"); + + // Also check high fidelity correlation of our stream decoded by FFmpeg to original signal + let delay = 22; + let mut num = 0.0; + let mut den_orig = 0.0; + let mut den_dec = 0.0; + for i in 0..(pcm.len() - delay) { + let o = pcm[i] as f64; + let d = our_by_ff_samples[i + delay] as f64; + num += o * d; + den_orig += o * o; + den_dec += d * d; + } + let corr = num / (den_orig.sqrt() * den_dec.sqrt()); + assert!(corr > 0.98, "correlation of our encoded stream decoded by FFmpeg is too low: {corr}"); +} diff --git a/crates/audio/tests/g726_oracle.rs b/crates/audio/tests/g726_oracle.rs new file mode 100644 index 000000000..ec875e2c4 --- /dev/null +++ b/crates/audio/tests/g726_oracle.rs @@ -0,0 +1,218 @@ +#![cfg(feature = "g726")] + +use craft_audio::g726::{BitPacking, BitRate, Decoder, Encoder, decode, decode_interleaved, encode, encode_interleaved}; +use std::process::Command; + +fn pearson_correlation(x: &[i16], y: &[i16]) -> f64 { + let n = x.len().min(y.len()); + if n == 0 { + return 0.0; + } + let x = &x[..n]; + let y = &y[..n]; + let mean_x = x.iter().map(|&v| v as f64).sum::() / (n as f64); + let mean_y = y.iter().map(|&v| v as f64).sum::() / (n as f64); + let mut num = 0.0; + let mut denom_x = 0.0; + let mut denom_y = 0.0; + for (&a, &b) in x.iter().zip(y) { + let da = (a as f64) - mean_x; + let db = (b as f64) - mean_y; + num += da * db; + denom_x += da * da; + denom_y += db * db; + } + let denom = (denom_x * denom_y).sqrt(); + if denom > 0.0 { num / denom } else { 0.0 } +} + +fn find_ffmpeg() -> Option { + for cmd in ["ffmpeg", "/opt/homebrew/bin/ffmpeg", "/usr/bin/ffmpeg"] { + if Command::new(cmd).arg("-version").output().is_ok() { + return Some(cmd.to_string()); + } + } + None +} + +#[test] +fn test_silence_roundtrip() { + let pcm = vec![0i16; 80]; + for rate in [BitRate::Rate16k, BitRate::Rate24k, BitRate::Rate32k, BitRate::Rate40k] { + for packing in [BitPacking::BigEndian, BitPacking::LittleEndian] { + let enc = encode(&pcm, rate, packing).expect("encode"); + let dec = decode(&enc, rate, packing).expect("decode"); + assert_eq!(dec.len(), pcm.len()); + for &s in &dec { + assert!(s.abs() <= 16, "silence sample too large: {s}"); + } + } + } +} + +#[test] +fn test_sine_wave_roundtrip_fidelity() { + let sample_rate = 8000.0; + let freq = 300.0; + let num_samples = 160; + let mut pcm = Vec::with_capacity(num_samples); + for i in 0..num_samples { + let t = i as f64 / sample_rate; + let s = (4000.0 * (2.0 * std::f64::consts::PI * freq * t).sin()) as i16; + pcm.push(s); + } + + for rate in [BitRate::Rate16k, BitRate::Rate24k, BitRate::Rate32k, BitRate::Rate40k] { + for packing in [BitPacking::BigEndian, BitPacking::LittleEndian] { + let enc = encode(&pcm, rate, packing).expect("encode sine"); + let dec = decode(&enc, rate, packing).expect("decode sine"); + let corr = pearson_correlation(&pcm, &dec); + assert!(corr > 0.90, "correlation {corr} too low for rate {rate:?} packing {packing:?}"); + } + } +} + +#[test] +fn test_encoder_and_decoder_reset() { + let mut enc = Encoder::new(BitRate::Rate32k, BitPacking::BigEndian); + let mut dec = Decoder::new(BitRate::Rate32k, BitPacking::BigEndian); + + let pcm = vec![1000i16, 2000, 3000, 2000, 1000, 0, -1000, -2000]; + let mut out1 = Vec::new(); + enc.encode(&pcm, &mut out1).expect("enc 1"); + enc.flush(&mut out1).expect("flush 1"); + + let mut dec_pcm1 = Vec::new(); + dec.decode(&out1, &mut dec_pcm1).expect("dec 1"); + + enc.reset(); + dec.reset(); + + let mut out2 = Vec::new(); + enc.encode(&pcm, &mut out2).expect("enc 2"); + enc.flush(&mut out2).expect("flush 2"); + + let mut dec_pcm2 = Vec::new(); + dec.decode(&out2, &mut dec_pcm2).expect("dec 2"); + + assert_eq!(out1, out2); + assert_eq!(dec_pcm1, dec_pcm2); +} + +#[test] +fn test_stereo_multichannel_roundtrip() { + let mut stereo_pcm = Vec::new(); + for i in 0..160 { + let left = (3000.0 * (i as f64 * 0.05).sin()) as i16; + let right = (2000.0 * (i as f64 * 0.03).cos()) as i16; + stereo_pcm.push(left); + stereo_pcm.push(right); + } + + let enc = encode_interleaved(&stereo_pcm, 2, BitRate::Rate32k, BitPacking::BigEndian).expect("encode stereo"); + let dec = decode_interleaved(&enc, 2, BitRate::Rate32k, BitPacking::BigEndian).expect("decode stereo"); + + assert_eq!(dec.len(), stereo_pcm.len()); + let corr = pearson_correlation(&stereo_pcm, &dec); + assert!(corr > 0.90, "stereo correlation {corr} too low"); +} + +#[test] +fn test_hostile_inputs_do_not_crash() { + let mut dec = Decoder::new(BitRate::Rate32k, BitPacking::BigEndian); + let mut out = Vec::new(); + let hostile = vec![0xEE; 1000]; + let _ = dec.decode(&hostile, &mut out); + + let mut enc = Encoder::new(BitRate::Rate40k, BitPacking::LittleEndian); + let mut out_enc = Vec::new(); + let hostile_pcm = vec![i16::MIN, i16::MAX, -1, 1, 0]; + let _ = enc.encode(&hostile_pcm, &mut out_enc); + let _ = enc.flush(&mut out_enc); +} + +#[test] +fn test_ffmpeg_g726_oracle_encoder_and_decoder() { + let ff = match find_ffmpeg() { + Some(f) => f, + None => return, + }; + + let sample_rate = 8000; + let num_samples = 240; + let mut pcm = Vec::with_capacity(num_samples); + for i in 0..num_samples { + let t = i as f64 / sample_rate as f64; + let s = (5000.0 * (2.0 * std::f64::consts::PI * 350.0 * t).sin()) as i16; + pcm.push(s); + } + + let dir = std::env::temp_dir().join("craft_g726_oracle"); + let _ = std::fs::create_dir_all(&dir); + let in_pcm_path = dir.join("input.s16le"); + let mut in_bytes = Vec::with_capacity(pcm.len() * 2); + for &s in &pcm { + in_bytes.extend_from_slice(&s.to_le_bytes()); + } + std::fs::write(&in_pcm_path, &in_bytes).expect("write input pcm"); + + for rate in [BitRate::Rate16k, BitRate::Rate24k, BitRate::Rate32k, BitRate::Rate40k] { + for (packing, ff_codec, ff_fmt) in [(BitPacking::BigEndian, "g726", "g726"), (BitPacking::LittleEndian, "g726le", "g726le")] { + let cs = rate.code_size(); + let ff_g726_path = dir.join(format!("ff_{}_{}.g726", cs, ff_codec)); + + // 1. FFmpeg encodes PCM to G.726 + let out = Command::new(&ff) + .args(["-y", "-f", "s16le", "-ar", "8000", "-ac", "1", "-i"]) + .arg(&in_pcm_path) + .args(["-c:a", ff_codec, "-code_size", &cs.to_string(), "-f", ff_fmt]) + .arg(&ff_g726_path) + .output() + .expect("ffmpeg encode"); + assert!(out.status.success(), "ffmpeg encode failed: {}", String::from_utf8_lossy(&out.stderr)); + let ff_g726_bytes = std::fs::read(&ff_g726_path).expect("read ff g726"); + + // 2. FFmpeg decodes its own G.726 stream + let ff_pcm_back_path = dir.join(format!("ff_back_{}_{}.s16le", cs, ff_codec)); + let out = Command::new(&ff) + .args(["-y", "-f", ff_fmt, "-code_size", &cs.to_string(), "-i"]) + .arg(&ff_g726_path) + .args(["-f", "s16le", "-ar", "8000", "-ac", "1"]) + .arg(&ff_pcm_back_path) + .output() + .expect("ffmpeg decode"); + assert!(out.status.success(), "ffmpeg decode failed: {}", String::from_utf8_lossy(&out.stderr)); + let ff_back_bytes = std::fs::read(&ff_pcm_back_path).expect("read ff back pcm"); + let ff_back_samples: Vec = ff_back_bytes.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect(); + + // 3. Our decoder decodes FFmpeg's stream + let our_decoded = decode(&ff_g726_bytes, rate, packing).expect("our decode"); + let corr = pearson_correlation(&our_decoded, &ff_back_samples); + assert!(corr > 0.998, "correlation {corr} too low between our decoder and FFmpeg decoder for rate {rate:?} packing {packing:?}"); + + // 4. Our encoder encodes PCM to G.726 + let our_g726_bytes = encode(&pcm, rate, packing).expect("our encode"); + let our_g726_path = dir.join(format!("our_{}_{}.g726", cs, ff_codec)); + std::fs::write(&our_g726_path, &our_g726_bytes).expect("write our g726"); + + // 5. FFmpeg decodes our encoded stream + let our_decoded_by_ff_path = dir.join(format!("our_by_ff_{}_{}.s16le", cs, ff_codec)); + let out = Command::new(&ff) + .args(["-y", "-f", ff_fmt, "-code_size", &cs.to_string(), "-i"]) + .arg(&our_g726_path) + .args(["-f", "s16le", "-ar", "8000", "-ac", "1"]) + .arg(&our_decoded_by_ff_path) + .output() + .expect("ffmpeg decode of our stream"); + assert!(out.status.success(), "ffmpeg decode of our stream failed: {}", String::from_utf8_lossy(&out.stderr)); + let our_by_ff_bytes = std::fs::read(&our_decoded_by_ff_path).expect("read our by ff pcm"); + let our_by_ff_samples: Vec = our_by_ff_bytes.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect(); + + let corr_input = pearson_correlation(&pcm, &our_by_ff_samples); + assert!( + corr_input > 0.90, + "correlation {corr_input} too low for input vs FFmpeg-decoded our stream for rate {rate:?} packing {packing:?}" + ); + } + } +} diff --git a/crates/audio/tests/gsm_oracle.rs b/crates/audio/tests/gsm_oracle.rs new file mode 100644 index 000000000..ec9c2f799 --- /dev/null +++ b/crates/audio/tests/gsm_oracle.rs @@ -0,0 +1,138 @@ +//! GSM 06.10 against ffmpeg's decoder as the reference (oracle; skipped when ffmpeg is absent, a +//! failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`): ffmpeg decodes what our encoder writes, in both +//! packings, to exactly the samples our decoder returns, and so does arbitrary frame data. + +use craft_audio::gsm::{Packing, decode, encode}; +use std::path::Path; +use std::process::Command; + +fn xorshift(seed: &mut u32) -> u32 { + *seed ^= *seed << 13; + *seed ^= *seed >> 17; + *seed ^= *seed << 5; + *seed +} + +fn signal(frames: usize) -> Vec { + let mut seed = 0x9E37_79B9u32; + (0..frames * 160) + .map(|i| { + let t = i as f64 / 8000.0; + let f0 = 110.0 + 40.0 * (t * 2.0).sin(); + let voiced = (t * f0 * std::f64::consts::TAU).sin() * 7000.0 + (t * 4.0 * f0 * std::f64::consts::TAU).sin() * 2000.0; + let noise = f64::from(xorshift(&mut seed) % 3000) - 1500.0; + // Voiced stretches, noise bursts, silence and full-scale clipping. + match (i / 1600) % 5 { + 0 | 1 => voiced as i16, + 2 => noise as i16, + 3 => 0, + _ => (voiced * 6.0).clamp(-32768.0, 32767.0) as i16, + } + }) + .collect() +} + +fn wav49_file(blocks: &[u8], samples: usize) -> Vec { + let mut fmt = Vec::new(); + fmt.extend_from_slice(&0x31u16.to_le_bytes()); // GSM 6.10 + fmt.extend_from_slice(&1u16.to_le_bytes()); + fmt.extend_from_slice(&8000u32.to_le_bytes()); + fmt.extend_from_slice(&1625u32.to_le_bytes()); + fmt.extend_from_slice(&65u16.to_le_bytes()); + fmt.extend_from_slice(&0u16.to_le_bytes()); + fmt.extend_from_slice(&2u16.to_le_bytes()); + fmt.extend_from_slice(&320u16.to_le_bytes()); + let mut body = b"WAVE".to_vec(); + body.extend_from_slice(b"fmt "); + body.extend_from_slice(&(fmt.len() as u32).to_le_bytes()); + body.extend_from_slice(&fmt); + body.extend_from_slice(b"fact"); + body.extend_from_slice(&4u32.to_le_bytes()); + body.extend_from_slice(&(samples as u32).to_le_bytes()); + body.extend_from_slice(b"data"); + body.extend_from_slice(&(blocks.len() as u32).to_le_bytes()); + body.extend_from_slice(blocks); + let mut out = b"RIFF".to_vec(); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(&body); + out +} + +fn ffmpeg_decode(ffmpeg: &Path, file: &Path, forced_format: Option<&str>) -> Vec { + let mut cmd = Command::new(ffmpeg); + cmd.args(["-v", "error", "-y"]); + if let Some(f) = forced_format { + cmd.args(["-f", f]); + } + let out = cmd.arg("-i").arg(file).args(["-f", "s16le", "-acodec", "pcm_s16le", "-"]).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg failed on {}: {}", file.display(), String::from_utf8_lossy(&out.stderr)); + out.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect() +} + +/// Frames whose long-term and RPE fields are arbitrary, over the log-area ratios of real speech. +/// Random log-area ratios give filters that overflow at every sample, where the specification's +/// saturating arithmetic and other decoders' differ; here every field of every sub-frame still +/// takes all of its values, with the amplitude and gain kept where the signal stays in range. +fn random_frames(n: usize, seed: &mut u32) -> Vec { + let speech = encode(&signal(n), Packing::Raw); + let mut out = Vec::new(); + for b in speech.as_chunks::<33>().0 { + let mut frame = craft_audio::gsm::Frame::from_raw(b).expect("frame"); + for s in &mut frame.sub { + s.lag = 40 + (xorshift(seed) % 81) as u8; + s.gain = (xorshift(seed) % 3) as u8; + s.grid = (xorshift(seed) & 3) as u8; + s.xmax = (xorshift(seed) % 26) as u8; + for p in &mut s.pulses { + *p = (xorshift(seed) & 7) as u8; + } + } + out.extend_from_slice(&frame.to_raw()); + } + out +} + +#[test] +fn ffmpeg_decodes_our_raw_streams_to_the_same_samples() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("gsm"); + for frames in [1usize, 2, 7, 50, 120] { + let bytes = encode(&signal(frames), Packing::Raw); + let file = dir.join(format!("ours_{frames}.gsm")); + std::fs::write(&file, &bytes).expect("write fixture"); + let theirs = ffmpeg_decode(&ffmpeg, &file, Some("gsm")); + let ours = decode(&bytes, Packing::Raw).expect("decode"); + assert_eq!(theirs.len(), ours.len(), "{frames} frames: sample count"); + assert!(theirs == ours, "{frames} frames: samples differ"); + } +} + +#[test] +fn ffmpeg_decodes_our_wav49_streams_to_the_same_samples() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("gsm"); + for frames in [2usize, 4, 20, 100] { + let pcm = signal(frames); + let bytes = encode(&pcm, Packing::Wav49); + let file = dir.join(format!("ours_{frames}.wav")); + std::fs::write(&file, wav49_file(&bytes, pcm.len())).expect("write fixture"); + let theirs = ffmpeg_decode(&ffmpeg, &file, None); + let ours = decode(&bytes, Packing::Wav49).expect("decode"); + assert_eq!(theirs.len(), ours.len(), "{frames} frames: sample count"); + assert!(theirs == ours, "{frames} frames: samples differ"); + } +} + +#[test] +fn ffmpeg_and_we_decode_arbitrary_frames_identically() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("gsm"); + let mut seed = 0xC0FF_EE11u32; + let bytes = random_frames(300, &mut seed); + let file = dir.join("random.gsm"); + std::fs::write(&file, &bytes).expect("write fixture"); + let theirs = ffmpeg_decode(&ffmpeg, &file, Some("gsm")); + let ours = decode(&bytes, Packing::Raw).expect("decode"); + assert_eq!(theirs.len(), ours.len()); + assert!(theirs == ours, "arbitrary frames decode differently"); +} diff --git a/crates/audio/tests/mp2_encoder_oracle.rs b/crates/audio/tests/mp2_encoder_oracle.rs new file mode 100644 index 000000000..ca4d15bd3 --- /dev/null +++ b/crates/audio/tests/mp2_encoder_oracle.rs @@ -0,0 +1,228 @@ +//! The Layer II encoder (feature `mpa-encode`): every frame has the header and size its settings +//! give and decodes with our decoder; ffmpeg as an external decoder (skipped without ffmpeg, a +//! failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`) decodes the stream without a complaint, to the +//! right length, and its output, aligned by [`DELAY`], matches the input within a signal-to-noise +//! ratio per bit rate. The bounds sit well under what the encoder reaches today; white noise loses +//! the subbands above the table's last one (a sixth of it at 48 kHz), so its bound is low. + +use std::path::Path; +use std::process::{Command, Stdio}; + +use craft_audio::mpa::encoder::{Config, DELAY, EncodeError, Encoder, bitrates, nearest_bitrate}; +use craft_audio::mpa::{Decoder, Mode, Version, parse_header}; + +fn chords(rate: u32, n: usize, detune: f32) -> Vec { + let f = [220.0, 277.18, 329.63, 440.0, 1318.5, 3520.0]; + let a = [0.2, 0.15, 0.12, 0.1, 0.05, 0.02]; + (0..n) + .map(|i| { + let t = i as f32 / rate as f32; + f.iter().zip(a).map(|(f, a)| a * (2.0 * std::f32::consts::PI * f * (1.0 + detune) * t).sin()).sum::() + }) + .collect() +} + +fn noise(n: usize, amp: f32, seed: u64) -> Vec { + let mut s = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + (0..n) + .map(|_| { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + ((s >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * amp + }) + .collect() +} + +fn encode(cfg: Config, input: &[Vec], chunk: usize) -> Vec { + let mut enc = Encoder::new(cfg).expect("encoder"); + let mut out = Vec::new(); + let n = input[0].len(); + let mut pos = 0; + while pos < n { + let end = (pos + chunk).min(n); + let planes: Vec<&[f32]> = input.iter().map(|c| &c[pos..end]).collect(); + out.extend(enc.encode(&planes)); + pos = end; + } + out.extend(enc.flush()); + out +} + +/// Split a stream into frames by its headers; every header must be one the settings give. +fn frames<'a>(bytes: &'a [u8], cfg: &Config) -> Vec<&'a [u8]> { + let mut out = Vec::new(); + let mut pos = 0; + while pos < bytes.len() { + let h = parse_header(&bytes[pos..]).unwrap_or_else(|e| panic!("frame {} at byte {pos}: {e}", out.len())); + assert_eq!(h.layer, 2); + assert_eq!(h.version, if cfg.sample_rate >= 32_000 { Version::Mpeg1 } else { Version::Mpeg2 }); + assert_eq!((h.sample_rate, h.bitrate_kbps), (cfg.sample_rate, cfg.bitrate_kbps)); + assert_eq!(h.mode, if cfg.channels == 1 { Mode::Mono } else { Mode::Stereo }); + assert!(!h.crc); + out.push(&bytes[pos..pos + h.frame_bytes]); + pos += h.frame_bytes; + } + assert_eq!(pos, bytes.len(), "the stream ends on a frame boundary"); + out +} + +fn snr(input: &[f32], dec: &[f32]) -> f64 { + let (mut s, mut n) = (0f64, 0f64); + for (a, b) in input.iter().zip(dec) { + s += f64::from(*a) * f64::from(*a); + n += f64::from(a - b) * f64::from(a - b); + } + 10.0 * (s / n.max(1e-30)).log10() +} + +struct Case { + name: &'static str, + rate: u32, + channels: usize, + kbps: u32, + signal: fn(u32, usize, usize) -> Vec, + min_snr: f64, +} + +fn sig_chords(rate: u32, n: usize, c: usize) -> Vec { + chords(rate, n, 0.003 * c as f32) +} +fn sig_noise(_rate: u32, n: usize, c: usize) -> Vec { + noise(n, 0.25, 11 + c as u64) +} + +const CASES: &[Case] = &[ + Case { name: "chords", rate: 48_000, channels: 2, kbps: 192, signal: sig_chords, min_snr: 30.0 }, + Case { name: "chords", rate: 44_100, channels: 2, kbps: 128, signal: sig_chords, min_snr: 25.0 }, + Case { name: "chords", rate: 44_100, channels: 1, kbps: 64, signal: sig_chords, min_snr: 25.0 }, + Case { name: "chords", rate: 32_000, channels: 2, kbps: 96, signal: sig_chords, min_snr: 20.0 }, + Case { name: "chords", rate: 22_050, channels: 2, kbps: 64, signal: sig_chords, min_snr: 20.0 }, + Case { name: "chords", rate: 24_000, channels: 1, kbps: 32, signal: sig_chords, min_snr: 18.0 }, + Case { name: "noise", rate: 48_000, channels: 2, kbps: 384, signal: sig_noise, min_snr: 4.0 }, + Case { name: "noise", rate: 44_100, channels: 2, kbps: 256, signal: sig_noise, min_snr: 4.0 }, +]; + +fn inputs(c: &Case, n: usize) -> Vec> { + (0..c.channels).map(|ch| (c.signal)(c.rate, n, ch)).collect() +} + +#[test] +fn frames_have_the_size_and_header_their_settings_give_and_decode_with_our_decoder() { + for c in CASES { + let n = c.rate as usize * 2 + 777; + let cfg = Config::cbr(c.rate, c.channels, c.kbps); + let bytes = encode(cfg, &inputs(c, n), 1000); + let frames = frames(&bytes, &cfg); + // every input sample and the filter delay fit in the frames, and no more than one frame more + let covered = frames.len() * 1152; + assert!(covered >= n + DELAY as usize && covered < n + DELAY as usize + 1152, "{}: {} frames for {n} samples", c.name, frames.len()); + // 144 kbit/s-slots per frame, the padding slots adding up to the exact rate + let nominal = f64::from(c.kbps) * 125.0 * covered as f64 / f64::from(c.rate); + assert!((bytes.len() as f64 - nominal).abs() < 1.0 + f64::from(c.rate) / 1000.0, "{}: {} bytes against {nominal}", c.name, bytes.len()); + let mut dec = Decoder::new(); + let mut out = vec![Vec::new(); c.channels]; + for f in frames { + let frame = dec.decode(f).unwrap_or_else(|e| panic!("{}: {e}", c.name)); + for (o, ch) in out.iter_mut().zip(frame.channels) { + o.extend(ch); + } + } + let d = DELAY as usize; + for (ch, input) in inputs(c, n).iter().enumerate() { + let s = snr(input, &out[ch][d..d + n]); + println!("{:<7} {:>5} Hz {}ch {:>3} kbps: SNR {s:.2} dB (our decoder)", c.name, c.rate, c.channels, c.kbps); + assert!(s >= c.min_snr, "{} {} Hz {}ch {} kbps: SNR {s:.2} dB under {}", c.name, c.rate, c.channels, c.kbps, c.min_snr); + } + } +} + +#[test] +fn the_stream_does_not_depend_on_how_the_input_is_chunked() { + let c = &CASES[1]; + let n = 44_100 + 333; + let cfg = Config::cbr(c.rate, c.channels, c.kbps); + let input = inputs(c, n); + let whole = encode(cfg, &input, n); + for chunk in [1, 7, 1152, 5000] { + assert_eq!(encode(cfg, &input, chunk), whole, "chunk {chunk}"); + } +} + +#[test] +fn silence_and_nothing_encode_to_valid_frames() { + let cfg = Config::cbr(48_000, 2, 128); + let silent = vec![vec![0f32; 5000]; 2]; + let bytes = encode(cfg, &silent, 5000); + let fs = frames(&bytes, &cfg); + let mut dec = Decoder::new(); + for f in fs { + let frame = dec.decode(f).expect("decode"); + assert!(frame.channels.iter().flatten().all(|v| v.abs() < 1e-6)); + } + assert!(Encoder::new(cfg).expect("encoder").flush().is_empty(), "no input, no frames"); +} + +#[test] +fn hostile_samples_are_tamed() { + let cfg = Config::cbr(44_100, 2, 192); + let mut x = vec![0f32; 4000]; + for (i, v) in x.iter_mut().enumerate() { + *v = [f32::NAN, f32::INFINITY, -f32::INFINITY, 1e30, -1e30, 3.0, 0.5][i % 7]; + } + let bytes = encode(cfg, &[x.clone(), x], 4000); + let mut dec = Decoder::new(); + for f in frames(&bytes, &cfg) { + dec.decode(f).expect("decode"); + } +} + +#[test] +fn settings_that_cannot_be_carried_are_refused() { + assert_eq!(Encoder::new(Config::cbr(44_000, 2, 128)).err(), Some(EncodeError::SampleRate(44_000))); + assert_eq!(Encoder::new(Config::cbr(44_100, 3, 128)).err(), Some(EncodeError::Channels(3))); + assert_eq!(Encoder::new(Config::cbr(44_100, 0, 128)).err(), Some(EncodeError::Channels(0))); + // ISO/IEC 11172-3 allows neither 32 kbit/s for two channels nor 224 for one + assert!(matches!(Encoder::new(Config::cbr(44_100, 2, 32)), Err(EncodeError::Bitrate { .. }))); + assert!(matches!(Encoder::new(Config::cbr(44_100, 1, 224)), Err(EncodeError::Bitrate { .. }))); + assert!(matches!(Encoder::new(Config::cbr(44_100, 2, 130)), Err(EncodeError::Bitrate { .. }))); + assert_eq!(bitrates(44_100, 1).len(), 10); + assert_eq!(bitrates(22_050, 2).first(), Some(&8)); + assert!(bitrates(8_000, 2).is_empty()); + assert_eq!(nearest_bitrate(44_100, 2, 100), Some(96)); + assert_eq!(nearest_bitrate(44_100, 2, 1), Some(64)); + assert_eq!(nearest_bitrate(8_000, 2, 100), None); +} + +fn ffmpeg_decode(ff: &Path, path: &Path, channels: usize) -> (Vec>, String) { + let out = Command::new(ff) + .args(["-v", "error", "-nostdin", "-i"]) + .arg(path) + .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .stdin(Stdio::null()) + .output() + .expect("run ffmpeg"); + let samples: Vec = out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(); + let planar = (0..channels).map(|c| samples.iter().skip(c).step_by(channels).copied().collect()).collect(); + (planar, String::from_utf8_lossy(&out.stderr).into_owned()) +} + +#[test] +fn ffmpeg_decodes_our_streams_to_the_input() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("mp2enc"); + for c in CASES { + let n = c.rate as usize * 2 + 777; + let input = inputs(c, n); + let bytes = encode(Config::cbr(c.rate, c.channels, c.kbps), &input, 1000); + let path = dir.join(format!("{}_{}_{}ch_{}k.mp2", c.name, c.rate, c.channels, c.kbps)); + std::fs::write(&path, &bytes).expect("write"); + let (dec, err) = ffmpeg_decode(&ff, &path, c.channels); + assert!(err.trim().is_empty(), "{}: ffmpeg reported: {err}", path.display()); + let d = DELAY as usize; + assert!(dec[0].len() >= n + d, "{}: decoded {} samples, need {}", c.name, dec[0].len(), n + d); + let s = (0..c.channels).map(|ch| snr(&input[ch], &dec[ch][d..d + n])).sum::() / c.channels as f64; + println!("{:<7} {:>5} Hz {}ch {:>3} kbps: SNR {s:.2} dB (ffmpeg)", c.name, c.rate, c.channels, c.kbps); + assert!(s >= c.min_snr, "{} {} Hz {}ch {} kbps: SNR {s:.2} dB under {}", c.name, c.rate, c.channels, c.kbps, c.min_snr); + } +} diff --git a/crates/audio/tests/qoa_oracle.rs b/crates/audio/tests/qoa_oracle.rs new file mode 100644 index 000000000..7b5ac2674 --- /dev/null +++ b/crates/audio/tests/qoa_oracle.rs @@ -0,0 +1,62 @@ +//! QOA against ffmpeg's decoder as the reference (oracle; skipped when ffmpeg is absent, a failure +//! with `CRAFT_MEDIA_REQUIRE_ORACLES=1`): ffmpeg decodes the files our encoder writes to exactly +//! the samples our decoder returns for them, over several sizes (partial slices, partial frames, +//! several frames), channel counts and rates. + +use craft_audio::qoa::{decode, encode}; +use std::process::Command; + +fn signal(channels: usize, frames: usize) -> Vec> { + let mut seed = 0x2545_F491u32; + (0..channels) + .map(|c| { + (0..frames) + .map(|i| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let tone = ((i as f64) * (0.02 + 0.013 * c as f64)).sin() * 9000.0; + // Tones, noise bursts, silence and full-scale peaks. + match (i / 700) % 4 { + 0 => tone as i16, + 1 => (tone + f64::from(seed % 6000) - 3000.0) as i16, + 2 => 0, + _ => { + if i % 2 == 0 { + i16::MAX + } else { + i16::MIN + } + } + } + }) + .collect() + }) + .collect() +} + +#[test] +fn ffmpeg_decodes_our_files_to_the_same_samples() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("qoa"); + for (rate, channels, frames) in + [(44_100u32, 1usize, 1usize), (8_000, 1, 19), (48_000, 2, 5_121), (22_050, 2, 12_345), (96_000, 1, 20_000), (44_100, 4, 6_000)] + { + let src = signal(channels, frames); + let bytes = encode(rate, &src).expect("encode"); + let ours = decode(&bytes).expect("decode"); + let file = dir.join(format!("ours_{rate}_{channels}_{frames}.qoa")); + std::fs::write(&file, &bytes).expect("write fixture"); + let out = Command::new(&ffmpeg) + .args(["-v", "error", "-y", "-i"]) + .arg(&file) + .args(["-f", "s16le", "-acodec", "pcm_s16le", "-"]) + .output() + .expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg failed on {}: {}", file.display(), String::from_utf8_lossy(&out.stderr)); + let theirs: Vec = out.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect(); + let interleaved: Vec = (0..frames).flat_map(|i| ours.channels.iter().map(move |ch| ch[i])).collect(); + assert_eq!(theirs.len(), interleaved.len(), "{rate} Hz, {channels} ch, {frames} frames: sample count"); + assert!(theirs == interleaved, "{rate} Hz, {channels} ch, {frames} frames: samples differ"); + } +} diff --git a/crates/audio/tests/sbc_oracle.rs b/crates/audio/tests/sbc_oracle.rs new file mode 100644 index 000000000..62495ae16 --- /dev/null +++ b/crates/audio/tests/sbc_oracle.rs @@ -0,0 +1,298 @@ +#![cfg(feature = "sbc")] + +use craft_audio::sbc::{ + AllocationMethod, BlockCount, ChannelMode, Decoder, Encoder, Header, SYNCWORD_MSBC, SYNCWORD_SBC, SamplingFrequency, Subbands, decode, encode, +}; +use std::process::Command; + +fn pearson_correlation(x: &[i16], y: &[i16], lag: usize) -> f64 { + let n = x.len().min(y.len().saturating_sub(lag)); + if n == 0 { + return 0.0; + } + let x = &x[..n]; + let y = &y[lag..lag + n]; + let mean_x = x.iter().map(|&v| v as f64).sum::() / (n as f64); + let mean_y = y.iter().map(|&v| v as f64).sum::() / (n as f64); + let mut num = 0.0; + let mut denom_x = 0.0; + let mut denom_y = 0.0; + for (&a, &b) in x.iter().zip(y) { + let da = (a as f64) - mean_x; + let db = (b as f64) - mean_y; + num += da * db; + denom_x += da * da; + denom_y += db * db; + } + let denom = (denom_x * denom_y).sqrt(); + if denom > 0.0 { num / denom } else { 0.0 } +} + +fn generate_sine(sample_rate: u32, channels: usize, num_frames: usize) -> Vec { + let mut pcm = Vec::with_capacity(num_frames * channels); + for i in 0..num_frames { + let t = (i as f64) / (sample_rate as f64); + let s_l = (16000.0 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()) as i16; + pcm.push(s_l); + if channels == 2 { + let s_r = (16000.0 * (2.0 * std::f64::consts::PI * 880.0 * t).sin()) as i16; + pcm.push(s_r); + } + } + pcm +} + +#[test] +fn test_header_parse_and_frame_length() { + // Standard SBC header: 0x9C, 44.1kHz, 16 blocks, Joint Stereo, Loudness, 8 subbands, bitpool 32 + let mut packet = vec![SYNCWORD_SBC, 0xBD, 32, 0x00]; + let header = Header::parse(&packet).expect("parse header"); + assert_eq!(header.sampling_frequency, SamplingFrequency::Freq44k1); + assert_eq!(header.blocks, BlockCount::Blocks16); + assert_eq!(header.channel_mode, ChannelMode::JointStereo); + assert_eq!(header.allocation_method, AllocationMethod::Loudness); + assert_eq!(header.subbands, Subbands::Subbands8); + assert_eq!(header.bitpool, 32); + assert_eq!(header.channels(), 2); + assert_eq!(header.samples_per_frame(), 128); + + // Frame length formula check + let expected_len = 4 + (4 * 8 * 2) / 8 + (8usize + 16 * 32).div_ceil(8); + assert_eq!(header.frame_length(), expected_len); + assert_eq!(header.frame_length(), 77); + + // mSBC header: 0xAD + packet[0] = SYNCWORD_MSBC; + let msbc_header = Header::parse(&packet).expect("parse msbc header"); + assert_eq!(msbc_header.frame_length(), 57); + assert_eq!(msbc_header.sample_rate(), 16000); + assert_eq!(msbc_header.channels(), 1); +} + +#[test] +fn test_silence_roundtrip() { + for &sample_rate in &[16_000u32, 32_000, 44_100, 48_000] { + for &channels in &[1usize, 2] { + for &subbands in &[4usize, 8] { + for &blocks in &[4usize, 8, 12, 16] { + let frame_samples = blocks * subbands * channels; + let pcm = vec![0i16; frame_samples * 4]; + let mut encoder = Encoder::new(sample_rate, channels, blocks, subbands, 32, AllocationMethod::Loudness).expect("create encoder"); + + let mut sbc_bytes = Vec::new(); + encoder.encode(&pcm, &mut sbc_bytes).expect("encode silence"); + assert!(!sbc_bytes.is_empty()); + + let mut decoder = Decoder::new(); + let mut decoded = Vec::new(); + decoder.decode(&sbc_bytes, &mut decoded).expect("decode silence"); + + assert_eq!(decoded.len(), pcm.len()); + for &s in &decoded { + assert!(s.abs() <= 16, "silence sample too large: {s}"); + } + } + } + } + } +} + +#[test] +fn test_sine_wave_roundtrip_fidelity() { + let sample_rate = 44_100u32; + let channels = 2usize; + let num_frames = 128 * 20; + let pcm = generate_sine(sample_rate, channels, num_frames); + + let sbc_bytes = encode(&pcm, sample_rate, channels, 32).expect("encode sine"); + let (decoded, info) = decode(&sbc_bytes).expect("decode sine"); + + assert_eq!(info.sample_rate, sample_rate); + assert_eq!(info.channels, channels); + assert_eq!(decoded.len(), pcm.len()); + + // 8-subband filterbank total delay is 73 samples per channel + let corr_l = pearson_correlation(&pcm[0..], &decoded[0..], 73 * 2); + assert!(corr_l > 0.98, "left channel correlation too low: {corr_l}"); +} + +#[test] +fn test_invalid_and_corrupt_inputs() { + let mut decoder = Decoder::new(); + let mut dst = Vec::new(); + + // Empty packet + assert!(decoder.decode_frame(&[], &mut dst).is_err()); + + // Too short header + assert!(decoder.decode_frame(&[SYNCWORD_SBC, 0x00], &mut dst).is_err()); + + // Invalid syncword + assert!(decoder.decode_frame(&[0x00, 0xBD, 32, 0x00], &mut dst).is_err()); + + // CRC mismatch + let bad_crc_frame = vec![SYNCWORD_SBC, 0xBD, 32, 0x55, 0x00, 0x00, 0x00, 0x00]; + assert!(decoder.decode_frame(&bad_crc_frame, &mut dst).is_err()); + + // Bitpool capacity exceeded (Mono 4 subbands capacity is 64; 65 must fail) + let bad_bitpool_frame = vec![SYNCWORD_SBC, 0x00, 65, 0x00]; + assert!(decoder.decode_frame(&bad_bitpool_frame, &mut dst).is_err()); + assert!(Encoder::new(16000, 1, 4, 4, 65, AllocationMethod::Loudness).is_err()); + + // Unsupported 15-block configuration (only 16kHz mono 8-subband 26-bitpool is valid mSBC) + assert!(Encoder::new(44100, 2, 15, 8, 32, AllocationMethod::Loudness).is_err()); + + // Incomplete PCM frames rejected by encoder + let mut enc = Encoder::new(44100, 2, 16, 8, 32, AllocationMethod::Loudness).expect("enc"); + let mut out = Vec::new(); + assert!(enc.encode(&[0i16; 100], &mut out).is_err()); + + // Valid mSBC encoding produces exact 57-byte mSBC frame + let mut msbc_enc = Encoder::new(16000, 1, 15, 8, 26, AllocationMethod::Loudness).expect("msbc enc"); + let mut msbc_out = Vec::new(); + msbc_enc.encode(&vec![0i16; 120], &mut msbc_out).expect("encode msbc frame"); + assert_eq!(msbc_out.len(), 57); + assert_eq!(msbc_out[0], SYNCWORD_MSBC); + + // Hostile fuzzed input should never panic + let mut seed = 0x1234_5678u32; + for len in [10, 50, 100, 500] { + let mut random_bytes = vec![0u8; len]; + for b in &mut random_bytes { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + *b = seed as u8; + } + let _ = decoder.decode(&random_bytes, &mut dst); + } +} + +#[test] +fn test_oracle_ffmpeg_cross_verification() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { + return; + }; + let dir = craft_media_testkit::fixture_subdir("sbc"); + + // 1. FFmpeg decodes our encoded SBC files + for &(sample_rate, channels) in &[(16_000u32, 1usize), (44_100, 2), (48_000, 2)] { + let pcm = generate_sine(sample_rate, channels, 128 * 20); + let sbc_bytes = encode(&pcm, sample_rate, channels, 32).expect("encode sbc"); + + let sbc_file = dir.join(format!("ours_{sample_rate}_{channels}.sbc")); + std::fs::write(&sbc_file, &sbc_bytes).expect("write sbc fixture"); + + let out = Command::new(&ffmpeg) + .args(["-v", "error", "-y", "-i"]) + .arg(&sbc_file) + .args(["-f", "s16le", "-acodec", "pcm_s16le", "-"]) + .output() + .expect("run ffmpeg"); + + assert!(out.status.success(), "ffmpeg failed to decode our SBC: {}", String::from_utf8_lossy(&out.stderr)); + + let theirs: Vec = out.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect(); + + assert!(!theirs.is_empty()); + let corr = pearson_correlation(&pcm, &theirs, 73 * channels); + assert!(corr > 0.95, "FFmpeg decoded output correlation against input too low ({sample_rate} Hz, {channels} ch): {corr}"); + } + + // 2. Our decoder decodes FFmpeg-encoded SBC files + for &(sample_rate, channels) in &[(16_000u32, 1usize), (44_100, 2), (48_000, 2)] { + let ff_sbc_file = dir.join(format!("ff_{sample_rate}_{channels}.sbc")); + let ff_enc = Command::new(&ffmpeg) + .args([ + "-v", + "error", + "-y", + "-f", + "lavfi", + "-i", + &format!("sine=frequency=440:duration=0.2:sample_rate={sample_rate}"), + "-c:a", + "sbc", + "-ac", + &channels.to_string(), + ]) + .arg(&ff_sbc_file) + .output() + .expect("ffmpeg encode sbc"); + + assert!(ff_enc.status.success(), "ffmpeg failed to encode SBC: {}", String::from_utf8_lossy(&ff_enc.stderr)); + + let ff_sbc_bytes = std::fs::read(&ff_sbc_file).expect("read ff sbc fixture"); + let (decoded, info) = decode(&ff_sbc_bytes).expect("decode ff sbc"); + assert_eq!(info.sample_rate, sample_rate); + assert_eq!(info.channels, channels); + assert!(!decoded.is_empty()); + + // Decode ff_sbc_file with ffmpeg as well to compare + let ff_raw = Command::new(&ffmpeg) + .args(["-v", "error", "-y", "-i"]) + .arg(&ff_sbc_file) + .args(["-f", "s16le", "-acodec", "pcm_s16le", "-"]) + .output() + .expect("ffmpeg decode raw"); + + let ff_pcm: Vec = ff_raw.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect(); + + let corr = pearson_correlation(&decoded, &ff_pcm, 0); + assert!(corr > 0.99, "Our decoder output correlation against FFmpeg decoder output too low: {corr}"); + } + + // 3. Our decoder decodes FFmpeg-encoded mSBC wideband speech + let msbc_file = dir.join("ff_msbc.sbc"); + let ff_msbc_enc = Command::new(&ffmpeg) + .args(["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=0.2:sample_rate=16000", "-c:a", "sbc", "-msbc", "1"]) + .arg(&msbc_file) + .output() + .expect("ffmpeg encode msbc"); + + assert!(ff_msbc_enc.status.success(), "ffmpeg failed to encode mSBC: {}", String::from_utf8_lossy(&ff_msbc_enc.stderr)); + + let msbc_bytes = std::fs::read(&msbc_file).expect("read msbc fixture"); + let (decoded, info) = decode(&msbc_bytes).expect("decode msbc"); + assert_eq!(info.sample_rate, 16000); + assert_eq!(info.channels, 1); + assert_eq!(info.blocks, 15); + assert_eq!(info.subbands, 8); + assert!(!decoded.is_empty()); + + let ff_msbc_raw = Command::new(&ffmpeg) + .args(["-v", "error", "-y", "-i"]) + .arg(&msbc_file) + .args(["-f", "s16le", "-acodec", "pcm_s16le", "-"]) + .output() + .expect("ffmpeg decode msbc raw"); + + let ff_msbc_pcm: Vec = ff_msbc_raw.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect(); + + let corr = pearson_correlation(&decoded, &ff_msbc_pcm, 0); + assert!(corr > 0.99, "mSBC decoded output correlation against FFmpeg decoder too low: {corr}"); + + // 4. FFmpeg decodes our encoded mSBC file + let msbc_sine = generate_sine(16000, 1, 120 * 20); + let mut our_msbc_enc = Encoder::new(16000, 1, 15, 8, 26, AllocationMethod::Loudness).expect("msbc enc"); + let mut our_msbc_bytes = Vec::new(); + our_msbc_enc.encode(&msbc_sine, &mut our_msbc_bytes).expect("encode msbc"); + + let our_msbc_file = dir.join("ours_msbc.sbc"); + std::fs::write(&our_msbc_file, &our_msbc_bytes).expect("write our msbc fixture"); + + let our_msbc_out = Command::new(&ffmpeg) + .args(["-v", "error", "-y", "-i"]) + .arg(&our_msbc_file) + .args(["-f", "s16le", "-acodec", "pcm_s16le", "-"]) + .output() + .expect("ffmpeg decode our msbc"); + + assert!(our_msbc_out.status.success(), "ffmpeg failed to decode our mSBC: {}", String::from_utf8_lossy(&our_msbc_out.stderr)); + + let our_msbc_theirs: Vec = our_msbc_out.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect(); + + assert!(!our_msbc_theirs.is_empty()); + let corr_msbc = pearson_correlation(&msbc_sine, &our_msbc_theirs, 73); + assert!(corr_msbc > 0.95, "FFmpeg decoded output correlation against our mSBC input too low: {corr_msbc}"); +} diff --git a/crates/audio/tests/vmd.rs b/crates/audio/tests/vmd.rs new file mode 100644 index 000000000..145aafa79 --- /dev/null +++ b/crates/audio/tests/vmd.rs @@ -0,0 +1,280 @@ +//! VMD sound decoder tests. ffmpeg reads VMD but cannot write it, so the files come from the +//! test kit's VMD writer. The decoder must return the samples that were packed, and the same +//! samples as ffmpeg (skipped without ffmpeg). + +use std::process::Command; + +use craft_audio::AudioError; +use craft_audio::vmd::{Decoder, Error}; +use craft_media::vmd::{FrameKind, open}; +use craft_media_testkit::hostile::Rng; +use craft_media_testkit::vmd::{Audio, Frame, Spec, build, dpcm_pack}; + +/// (frame length field, audio flags, channels, 16-bit): every layout the decoder handles. +const FORMATS: [(i16, u16, usize, bool); 6] = + [(50, 0, 1, false), (50, 0x200, 2, false), (50, 0x8000, 2, false), (-50, 0, 1, true), (-50, 0x200, 2, true), (-50, 0x8000, 2, true)]; + +fn spec(frame_length: i16, flags: u16) -> Spec { + let mut spec = Spec::new(4, 4); + spec.audio = Some(Audio { sample_rate: 22050, frame_length, buffers: 5, flags }); + spec +} + +fn decoder(frame_length: i16, flags: u16) -> Decoder { + Decoder::new(&build(&spec(frame_length, flags), &[])).unwrap() +} + +/// One block of random sound: its bytes in the file and the samples it decodes to. +fn block(rng: &mut Rng, d: &Decoder) -> (Vec, Vec) { + let n = d.block_samples() * d.channels(); + if d.bits() == 8 { + let bytes: Vec = (0..n).map(|_| rng.next_u64() as u8).collect(); + let samples = bytes.iter().map(|&b| (i16::from(b) - 0x80) << 8).collect(); + return (bytes, samples); + } + // a random walk, so that the steps are of every size + let mut last = [0i32; 2]; + let samples: Vec = (0..n) + .map(|i| { + let bits = 1 + rng.below(15); + let step = rng.below(1 << bits) as i32 - (1 << (bits - 1)); + let s = &mut last[i % d.channels()]; + *s = (*s + step).clamp(-32768, 32767); + *s as i16 + }) + .collect(); + dpcm_pack(&samples, d.channels()) +} + +/// A file of sound frames (with a small picture each, as ffmpeg expects video) and the samples +/// expected of it. The first frame is a mask frame: one silent block, then four of sound. +fn movie(seed: u64, frame_length: i16, flags: u16) -> (Vec, Vec) { + let spec = spec(frame_length, flags); + let d = decoder(frame_length, flags); + let mut rng = Rng(seed | 1); + let mut picture = vec![2u8]; + picture.extend([9; 16]); + let silence = vec![0i16; d.block_samples() * d.channels()]; + let mut want = Vec::new(); + let mut blocks = Vec::new(); + for n in 0..12 { + let sound = match n { + 0 => { + let mut data = 1u32.to_le_bytes().to_vec(); + want.extend_from_slice(&silence); + for _ in 0..4 { + let (bytes, samples) = block(&mut rng, &d); + data.extend_from_slice(&bytes); + want.extend_from_slice(&samples); + } + Frame::audio(2, data) + } + _ if rng.below(4) == 0 => { + want.extend_from_slice(&silence); + Frame::audio(3, vec![]) + } + _ => { + let (bytes, samples) = block(&mut rng, &d); + want.extend_from_slice(&samples); + Frame::audio(1, bytes) + } + }; + blocks.push(vec![sound, Frame::video([0, 0, 3, 3], false, picture.clone())]); + } + (build(&spec, &blocks), want) +} + +fn decode_all(bytes: &[u8]) -> Vec { + let file = open(bytes).unwrap(); + let d = Decoder::new(file.header_bytes()).unwrap(); + let mut out = Vec::new(); + for (i, frame) in file.frames.iter().enumerate() { + if let FrameKind::Audio { flags } = frame.kind { + out.extend(d.decode(flags, &file.read_frame(bytes, i).unwrap()).unwrap()); + } + } + out +} + +#[test] +fn decodes_the_samples_that_were_packed() { + for (i, (frame_length, flags, channels, sixteen)) in FORMATS.into_iter().enumerate() { + let d = decoder(frame_length, flags); + assert_eq!((d.channels(), d.bits(), d.sample_rate()), (channels, if sixteen { 16 } else { 8 }, 22050), "format {i}"); + // old-style stereo counts both channels in the frame length + assert_eq!(d.block_samples(), if flags & 0x8000 != 0 { 25 } else { 50 }, "format {i}"); + let (bytes, want) = movie(i as u64 + 1, frame_length, flags); + assert_eq!(want.len(), 16 * d.block_samples() * channels); + assert!(decode_all(&bytes) == want, "format {i}"); + } +} + +#[test] +fn matches_ffmpeg() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg_or_skip("vmd sound oracle") else { return }; + let dir = craft_media_testkit::private_dir("vmd-sound"); + for (i, (frame_length, flags, ..)) in FORMATS.into_iter().enumerate() { + let (bytes, _) = movie(i as u64 + 1, frame_length, flags); + let path = dir.join(format!("sound{i}.vmd")); + std::fs::write(&path, &bytes).unwrap(); + let out = Command::new(&ffmpeg).args(["-v", "error", "-i"]).arg(&path).args(["-vn", "-f", "s16le", "-"]).output().unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "format {i}: ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); + let theirs: Vec = out.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect(); + assert!(theirs == decode_all(&bytes), "format {i} differs from ffmpeg"); + } + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn sixteen_bit_steps() { + // values ffmpeg gave for this block: the first sample, then signed steps from the table + let mut data = 1000i16.to_le_bytes().to_vec(); + data.extend([1, 1, 1, 0x81, 0x81, 2, 3, 0x7F, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); + let d = decoder(-20, 0); + assert_eq!(d.block_bytes(), 21); + assert_eq!( + d.decode(1, &data).unwrap(), + [1000, 1008, 1016, 1024, 1016, 1008, 1024, 1056, 17440, 1056, 1056, 1056, 1056, 1056, 1056, 1056, 1056, 1056, 1056, 1064] + ); + // stereo: the channels take turns + let mut data = [1000i16.to_le_bytes(), (-1000i16).to_le_bytes()].concat(); + data.extend([1, 0x82].repeat(3)); + let d = decoder(-4, 0x200); + assert_eq!(d.decode(1, &data).unwrap(), [1000, -1000, 1008, -1016, 1016, -1032, 1024, -1048]); + // a flags 1 frame of several blocks: each block starts from its own first samples + let (first, first_samples) = dpcm_pack(&[100, -100, 300, -50, 200, 0, 1000, 500], 2); + let (second, second_samples) = dpcm_pack(&[-7000, 7000, -6000, 6500, -6100, 6400, -3000, 3000], 2); + assert_eq!(d.decode(1, &[first, second, vec![1, 2, 3]].concat()).unwrap(), [first_samples, second_samples].concat()); + // steps past 16 bits stop at the ends + let mut data = 30000i16.to_le_bytes().to_vec(); + data.extend([0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); + assert_eq!(decoder(-7, 0).decode(1, &data).unwrap(), [30000, 32767, 16383, -1, -16385, -32768, -32768]); +} + +#[test] +fn eight_bit_and_silence() { + let d = decoder(4, 0); + assert_eq!(d.decode(1, &[0x80, 0x00, 0xFF, 0x70]).unwrap(), [0, -32768, 0x7F00, -0x1000]); + assert_eq!(d.decode(3, &[]).unwrap(), [0; 4]); + assert_eq!(d.decode(1, &[]).unwrap(), [0i16; 0]); + assert_eq!(decoder(4, 0x200).decode(3, &[]).unwrap(), [0; 8]); + // a flags 1 frame of more than one block plays every whole block + assert_eq!( + d.decode(1, &[0x80, 0x81, 0x82, 0x83, 0x90, 0x91, 0x92, 0x93, 0xA0]).unwrap(), + [0, 0x100, 0x200, 0x300, 0x1000, 0x1100, 0x1200, 0x1300] + ); + assert_eq!(decoder(-4, 0x8000).decode(3, &[]).unwrap(), [0; 4]); +} + +#[test] +fn silence_mask_runs_bit_by_bit() { + let d = decoder(2, 0); + let frame = |mask: u32, data: &[u8]| d.decode(2, &[&mask.to_le_bytes()[..], data].concat()); + let (a, b) = ([0x90, 0x91], [0xA0, 0xA1]); + let (sa, sb) = ([0x1000, 0x1100], [0x2000, 0x2100]); + assert_eq!(frame(0, &[a, b].concat()).unwrap(), [sa, sb].concat()); + // silent, sound, silent, sound + assert_eq!(frame(0b0101, &[a, b].concat()).unwrap(), [[0, 0], sa, [0, 0], sb].concat()); + // game files set a bit for every block when all are silent + assert_eq!(frame(0b0111, &[]).unwrap(), [0; 6]); + // a trailing part of a block is left out + assert_eq!(frame(0, &[0x90, 0x91, 0xA0]).unwrap(), sa); + assert_eq!(d.decode(2, &[0, 0, 0]), Err(Error::Invalid("the silence mask is cut short"))); +} + +#[test] +fn bad_input_is_an_error() { + let d = decoder(-20, 0); + assert_eq!(d.decode(1, &[0; 20]), Err(Error::Invalid("a block of sound is cut short"))); + assert_eq!(d.decode(4, &[0; 21]), Err(Error::Unsupported("unknown sound frame flags"))); + assert_eq!(d.decode(4, &[]), Err(Error::Unsupported("unknown sound frame flags"))); + // in the file API's error: unsupported stays unsupported, the rest is malformed input + assert!(matches!(AudioError::from(Error::Unsupported("x")), AudioError::Unsupported(_))); + assert!(matches!(AudioError::from(Error::Invalid("x")), AudioError::Malformed(_))); + + let good = build(&spec(20, 0), &[]); + let with = |patch: &dyn Fn(&mut Vec)| { + let mut h = good.clone(); + patch(&mut h); + Decoder::new(&h).err() + }; + assert_eq!(with(&|_| {}), None); + assert_eq!(with(&|h| h.truncate(815)), Some(Error::Invalid("the header is shorter than 816 bytes"))); + assert_eq!(with(&|h| h[0] = 0), Some(Error::Invalid("not a VMD header"))); + assert_eq!(with(&|h| h[17] = 0), Some(Error::Invalid("the file has no sound"))); + assert_eq!(with(&|h| h[804..806].fill(0)), Some(Error::Invalid("the file has no sound"))); + assert_eq!(with(&|h| h[810] = 0x10), Some(Error::Unsupported("IMA ADPCM sound"))); + // a frame length of nothing decodes to nothing + let mut empty = good.clone(); + empty[806..808].fill(0); + let d = Decoder::new(&empty).unwrap(); + assert_eq!(d.decode(1, &[1, 2, 3]).unwrap(), [0i16; 0]); + assert_eq!(d.decode(2, &[0, 0, 0, 0, 1, 2]).unwrap(), [0i16; 0]); +} + +#[test] +fn hostile_input_never_panics() { + for (i, (frame_length, flags, ..)) in FORMATS.into_iter().enumerate() { + let (bytes, _) = movie(i as u64 + 1, frame_length, flags); + craft_media_testkit::hostile::hammer(&format!("vmd sound format {i}"), &bytes, 10_000, |d| { + let Ok(file) = open(d) else { return }; + let Ok(decoder) = Decoder::new(file.header_bytes()) else { return }; + for (i, frame) in file.frames.iter().enumerate() { + let FrameKind::Audio { flags } = frame.kind else { continue }; + if let Ok(data) = file.read_frame(d, i) { + let _ = decoder.decode(flags, &data); + } + } + }); + } +} + +/// Real files, for whoever has some: the sound of every `.vmd` in the directory +/// `CRAFT_MEDIA_VMD_SAMPLES` names must decode to the samples ffmpeg gets. Game files are not +/// redistributable, so none are in the repository and the test is skipped without the variable. +#[test] +fn real_files_match_ffmpeg() { + let Some(dir) = std::env::var_os("CRAFT_MEDIA_VMD_SAMPLES").filter(|d| !d.is_empty()) else { + craft_media_testkit::skip_test("vmd samples", "CRAFT_MEDIA_VMD_SAMPLES is not set"); + return; + }; + let Some(ffmpeg) = craft_media_testkit::ffmpeg_or_skip("vmd sound samples") else { return }; + let mut paths: Vec<_> = std::fs::read_dir(&dir) + .unwrap() + .filter_map(|e| Some(e.ok()?.path())) + .filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("vmd"))) + .collect(); + paths.sort(); + assert!(!paths.is_empty(), "no .vmd files in CRAFT_MEDIA_VMD_SAMPLES"); + let (mut files, mut samples) = (0, 0); + for path in &paths { + let name = path.display(); + let source = std::fs::File::open(path).unwrap(); + let file = open(&source).unwrap(); + if file.audio_params().is_none() { + continue; + } + let d = Decoder::new(file.header_bytes()).unwrap(); + let mut ours = Vec::new(); + for (i, frame) in file.frames.iter().enumerate() { + let FrameKind::Audio { flags } = frame.kind else { continue }; + let mut data = file.read_frame(&source, i).unwrap(); + if flags == 2 && data.len() >= 4 { + // ffmpeg plays a mask frame's silent blocks before its sound; put ours in that + // order to compare + let silent = u32::from_le_bytes([data[0], data[1], data[2], data[3]]).count_ones() as usize; + ours.resize(ours.len() + silent * d.block_samples() * d.channels(), 0); + data[..4].fill(0); + } + ours.extend(d.decode(flags, &data).unwrap_or_else(|e| panic!("{name}: frame {i}: {e}"))); + } + let out = Command::new(&ffmpeg).args(["-v", "quiet", "-i"]).arg(path).args(["-vn", "-f", "s16le", "-"]).output().unwrap(); + let theirs: Vec = out.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect(); + if let Some(at) = (0..ours.len().max(theirs.len())).find(|&i| ours.get(i) != theirs.get(i)) { + panic!("{name}: sample {at} differs from ffmpeg ({} samples here, {} there)", ours.len(), theirs.len()); + } + files += 1; + samples += ours.len(); + } + println!("{files} files, {samples} samples match ffmpeg"); +} diff --git a/crates/audio/tests/vorbis_decode_hostile.rs b/crates/audio/tests/vorbis_decode_hostile.rs new file mode 100644 index 000000000..fba004e10 --- /dev/null +++ b/crates/audio/tests/vorbis_decode_hostile.rs @@ -0,0 +1,230 @@ +//! Hostile input to the Vorbis decoder: damaged headers and packets, truncations, and headers that +//! ask for absurd sizes. Every case is an error or a result, never a panic or a large allocation. + +use craft_audio::vorbis::decoder::{Decoder, Error, decode_ogg}; +use craft_audio::{AudioBuffer, OggVorbisOptions, encode_ogg_vorbis}; + +fn xorshift(seed: &mut u32) -> u32 { + *seed ^= *seed << 13; + *seed ^= *seed >> 17; + *seed ^= *seed << 5; + *seed +} + +struct Parts { + ogg: Vec, + headers: Vec>, + packets: Vec>, +} + +fn parts(channels: usize) -> Parts { + let signal: Vec> = (0..channels) + .map(|c| (0..20_000).map(|i| ((i as f32 * (0.03 + 0.01 * c as f32)).sin() * 0.4) + ((i * 7 % 13) as f32 - 6.0) / 60.0).collect()) + .collect(); + let ogg = + encode_ogg_vorbis(&AudioBuffer { sample_rate: 44_100, channels: signal }, &OggVorbisOptions::default().with_quality(4.0)).expect("encode"); + let file = craft_media::ogg::open(ogg.as_slice()).expect("open"); + let s = &file.streams[0]; + let packets = (0..s.packets.len()).map(|i| file.read_packet(ogg.as_slice(), 0, i).expect("packet")).collect(); + Parts { headers: s.headers.clone(), packets, ogg } +} + +fn decoder(p: &Parts) -> Decoder { + Decoder::new(&p.headers[0], &p.headers[1], &p.headers[2]).expect("valid headers") +} + +#[test] +fn every_truncated_header_is_an_error() { + let p = parts(2); + for which in [0usize, 2] { + for n in 0..p.headers[which].len() { + let mut h = p.headers.clone(); + h[which].truncate(n); + assert!(Decoder::new(&h[0], &h[1], &h[2]).is_err(), "header {which} cut to {n} bytes"); + } + } + // A damaged comment header is not fatal. + let mut h = p.headers.clone(); + h[1].truncate(12); + let d = Decoder::new(&h[0], &h[1], &h[2]).expect("comments are best effort"); + assert!(d.comments().comments.is_empty()); + assert!(Decoder::new(&p.headers[0], &[], &p.headers[2]).is_err(), "the comment header still needs its tag"); +} + +#[test] +fn damaged_headers_never_panic() { + let p = parts(2); + let mut seed = 99u32; + for which in [0usize, 2] { + let len = p.headers[which].len(); + for _ in 0..800 { + let mut h = p.headers.clone(); + for _ in 0..1 + xorshift(&mut seed) % 3 { + let at = xorshift(&mut seed) as usize % len; + h[which][at] = xorshift(&mut seed) as u8; + } + if let Ok(mut d) = Decoder::new(&h[0], &h[1], &h[2]) { + // A setup that survives must also survive audio packets. + for pk in p.packets.iter().take(6) { + let _ = d.decode_packet(pk); + } + } + } + } +} + +#[test] +fn damaged_packets_never_panic() { + let p = parts(2); + let mut seed = 7u32; + let mut d = decoder(&p); + for pk in &p.packets { + for _ in 0..6 { + let mut bad = pk.clone(); + match xorshift(&mut seed) % 3 { + 0 => bad.truncate(xorshift(&mut seed) as usize % (bad.len() + 1)), + 1 => { + let at = xorshift(&mut seed) as usize % bad.len(); + bad[at] = xorshift(&mut seed) as u8; + } + _ => bad = (0..xorshift(&mut seed) % 300).map(|_| xorshift(&mut seed) as u8).collect(), + } + let _ = d.decode_packet(&bad); + } + } + // The decoder still decodes good packets after all that. + d.reset(); + assert!(d.decode_packet(&p.packets[3]).is_ok()); +} + +#[test] +fn header_packets_and_empty_packets_are_not_audio() { + let p = parts(1); + let mut d = decoder(&p); + assert_eq!(d.decode_packet(&p.headers[0]), Err(Error::NotAudio)); + assert_eq!(d.decode_packet(&p.headers[2]), Err(Error::NotAudio)); + assert!(matches!(d.decode_packet(&[]), Err(Error::Packet(_)))); +} + +#[test] +fn damaged_files_never_panic() { + let p = parts(2); + let mut seed = 31u32; + for _ in 0..120 { + let mut bad = p.ogg.clone(); + for _ in 0..1 + xorshift(&mut seed) % 4 { + let at = xorshift(&mut seed) as usize % bad.len(); + bad[at] = xorshift(&mut seed) as u8; + } + let _ = decode_ogg(&bad); + bad.truncate(xorshift(&mut seed) as usize % bad.len()); + let _ = decode_ogg(&bad); + } + assert!(matches!(decode_ogg(b"not an ogg file"), Err(Error::Ogg(_)))); + assert!(matches!(decode_ogg(&[]), Err(Error::Ogg(_)))); +} + +/// A bit writer for hand-built setups. +#[derive(Default)] +struct W(Vec, usize); +impl W { + fn put(&mut self, v: u64, n: u32) { + for i in 0..n { + if self.1.is_multiple_of(8) { + self.0.push(0); + } + let last = self.0.len() - 1; + self.0[last] |= (((v >> i) & 1) as u8) << (self.1 % 8); + self.1 += 1; + } + } +} + +fn setup_with_first_book(book: impl FnOnce(&mut W)) -> Vec { + let mut w = W::default(); + w.put(5, 8); + for c in b"vorbis" { + w.put(u64::from(*c), 8); + } + w.put(0, 8); // one book + book(&mut w); + w.0 +} + +#[test] +fn absurd_codebook_sizes_are_refused_before_allocating() { + let p = parts(1); + let try_setup = |setup: Vec| Decoder::new(&p.headers[0], &p.headers[1], &setup); + // 2^24 - 1 entries. + assert!( + try_setup(setup_with_first_book(|w| { + w.put(0x56_4342, 24); + w.put(1, 16); + w.put(0xFF_FFFF, 24); + w.put(1, 1); // ordered + w.put(0, 5); + })) + .is_err() + ); + // An ordered book whose lengths overrun its entries. + assert!( + try_setup(setup_with_first_book(|w| { + w.put(0x56_4342, 24); + w.put(1, 16); + w.put(8, 24); + w.put(1, 1); + w.put(0, 5); + w.put(0xFF, 4); // asks for more codewords of length 1 than there are entries + })) + .is_err() + ); + // A lookup table of 65535 dimensions over a million entries: 69 billion values. + assert!( + try_setup(setup_with_first_book(|w| { + w.put(0x56_4342, 24); + w.put(0xFFFF, 16); + w.put(1 << 20, 24); + w.put(1, 1); // ordered + w.put(19, 5); // length 20 + w.put(1 << 20, 21); // all the entries + w.put(2, 4); // lookup type 2 + w.put(0, 32); + w.put(0, 32); + w.put(0, 4); + w.put(0, 1); + })) + .is_err() + ); + // A million-entry book with a legitimate tree but a lookup table that is not in the packet. + assert!( + try_setup(setup_with_first_book(|w| { + w.put(0x56_4342, 24); + w.put(4, 16); + w.put(1 << 20, 24); + w.put(1, 1); + w.put(19, 5); + w.put(1 << 20, 21); + w.put(1, 4); // lookup type 1 + w.put(0, 32); + w.put(0, 32); + w.put(15, 4); + w.put(0, 1); + })) + .is_err() + ); +} + +#[test] +fn identification_header_limits() { + let p = parts(1); + let mut h = p.headers[0].clone(); + let setup = &p.headers[2]; + h[11] = 0; // no channels + assert!(matches!(Decoder::new(&h, &p.headers[1], setup), Err(Error::Header(_)))); + let mut h = p.headers[0].clone(); + h[28] = 0x95; // a short block size of 2^5 is below the 64 Vorbis allows + assert!(matches!(Decoder::new(&h, &p.headers[1], setup), Err(Error::Header(_)))); + let mut h = p.headers[0].clone(); + h[7] = 1; // version 1 + assert!(matches!(Decoder::new(&h, &p.headers[1], setup), Err(Error::Header(_)))); +} diff --git a/crates/audio/tests/vorbis_decode_oracle.rs b/crates/audio/tests/vorbis_decode_oracle.rs new file mode 100644 index 000000000..a23d2a954 --- /dev/null +++ b/crates/audio/tests/vorbis_decode_oracle.rs @@ -0,0 +1,216 @@ +//! The Vorbis decoder against ffmpeg's as the reference (oracle; skipped when ffmpeg is absent, a +//! failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). Streams come from two encoders, this crate's and +//! ffmpeg's own, so the setups differ: different floors, residues, block sizes, channel counts and +//! coupling. Both decoders must return the same samples. + +use craft_audio::AudioBuffer; +use craft_audio::vorbis::decoder::{Decoder, decode_ogg}; +use craft_audio::{OggVorbisOptions, encode_ogg_vorbis}; +use std::path::Path; +use std::process::Command; + +fn xorshift(seed: &mut u32) -> u32 { + *seed ^= *seed << 13; + *seed ^= *seed >> 17; + *seed ^= *seed << 5; + *seed +} + +/// A signal with tones, noise bursts, clicks and silence, different in every channel. +fn signal(rate: u32, channels: usize, frames: usize) -> Vec> { + let mut seed = 0x1234_5678u32; + (0..channels) + .map(|c| { + (0..frames) + .map(|i| { + let t = i as f64 / f64::from(rate); + let tone = + (t * (220.0 + 110.0 * c as f64) * std::f64::consts::TAU).sin() * 0.3 + (t * 3100.0 * std::f64::consts::TAU).sin() * 0.05; + let noise = (f64::from(xorshift(&mut seed) % 2000) - 1000.0) / 6000.0; + let s = match (i / (rate as usize / 4)) % 6 { + 0 | 1 => tone, + 2 => noise, + 3 => 0.0, + 4 => tone + if i % 3000 < 8 { 0.6 } else { 0.0 }, + _ => tone * (t * 4.0).sin(), + }; + s as f32 + }) + .collect() + }) + .collect() +} + +fn ffmpeg_decode(ffmpeg: &Path, ogg: &Path, channels: usize) -> Vec> { + let out = Command::new(ffmpeg) + .args(["-v", "error", "-nostdin", "-i"]) + .arg(ogg) + .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .output() + .expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg failed on {}: {}", ogg.display(), String::from_utf8_lossy(&out.stderr)); + let all: Vec = out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(); + (0..channels).map(|c| all.iter().skip(c).step_by(channels).copied().collect()).collect() +} + +/// Each of our channels matches a different one of theirs (ffmpeg reorders the channels of surround +/// streams), to within float rounding. +fn assert_same(name: &str, ours: &[Vec], theirs: &[Vec]) { + assert_prefix(name, ours, theirs, true); +} + +/// As [`assert_same`], but with `exact` unset ffmpeg may return more samples than we do (it does +/// not always trim a stream to its last granule position); the common part must agree. +fn assert_prefix(name: &str, ours: &[Vec], theirs: &[Vec], exact: bool) { + assert_eq!(ours.len(), theirs.len(), "{name}: channel count"); + assert!(ours.iter().chain(theirs).flatten().all(|v| v.is_finite()), "{name}: non-finite oracle input or output"); + let mut used = vec![false; theirs.len()]; + for (c, o) in ours.iter().enumerate() { + let mut best: Option<(usize, f32)> = None; + for (k, t) in theirs.iter().enumerate() { + if used[k] { + continue; + } + if exact { + assert_eq!(o.len(), t.len(), "{name}: channel {c} length {} vs ffmpeg {}", o.len(), t.len()); + } else { + assert!(o.len() <= t.len(), "{name}: channel {c} length {} vs ffmpeg {}", o.len(), t.len()); + } + let worst = o.iter().zip(t).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); + if best.is_none_or(|(_, w)| worst < w) { + best = Some((k, worst)); + } + } + let (k, worst) = best.expect("a free channel"); + used[k] = true; + assert!(worst < 2e-4, "{name}: channel {c} differs from ffmpeg's channel {k} by up to {worst}"); + } +} + +#[test] +fn ffmpeg_decodes_our_encoders_streams_to_the_same_samples() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("vorbis_decode"); + for (rate, channels, quality) in + [(44_100u32, 2usize, 6.0f32), (44_100, 1, 3.0), (48_000, 2, -1.0), (22_050, 1, 10.0), (44_100, 6, 5.0), (32_000, 8, 4.0)] + { + let buf = AudioBuffer { sample_rate: rate, channels: signal(rate, channels, rate as usize * 2 + 777) }; + let ogg = encode_ogg_vorbis(&buf, &OggVorbisOptions::default().with_quality(quality)).expect("encode"); + let file = dir.join(format!("ours_{rate}_{channels}_{quality}.ogg")); + std::fs::write(&file, &ogg).expect("write fixture"); + let decoded = decode_ogg(&ogg).expect("decode"); + assert_eq!(decoded.damaged_packets, 0); + assert_eq!(decoded.sample_rate, rate); + assert_same(&format!("our stream {rate} Hz {channels} ch q{quality}"), &decoded.channels, &ffmpeg_decode(&ffmpeg, &file, channels)); + } +} + +/// ffmpeg's own Vorbis encoder (stereo only) writes setups ours does not: coupled channels, residue +/// type 2, floor classes with subclasses and master books, two block sizes. The reference is +/// Symphonia, an independent decoder. ffmpeg's decoder agrees on the first channel but not on the +/// second of these streams, where it differs from both Symphonia and this decoder; the stream does +/// not show which reading it means (the channel comes back poorly, about 3 dB SNR, in all three), +/// so ffmpeg is compared on the first channel only. The setups ffmpeg's decoder does read the same +/// way as we do are covered, on both channels, in `vorbis_decode_synthetic.rs`. +#[test] +fn we_decode_ffmpegs_encoder_streams_like_symphonia() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("vorbis_decode"); + for (rate, bitrate) in [(44_100u32, "128k"), (48_000, "96k"), (22_050, "48k"), (32_000, "64k")] { + let channels = 2usize; + let pcm: Vec = { + let s = signal(rate, channels, rate as usize * 2 + 301); + (0..s[0].len()).flat_map(|i| s.iter().map(move |c| c[i])).collect() + }; + let raw = dir.join(format!("src_{rate}_{channels}.f32")); + std::fs::write(&raw, pcm.iter().flat_map(|v| v.to_le_bytes()).collect::>()).expect("write source"); + let file = dir.join(format!("ffmpeg_{rate}_{channels}_{bitrate}.ogg")); + let out = Command::new(&ffmpeg) + .args(["-v", "error", "-nostdin", "-y", "-f", "f32le", "-ar"]) + .arg(rate.to_string()) + .arg("-ac") + .arg(channels.to_string()) + .arg("-i") + .arg(&raw) + .args(["-c:a", "vorbis", "-strict", "-2", "-b:a", bitrate]) + .arg(&file) + .output() + .expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg could not encode {}: {}", file.display(), String::from_utf8_lossy(&out.stderr)); + let ogg = std::fs::read(&file).expect("read"); + let ours = decode_ogg(&ogg).expect("decode"); + assert_eq!(ours.damaged_packets, 0, "{}", file.display()); + let (_, symphonia) = craft_audio::decode(&ogg, Some("ogg")).expect("symphonia"); + let name = format!("ffmpeg-encoded {rate} Hz {bitrate}"); + assert_prefix(&name, &ours.channels, &symphonia.channels, false); + // The first channel also agrees with ffmpeg's decoder. + let theirs = ffmpeg_decode(&ffmpeg, &file, channels); + assert_prefix(&format!("{name} (channel 0 against ffmpeg)"), &ours.channels[..1], &theirs[..1], true); + } +} + +#[test] +fn packets_decode_one_at_a_time_to_the_file_result() { + let buf = AudioBuffer { sample_rate: 44_100, channels: signal(44_100, 2, 30_000) }; + let ogg = encode_ogg_vorbis(&buf, &OggVorbisOptions::default().with_quality(5.0)).expect("encode"); + let file = craft_media::ogg::open(ogg.as_slice()).expect("open"); + let s = &file.streams[file.stream_of(craft_media::ogg::Codec::Vorbis).expect("vorbis")]; + let mut dec = Decoder::new(&s.headers[0], &s.headers[1], &s.headers[2]).expect("decoder"); + assert_eq!((dec.identification().channels, dec.identification().sample_rate), (2, 44_100)); + let mut got: Vec> = vec![Vec::new(); 2]; + for i in 0..s.packets.len() { + let p = file.read_packet(ogg.as_slice(), 0, i).expect("packet"); + for (a, b) in got.iter_mut().zip(dec.decode_packet(&p).expect("packet decodes")) { + a.extend(b); + } + } + let whole = decode_ogg(&ogg).expect("file"); + for (a, b) in got.iter().zip(&whole.channels) { + assert!(a.len() >= b.len() && a[..b.len()] == b[..]); + } + // After a reset the next packet only primes the overlap again. + dec.reset(); + let p = file.read_packet(ogg.as_slice(), 0, 5).expect("packet"); + assert!(dec.decode_packet(&p).expect("decodes").iter().all(Vec::is_empty)); +} + +#[test] +fn the_round_trip_through_our_encoder_is_faithful() { + let src = signal(44_100, 2, 44_100); + let buf = AudioBuffer { sample_rate: 44_100, channels: src.clone() }; + let ogg = encode_ogg_vorbis(&buf, &OggVorbisOptions::default().with_quality(8.0)).expect("encode"); + let out = decode_ogg(&ogg).expect("decode"); + assert_eq!(out.channels[0].len(), src[0].len()); + let (mut sig, mut err) = (0f64, 0f64); + for (a, b) in src[0].iter().zip(&out.channels[0]) { + sig += f64::from(*a) * f64::from(*a); + err += f64::from(a - b) * f64::from(a - b); + } + assert!(10.0 * (sig / err).log10() > 15.0, "SNR {:.1} dB", 10.0 * (sig / err).log10()); +} + +/// A stream from libvorbis itself (the repository's `tone.ogg` fixture, made with ffmpeg's libvorbis +/// wrapper): mono, 8 kHz, the lowest quality. +#[test] +fn a_libvorbis_stream_decodes_like_ffmpeg() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/tone.ogg"); + let ogg = std::fs::read(&path).expect("fixture"); + let ours = decode_ogg(&ogg).expect("decode"); + assert_eq!((ours.sample_rate, ours.channels.len(), ours.damaged_packets), (8000, 1, 0)); + assert!(ours.comments.vendor.contains("Lavf") || ours.comments.vendor.contains("libVorbis"), "vendor {:?}", ours.comments.vendor); + assert!(ours.channels[0].iter().any(|s| s.abs() > 0.1), "the fixture is a tone"); + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + assert_prefix("libvorbis tone.ogg", &ours.channels, &ffmpeg_decode(&ffmpeg, &path, 1), false); +} + +#[test] +#[should_panic(expected = "non-finite oracle input or output")] +fn oracle_comparison_rejects_nan_output() { + assert_same("NaN output", &[vec![f32::NAN]], &[vec![0.0]]); +} + +#[test] +#[should_panic(expected = "non-finite oracle input or output")] +fn oracle_comparison_rejects_nan_reference() { + assert_same("NaN reference", &[vec![0.0]], &[vec![f32::NAN]]); +} diff --git a/crates/audio/tests/vorbis_decode_synthetic.rs b/crates/audio/tests/vorbis_decode_synthetic.rs new file mode 100644 index 000000000..46c48eced --- /dev/null +++ b/crates/audio/tests/vorbis_decode_synthetic.rs @@ -0,0 +1,384 @@ +//! Differential tests on streams built by hand: a setup header written here, with floor 0 and +//! floor 1 side by side, residues 0, 1 and 2, several submaps and channel coupling, followed by +//! random audio packets. Every packet of random bits is decodable, so the two decoders (ours and +//! ffmpeg's, the oracle; skipped when ffmpeg is absent, a failure with +//! `CRAFT_MEDIA_REQUIRE_ORACLES=1`) must return the same samples, and no encoder's habits narrow +//! what is exercised. Floor 0, residue 0 and multi-submap mappings are the parts no encoder here +//! writes. + +use craft_audio::vorbis::decoder::{Decoder, decode_ogg}; +use craft_media::ogg::{PageWriter, vorbis_comment}; +use std::process::Command; + +fn xorshift(seed: &mut u32) -> u32 { + *seed ^= *seed << 13; + *seed ^= *seed >> 17; + *seed ^= *seed << 5; + *seed +} + +/// A least-significant-bit-first bit writer. +#[derive(Default)] +struct W { + bytes: Vec, + bits: usize, +} + +impl W { + fn put(&mut self, v: u64, n: u32) { + for i in 0..n { + if self.bits.is_multiple_of(8) { + self.bytes.push(0); + } + let last = self.bytes.len() - 1; + self.bytes[last] |= (((v >> i) & 1) as u8) << (self.bits % 8); + self.bits += 1; + } + } + fn flag(&mut self, b: bool) { + self.put(u64::from(b), 1); + } +} + +fn float_bits(v: f64) -> u64 { + // The Vorbis float32 packing: sign, 10-bit exponent biased by 788, 21-bit mantissa. + if v == 0.0 { + return 0; + } + let (sign, a) = if v < 0.0 { (1u64 << 31, -v) } else { (0, v) }; + let mut exp = 0i32; + let mut m = a; + while m >= (1 << 21) as f64 { + m /= 2.0; + exp += 1; + } + while m < (1 << 20) as f64 { + m *= 2.0; + exp -= 1; + } + sign | (((exp + 788) as u64) << 21) | (m.round() as u64 & 0x1F_FFFF) +} + +/// A complete codebook: `entries` codewords all of length `len` (`entries == 2^len`), optionally +/// with a lookup table: `(type, minimum, delta, value_bits, multiplicands)`. +fn book(w: &mut W, dims: u32, entries: u32, len: u32, lookup: Option<(u32, f64, f64, u32, Vec)>) { + w.put(0x56_4342, 24); + w.put(u64::from(dims), 16); + w.put(u64::from(entries), 24); + w.flag(false); // not ordered + w.flag(false); // not sparse + for _ in 0..entries { + w.put(u64::from(len - 1), 5); + } + match lookup { + None => w.put(0, 4), + Some((ty, min, delta, bits, mult)) => { + w.put(u64::from(ty), 4); + w.put(float_bits(min), 32); + w.put(float_bits(delta), 32); + w.put(u64::from(bits - 1), 4); + w.flag(ty == 1); // sequence_p: cumulative for the floor 0 book + for m in mult { + w.put(u64::from(m), bits); + } + } + } +} + +struct Layout { + channels: u8, + /// The residue type of each of the two residues. + residue_types: [u32; 2], + /// The submap of each channel (0 or 1): submap 0 uses floor 0 and residue 0, submap 1 uses + /// floor 1 and residue 1. + mux: Vec, + coupling: Vec<(u8, u8)>, +} + +fn identification(channels: u8) -> Vec { + let mut w = W::default(); + w.put(1, 8); + for c in b"vorbis" { + w.put(u64::from(*c), 8); + } + w.put(0, 32); + w.put(u64::from(channels), 8); + w.put(16_000, 32); + w.put(0, 32); + w.put(0, 32); + w.put(0, 32); + w.put(8, 4); // short blocks: 256 + w.put(10, 4); // long blocks: 1024 + w.flag(true); + w.bytes +} + +fn setup(l: &Layout) -> Vec { + let mut w = W::default(); + w.put(5, 8); + for c in b"vorbis" { + w.put(u64::from(*c), 8); + } + // Books: 0 floor 0 vectors, 1 class book, 2 and 3 residue vectors, 4 floor 1 values. + w.put(4, 8); // five books + book(&mut w, 4, 16, 4, Some((1, 0.7, 0.2, 1, vec![0, 1]))); // lookup1_values(16, 4) = 2 + book(&mut w, 1, 4, 2, None); + book(&mut w, 2, 16, 4, Some((1, -0.4, 0.25, 2, vec![0, 1, 2, 3]))); // lookup1_values(16, 2) = 4 + book(&mut w, 4, 16, 4, Some((1, -0.3, 0.6, 1, vec![0, 1]))); + book(&mut w, 1, 128, 7, None); + // One time domain placeholder. + w.put(0, 6); + w.put(0, 16); + // Floors: 0 and 1. + w.put(1, 6); // two floors + w.put(0, 16); + w.put(8, 8); // order + w.put(16_000, 16); // rate + w.put(64, 16); // bark map size + w.put(8, 6); // amplitude bits + w.put(2, 8); // amplitude offset + w.put(0, 4); // one book + w.put(0, 8); + w.put(1, 16); + w.put(1, 5); // one partition + w.put(0, 4); // class 0 + w.put(2, 3); // dimension 3 + w.put(0, 2); // no subclasses + w.put(4 + 1, 8); // subclass book: book 4 (stored plus one) + w.put(1, 2); // multiplier 2 + w.put(8, 4); // rangebits + for x in [10, 40, 130] { + w.put(x, 8); + } + // Residues. + w.put(1, 6); // two residues + for ty in l.residue_types { + w.put(u64::from(ty), 16); + w.put(0, 24); // begin + w.put(if ty == 2 { 96 } else { 48 }, 24); // end + w.put(7, 24); // partition size 8 + w.put(3, 6); // four classifications + w.put(1, 8); // class book + for _ in 0..4 { + w.put(0b011, 3); // passes 0 and 1 + w.flag(false); + } + for class in 0..4 { + w.put(2 + (class % 2), 8); // pass 0 uses book 2 or 3 + w.put(3 - (class % 2), 8); // pass 1 uses book 3 or 2 + } + } + // One mapping, two submaps. + w.put(0, 6); + w.put(0, 16); + w.flag(true); + w.put(1, 4); // two submaps + w.flag(!l.coupling.is_empty()); + if !l.coupling.is_empty() { + w.put(l.coupling.len() as u64 - 1, 8); + let bits = if l.channels <= 1 { 0 } else { 8 - (l.channels - 1).leading_zeros() }; + for &(m, a) in &l.coupling { + w.put(u64::from(m), bits); + w.put(u64::from(a), bits); + } + } + w.put(0, 2); + for &m in &l.mux { + w.put(u64::from(m), 4); + } + for sub in 0..2u64 { + w.put(0, 8); + w.put(sub, 8); // floor + w.put(sub, 8); // residue + } + // Two modes over the one mapping. + w.put(1, 6); + for long in [false, true] { + w.flag(long); + w.put(0, 16); + w.put(0, 16); + w.put(0, 8); + } + w.flag(true); + w.bytes +} + +fn stream(l: &Layout, packets: usize, seed: &mut u32) -> Vec { + let mut pages = PageWriter::new(7); + let mut out = pages.header(&identification(l.channels)); + out.extend(pages.header(&vorbis_comment("synthetic", &[("TITLE", "hand built")]))); + out.extend(pages.header(&setup(l))); + // The window flags of a long block say whether its neighbours are long, so choose the block + // sizes first. + let longs: Vec = (0..packets).map(|_| !xorshift(seed).is_multiple_of(3)).collect(); + let mut granule = 0i64; + for i in 0..packets { + let long = longs[i]; + // Packet type 0, the mode bit, and for a long block the two neighbour flags. + let prev = i == 0 || longs[i - 1]; + let next = i + 1 >= packets || longs[i + 1]; + let mut w = W::default(); + w.flag(false); + w.flag(long); + if long { + w.flag(prev); + w.flag(next); + } + // Floor 0 needs a codebook number that exists, which random bits would not give, so the + // channels that use it (the first ones) are written properly: an amplitude, book 0 and two + // codewords of its vectors (a full tree of 4-bit codes: the code is the entry number). + for _ in 0..l.mux.iter().take_while(|&&m| m == 0).count() { + w.put(1 + u64::from(xorshift(seed)) % 24, 8); + w.put(0, 1); + for _ in 0..2 { + let entry = xorshift(seed) % 16; + for bit in (0..4).rev() { + w.put(u64::from(entry >> bit) & 1, 1); + } + } + } + // The rest is random bits, enough that no residue runs out of packet. + let mut p = w.bytes; + let fixed = p.len(); + p.extend((0..200 + xorshift(seed) as usize % 200).map(|_| xorshift(seed) as u8)); + let _ = fixed; + // The bits after the fixed fields start mid-byte: the last fixed byte keeps its own bits and + // takes random ones above them. + let used = w.bits % 8; + if used != 0 { + let last = fixed - 1; + p[last] |= (xorshift(seed) as u8) << used; + } + if i > 0 { + let size = |long: bool| if long { 1024 } else { 256 }; + granule += (size(longs[i - 1]) / 4 + size(long) / 4) as i64; + } + out.extend(pages.packet(&p, granule)); + } + out.extend(pages.finish(None)); + out +} + +/// `tolerance`: the largest difference from ffmpeg, as a fraction of the peak output. A floor 0 +/// curve is an exponential of a quotient that random coefficients can make very large, so where +/// two floors meet in one stream (ffmpeg computes in single precision, we in double) the results +/// agree only to about a thousandth of the peak. +fn run(name: &str, l: &Layout, seed: u32, tolerance: f32) { + let mut s = seed; + let ogg = stream(l, 40, &mut s); + // Packet by packet our decoder must accept every one. + let file = craft_media::ogg::open(ogg.as_slice()).expect("open"); + let st = &file.streams[0]; + let mut dec = Decoder::new(&st.headers[0], &st.headers[1], &st.headers[2]).expect("setup decodes"); + let mut total = vec![Vec::new(); usize::from(l.channels)]; + for i in 0..st.packets.len() { + let p = file.read_packet(ogg.as_slice(), 0, i).expect("packet"); + let pcm = dec.decode_packet(&p).unwrap_or_else(|e| panic!("{name}: packet {i}: {e}")); + for (t, c) in total.iter_mut().zip(pcm) { + t.extend(c); + } + } + let expected = usize::try_from(st.last_granule.expect("generated final granule")).expect("nonnegative granule"); + for channel in &total { + assert_eq!(channel.len(), expected, "{name}: decoded sample count"); + assert!(channel.iter().all(|v| v.is_finite()), "{name}: non-finite output"); + } + let whole = decode_ogg(&ogg).expect("whole file"); + assert_eq!(whole.channels, total, "{name}: packet and file decoding differ"); + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("vorbis_synthetic"); + let path = dir.join(format!("{name}.ogg")); + std::fs::write(&path, &ogg).expect("write fixture"); + let out = Command::new(&ffmpeg) + .args(["-v", "error", "-nostdin", "-i"]) + .arg(&path) + .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .output() + .expect("run ffmpeg"); + assert!(out.status.success(), "{name}: ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); + let all: Vec = out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(); + let ch = usize::from(l.channels); + let theirs: Vec> = (0..ch).map(|c| all.iter().skip(c).step_by(ch).copied().collect()).collect(); + assert!(theirs.iter().flatten().all(|v| v.is_finite()), "{name}: non-finite ffmpeg output"); + for channel in &theirs { + assert!(channel.len() >= expected, "{name}: ffmpeg returned fewer than the expected samples"); + } + // ffmpeg puts the channels of surround streams in its own order, so each of ours is matched + // with the channel of theirs it agrees with best, and every one of theirs is used once. + let mut used = vec![false; ch]; + #[allow(clippy::needless_range_loop)] + for c in 0..ch { + let mut best: Option<(usize, f32, f32)> = None; + for (k, t) in theirs.iter().enumerate().filter(|(k, _)| !used[*k]) { + let n = total[c].len().min(t.len()); + assert!(n > 1000, "{name}: only {n} samples to compare"); + let scale = total[c][..n].iter().fold(1e-3f32, |m, v| m.max(v.abs())); + let worst = (0..n).map(|i| (total[c][i] - t[i]).abs()).fold(0f32, f32::max); + if best.is_none_or(|(_, w, sc)| worst / scale < w / sc) { + best = Some((k, worst, scale)); + } + } + let (k, worst, scale) = best.expect("a free channel"); + used[k] = true; + assert!(worst <= tolerance * scale + 1e-5, "{name}: channel {c} differs from ffmpeg's channel {k} by {worst} (peak {scale})"); + } +} + +#[test] +fn mono_floor_zero_and_residue_zero() { + run("mono_f0_r0", &Layout { channels: 1, residue_types: [0, 0], mux: vec![0], coupling: vec![] }, 11, 1e-4); +} + +#[test] +fn mono_floor_one_and_residue_one() { + run("mono_f1_r1", &Layout { channels: 1, residue_types: [1, 1], mux: vec![1], coupling: vec![] }, 12, 1e-4); +} + +#[test] +fn two_submaps_floor_zero_and_one() { + run("stereo_mixed", &Layout { channels: 2, residue_types: [0, 1], mux: vec![0, 1], coupling: vec![] }, 13, 3e-3); +} + +#[test] +fn coupled_stereo_residue_two() { + run("stereo_coupled_r2", &Layout { channels: 2, residue_types: [2, 2], mux: vec![1, 1], coupling: vec![(0, 1)] }, 14, 1e-4); +} + +#[test] +fn six_channels_with_coupling_and_submaps() { + let l = Layout { channels: 6, residue_types: [1, 2], mux: vec![0, 0, 0, 1, 1, 1], coupling: vec![(0, 3), (1, 2), (4, 5)] }; + run("six", &l, 15, 3e-3); +} + +#[test] +fn mono_floor_one_and_residue_zero() { + run("mono_f1_r0", &Layout { channels: 1, residue_types: [0, 0], mux: vec![1], coupling: vec![] }, 16, 1e-4); +} + +#[test] +fn mono_floor_zero_and_residue_one() { + run("mono_f0_r1", &Layout { channels: 1, residue_types: [1, 1], mux: vec![0], coupling: vec![] }, 17, 1e-4); +} + +/// A packet that names a floor 0 codebook that does not exist cannot be decoded (§6.2.2); the +/// decoder says so and the stream goes on with the next packet. +#[test] +fn a_floor_zero_codebook_that_does_not_exist_is_a_packet_error() { + let l = Layout { channels: 1, residue_types: [1, 1], mux: vec![0], coupling: vec![] }; + let mut seed = 5u32; + let ogg = stream(&l, 6, &mut seed); + let file = craft_media::ogg::open(ogg.as_slice()).expect("open"); + let st = &file.streams[0]; + let mut dec = Decoder::new(&st.headers[0], &st.headers[1], &st.headers[2]).expect("decoder"); + let good = file.read_packet(ogg.as_slice(), 0, 0).expect("packet"); + assert!(dec.decode_packet(&good).is_ok()); + // A short block: type 0, mode 0, then the 8 amplitude bits, then book number 1 (only 0 exists). + let mut w = W::default(); + w.flag(false); + w.flag(false); + w.put(9, 8); + w.put(1, 1); + w.put(0, 64); + assert!(matches!(dec.decode_packet(&w.bytes), Err(craft_audio::vorbis::decoder::Error::Packet(_)))); + assert!(dec.decode_packet(&good).is_ok(), "the decoder carries on"); +} 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/captions/Cargo.toml b/crates/captions/Cargo.toml index df665336d..1136f55f9 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -10,6 +10,11 @@ repository.workspace = true [lints] workspace = true +[features] +default = [] +# MP4 timed text (3GPP TS 26.245 / mov_text / tx3g) sample codec. +mov-text = [] + [dependencies] craft-timeline = { workspace = true } craft-xml = { workspace = true } @@ -19,3 +24,7 @@ thiserror = { workspace = true } proptest = { workspace = true } # A second XML reader for the tests: checks of written TTML, and the comparison in tests/it/ttml_xml_views.rs. roxmltree = "0.21" +# ffmpeg as the reference for the ASS tests (tests/it/ass.rs). +craft-media-testkit = { workspace = true } +# craft-media isobmff for mov_text oracle demuxing/muxing tests. +craft-media = { workspace = true, features = ["isobmff"] } diff --git a/crates/captions/README.md b/crates/captions/README.md index 0676d1d72..b2f6a195f 100644 --- a/crates/captions/README.md +++ b/crates/captions/README.md @@ -27,6 +27,10 @@ assert!(scc.starts_with(b"Scenarist_SCC V1.0")); and the SMPTE ST 334-2 caption distribution packet. - `plain_text` strips inline tags and decodes the common entities, for display or for formats without markup. +- Optional feature `mov-text` provides MP4 Timed Text (`mov_text` / `tx3g`, 3GPP TS 26.245) + sample decoding, encoding, modifier box parsing (`styl`, `hlit`, `hclr`, `krok`, `dlay`, `href`, + `tbox`, `blnk`, `wrap`), and `Tx3gConfig` sample entry parsing/writing for ISO BMFF (`.mp4`) and + QuickTime (`.mov`) subtitle tracks. ## Time @@ -55,6 +59,7 @@ lists at most 20 characters per stream. | EBU STL `.stl` | yes | yes | EBU Tech 3264-E: GSI block + 128-byte TTI blocks, `STL25.01` (25 fps) or `STL30.01` (read/written as 29.97 fps, non-drop labels), ISO/IEC 6937 Latin text (accents as diacritic + letter), italics / underline codes as `` / ``, extension blocks for long subtitles, start-of-programme (TCP) subtracted. | | TTML `.ttml` (IMSC1) | yes | yes | Writes the IMSC1 Text profile (TTML2 namespaces) with the document's language as `xml:lang` (read back on import): `

` per cue, `
`, styled ``s for `` / `` / ``, `ttm:agent` speakers, exact frame times (`123f`) at the sequence rate. Reads any TTML (TTML1, TTML2, the 2006 `ttaf1` drafts): clock / frame / offset / tick times, `dur`, nested time containers (`body` / `div` begins offset and ends clip their contents; `seq` containers are read as `par` with a warning), timed spans, referenced styles. | | DFXP `.dfxp` | yes | yes | TTML1 with the DFXP presentation profile; clock times in milliseconds (frame-exact after `snap_to_frames`). | +| ASS / SSA `.ass`, `.ssa` | yes | yes (ASS v4+) | The `[Events]` section: `Dialogue:` lines through the file's `Format:` line, `Name` as the speaker, `\N`, `\n`, `\h` and the `\i`, `\b`, `\u` override tags kept (as ``, ``, ``); other override tags and drawing lines are dropped. Times are centiseconds. Written files have one `Default` style. | All cue times are exact `Tick`s. Milliseconds convert exactly (1 ms = 254 016 000 ticks); SCC frames map through `FrameRate::FPS_29_97`. `Document::snap_to_frames` snaps cues to a frame grid and diff --git a/crates/captions/src/ass.rs b/crates/captions/src/ass.rs new file mode 100644 index 000000000..2d0a1df55 --- /dev/null +++ b/crates/captions/src/ass.rs @@ -0,0 +1,244 @@ +//! Advanced SubStation Alpha and SubStation Alpha (`.ass`, `.ssa`). +//! +//! Reading takes the `[Events]` section: its `Format:` line gives the field order (ASS v4+ and SSA +//! v4 differ in the first field only), each `Dialogue:` line becomes a cue; `Comment:` lines and +//! the other sections are skipped. A cue gets the `Name` field as its speaker. The text keeps what +//! the neutral model can show: `\N` and `\n` become a line break and a space, `\h` a no-break +//! space, and the override tags `\i`, `\b` and `\u` become ``, `` and ``. Every other +//! override tag (colours, fonts, positions, karaoke, animation) is dropped, and a line that draws +//! vector shapes (`\p1`) is skipped with a warning. +//! +//! Writing gives a minimal ASS v4+ file: one `Default` style, one `Dialogue:` line per cue with +//! times to the centisecond. Braces in the text, which ASS reads as override blocks, are written +//! as the full-width `{` and `}`. + +use crate::time::{TICKS_PER_SECOND, Tick}; +use crate::{Cue, Document, Error, Result}; + +const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100; + +/// `H:MM:SS.cc`, the form SSA and ASS use (any number of fraction digits is read). +fn parse_time(s: &str) -> Option { + let s = s.trim(); + let (hms, frac) = s.split_once('.').unwrap_or((s, "")); + let mut parts = hms.split(':'); + let (h, m, sec) = (parts.next()?, parts.next()?, parts.next()?); + if parts.next().is_some() { + return None; + } + let num = |p: &str| -> Option { (!p.is_empty() && p.len() <= 9 && p.bytes().all(|b| b.is_ascii_digit())).then(|| p.parse().ok()).flatten() }; + let (h, m, sec) = (num(h)?, num(m)?, num(sec)?); + if m >= 60 || sec >= 60 || h > 9999 { + return None; + } + let mut ticks = ((h * 60 + m) * 60 + sec) * TICKS_PER_SECOND; + if !frac.is_empty() { + if frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let d: i64 = frac.parse().ok()?; + ticks += (i128::from(d) * i128::from(TICKS_PER_SECOND) / 10i128.pow(frac.len() as u32)) as i64; + } + Some(Tick(ticks)) +} + +fn format_time(t: Tick) -> String { + let cs = (i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS); + let (h, m, s, c) = (cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100); + format!("{h}:{m:02}:{s:02}.{c:02}") +} + +/// The Text field of a Dialogue line as cue text; `None` when the line draws shapes. +fn convert_text(raw: &str) -> Option { + let mut out = String::new(); + // Open ``, ``, `` in the order they were opened. + let mut open: Vec = Vec::new(); + let mut chars = raw.chars().peekable(); + let mut drawing = false; + let mut dropped_drawing = false; + while let Some(c) = chars.next() { + match c { + '{' => { + let mut block = String::new(); + let mut closed = false; + for b in chars.by_ref() { + if b == '}' { + closed = true; + break; + } + block.push(b); + } + if !closed { + // An unterminated block is literal text. + out.push('{'); + out.push_str(&block); + continue; + } + for tag in block.split('\\').skip(1) { + let tag = tag.trim_end(); + let (name, val) = tag.split_at(tag.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(tag.len())); + match name { + "i" | "b" | "u" => { + let letter = name.chars().next().unwrap_or('i'); + let on = val.trim() != "0"; + if on && !open.contains(&letter) { + open.push(letter); + out.push_str(&format!("<{letter}>")); + } else if !on && open.contains(&letter) { + // Close back to it, reopening what was opened after. + let at = open.iter().position(|&o| o == letter).unwrap_or(0); + let after: Vec = open.split_off(at + 1); + for o in after.iter().rev() { + out.push_str(&format!("")); + } + open.pop(); + out.push_str(&format!("")); + for o in after { + open.push(o); + out.push_str(&format!("<{o}>")); + } + } + } + "p" => drawing = val.trim().parse::().unwrap_or(0) != 0, + _ => {} + } + } + } + '\\' => match chars.peek() { + Some('N') => { + chars.next(); + out.push('\n'); + } + Some('n') => { + chars.next(); + out.push(' '); + } + Some('h') => { + chars.next(); + out.push('\u{a0}'); + } + _ => out.push('\\'), + }, + c => { + if drawing { + dropped_drawing = true; + } else { + out.push(c); + } + } + } + } + if dropped_drawing && out.trim().is_empty() { + return None; + } + while let Some(o) = open.pop() { + out.push_str(&format!("")); + } + Some(out) +} + +pub fn parse(text: &str) -> Result { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let mut doc = Document::default(); + let mut in_events = false; + let mut saw_events = false; + // Column of each field in a Dialogue line. + let mut cols: Vec = + ["layer", "start", "end", "style", "name", "marginl", "marginr", "marginv", "effect", "text"].map(String::from).to_vec(); + let mut drawings = 0usize; + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.starts_with('[') && line.ends_with(']') { + in_events = line.eq_ignore_ascii_case("[events]"); + saw_events |= in_events; + continue; + } + if !in_events { + continue; + } + let Some((key, rest)) = line.split_once(':') else { continue }; + let rest = rest.trim_start(); + match key.trim().to_ascii_lowercase().as_str() { + "format" => cols = rest.split(',').map(|f| f.trim().to_ascii_lowercase()).collect(), + "dialogue" => { + // The last column (Text) keeps its commas. + let fields: Vec<&str> = rest.splitn(cols.len(), ',').collect(); + let get = |name: &str| cols.iter().position(|c| c == name).and_then(|i| fields.get(i)).copied(); + let (Some(start), Some(end), Some(raw)) = (get("start").and_then(parse_time), get("end").and_then(parse_time), get("text")) else { + doc.warnings.push(format!("line {}: not a Dialogue line this reader understands", n + 1)); + continue; + }; + let Some(text) = convert_text(raw) else { + drawings += 1; + continue; + }; + let name = get("name").map(str::trim).filter(|s| !s.is_empty()); + doc.cues.push(Cue { start, end, text, speaker: name.map(str::to_string), ..Default::default() }); + } + _ => {} + } + } + if !saw_events { + return Err(Error::NotFormat("ASS")); + } + if drawings > 0 { + doc.warnings.push(format!("{drawings} vector drawing line(s) were skipped")); + } + Ok(doc) +} + +fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 8); + let mut rest = text; + while !rest.is_empty() { + if let Some(r) = rest.strip_prefix("\r\n") { + out.push_str("\\N"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\i1}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\i0}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\b1}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\b0}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\u1}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\u0}"); + rest = r; + } else if let Some(c) = rest.chars().next() { + match c { + '\n' | '\r' => out.push_str("\\N"), + // Empty override block separates a literal slash from N/n/h. + '\\' => out.push_str("\\{}"), + '{' => out.push('\u{ff5b}'), + '}' => out.push('\u{ff5d}'), + '\u{a0}' => out.push_str("\\h"), + c => out.push(c), + } + rest = &rest[c.len_utf8()..]; + } + } + out +} + +pub fn write(doc: &Document) -> String { + let mut out = String::from( + "[Script Info]\n; Written by craft-captions\nScriptType: v4.00+\nWrapStyle: 0\nScaledBorderAndShadow: yes\nPlayResX: 384\nPlayResY: 288\n\n\ + [V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n\ + Style: Default,Arial,16,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,1\n\n\ + [Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n", + ); + for c in &doc.cues { + // A comma in the Name field would shift the columns; the other fields are fixed text. + let name = c.speaker.as_deref().unwrap_or("").replace([',', '\n', '\r'], " "); + out.push_str(&format!("Dialogue: 0,{},{},Default,{},0,0,0,,{}\n", format_time(c.start), format_time(c.end), name, escape(&c.text))); + } + out +} diff --git a/crates/captions/src/jacosub.rs b/crates/captions/src/jacosub.rs new file mode 100644 index 000000000..30233b6f1 --- /dev/null +++ b/crates/captions/src/jacosub.rs @@ -0,0 +1,242 @@ +//! JACOsub (`.jss`, `.js`): multi-feature scriptable subtitle format. +//! +//! ```text +//! # JACOsub file +//! #TimeRes 100 +//! 0:00:01.00 0:00:03.00 D0 First line\nsecond line +//! ``` +//! +//! Lines beginning with `#` are comments or header directives. Timed caption lines begin with +//! `START STOP [DIRECTIVE] Text`, where timestamps are `H:MM:SS.FF` (or `@units`) relative to +//! the declared `#TimeRes` (default 30). Inside the text, `\n` represents a newline. + +use crate::text::{escape_markup, ms_to_tick, plain_text, tick_to_ms}; +use crate::{Cue, Document, Error, Result}; + +/// Parse a JACOsub timestamp `H:MM:SS.FF` or `@units` into milliseconds. +pub(crate) fn parse_time(s: &str, time_res: i64) -> Option { + let s = s.trim(); + if s.is_empty() { + return None; + } + + if let Some(units_str) = s.strip_prefix('@') { + let units: i64 = units_str.trim().parse().ok()?; + let time_res = if time_res > 0 { time_res } else { 30 }; + return Some(units.saturating_mul(1000) / time_res); + } + + let (h_str, rest) = s.split_once(':')?; + let (m_str, rest) = rest.split_once(':')?; + let (s_str, f_str) = rest.split_once('.')?; + + let h: i64 = h_str.trim().parse().ok()?; + let m: i64 = m_str.trim().parse().ok()?; + let sec: i64 = s_str.trim().parse().ok()?; + let frac: i64 = f_str.trim().parse().ok()?; + + let time_res = if time_res > 0 { time_res } else { 30 }; + let frac_ms = frac.saturating_mul(1000) / time_res; + + let total_secs = h.saturating_mul(3600).saturating_add(m.saturating_mul(60)).saturating_add(sec); + Some(total_secs.saturating_mul(1000).saturating_add(frac_ms)) +} + +/// Format milliseconds into JACOsub timestamp string `H:MM:SS.cc` (at 100 centiseconds/sec). +pub(crate) fn format_time(ms: i64) -> String { + let ms = ms.max(0); + let total_secs = ms / 1000; + let centis = (ms % 1000) / 10; + let hours = total_secs / 3600; + let mins = (total_secs % 3600) / 60; + let secs = total_secs % 60; + + format!("{hours}:{mins:02}:{secs:02}.{centis:02}") +} + +/// Check if a line is a JACOsub timed caption line: `H:MM:SS.FF H:MM:SS.FF ...` or `@units @units ...`. +pub(crate) fn is_timed_line(line: &str) -> bool { + let line = line.trim(); + if line.starts_with('#') { + return false; + } + let mut parts = line.split_whitespace(); + let Some(t0) = parts.next() else { return false }; + let Some(t1) = parts.next() else { return false }; + (t0.contains(':') && t0.contains('.') && t1.contains(':') && t1.contains('.')) || (t0.starts_with('@') && t1.starts_with('@')) +} + +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut time_res: i64 = 30; // standard default + let mut shift_ms: i64 = 0; + let mut found = false; + + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + + if let Some(cmd) = line.strip_prefix('#') { + let cmd_lower = cmd.to_ascii_lowercase(); + if cmd_lower.starts_with("timeres") || cmd_lower.starts_with('t') { + let parts: Vec<&str> = cmd.split_whitespace().collect(); + if parts.len() >= 2 + && let Ok(res) = parts[1].parse::() + && res > 0 + { + time_res = res; + } + } else if cmd_lower.starts_with("shift") || cmd_lower.starts_with('s') { + let parts: Vec<&str> = cmd.split_whitespace().collect(); + if parts.len() >= 2 { + let s_val = parts[1].trim(); + let (neg, s_raw) = if let Some(stripped) = s_val.strip_prefix('-') { + (true, stripped) + } else if let Some(stripped) = s_val.strip_prefix('+') { + (false, stripped) + } else { + (false, s_val) + }; + if let Some(ms) = parse_time(s_raw, time_res) { + shift_ms = if neg { -ms } else { ms }; + } + } + } + continue; + } + + if !is_timed_line(line) { + continue; + } + + let mut parts = line.split_whitespace(); + let Some(start_str) = parts.next() else { continue }; + let Some(end_str) = parts.next() else { continue }; + + let start_ms = match parse_time(start_str, time_res) { + Some(ms) => ms.saturating_add(shift_ms).max(0), + None => { + doc.warnings.push(format!("line {}: invalid start timestamp, skipped", n + 1)); + continue; + } + }; + let end_ms = match parse_time(end_str, time_res) { + Some(ms) => ms.saturating_add(shift_ms).max(0), + None => { + doc.warnings.push(format!("line {}: invalid end timestamp, skipped", n + 1)); + continue; + } + }; + + found = true; + + // Skip to after the end timestamp in the original line to preserve exact spaces + let after_end_pos = match line.find(end_str) { + Some(idx) => idx + end_str.len(), + None => continue, + }; + let remainder = &line[after_end_pos..]; + let trimmed_rem = remainder.trim_start(); + + // Check if there is a directive prefix: either [Directive] or a single non-space word starting with D + let text_part = if let Some(stripped) = trimmed_rem.strip_prefix('[') { + match stripped.find(']') { + Some(end_bracket) => stripped[end_bracket + 1..].trim_start(), + None => trimmed_rem, + } + } else if let Some(space_idx) = trimmed_rem.find(' ') { + let first_token = &trimmed_rem[..space_idx]; + if first_token.starts_with('D') && first_token[1..].chars().all(|c| c.is_ascii_digit()) { + trimmed_rem[space_idx + 1..].trim_start() + } else { + trimmed_rem + } + } else { + trimmed_rem + }; + + // Text parsing: `\n` represents newline + let raw_lines: Vec<&str> = text_part.split(r"\n").map(str::trim).filter(|l| !l.is_empty()).collect(); + let lines: Vec = raw_lines.into_iter().map(escape_markup).collect(); + + let start = ms_to_tick(start_ms); + let end = ms_to_tick(end_ms); + if end <= start || lines.is_empty() { + doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1)); + continue; + } + + doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() }); + } + + if !found && !text.trim().is_empty() { + return Err(Error::NotFormat("JACOsub")); + } + + Ok(doc) +} + +pub fn write(doc: &Document) -> String { + let mut out = String::new(); + out.push_str("# JACOsub file\n"); + out.push_str("#TimeRes 100\n\n"); + + for c in &doc.cues { + let start_ms = tick_to_ms(c.start); + let end_ms = tick_to_ms(c.end).max(start_ms + 10); + let raw_lines = plain_text(&c.text); + let lines: Vec<&str> = raw_lines.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); + + if !lines.is_empty() { + let text = lines.join(r"\n"); + out.push_str(&format!("{} {} D0 {}\n", format_time(start_ms), format_time(end_ms), text)); + } + } + + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_write_roundtrip() { + let jss = "# JACOsub file\n#TimeRes 100\n\n0:00:01.00 0:00:03.00 D0 First line\\nsecond line\n0:00:04.50 0:00:06.00 D0 Second cue\n"; + let doc = parse(jss).expect("parse"); + assert_eq!(doc.cues.len(), 2); + assert_eq!(doc.cues[0].start, ms_to_tick(1000)); + assert_eq!(doc.cues[0].end, ms_to_tick(3000)); + assert_eq!(doc.cues[0].text, "First line\nsecond line"); + assert_eq!(doc.cues[1].start, ms_to_tick(4500)); + assert_eq!(doc.cues[1].end, ms_to_tick(6000)); + assert_eq!(doc.cues[1].text, "Second cue"); + + let written = write(&doc); + assert_eq!(written, jss); + } + + #[test] + fn parse_bracketed_directive() { + let jss = "#TimeRes 100\n0:00:01.00 0:00:03.00 [Style1] Bracketed style text\n"; + let doc = parse(jss).expect("parse"); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].text, "Bracketed style text"); + } + + #[test] + fn negative_shift_under_one_hour() { + let jss = "#TimeRes 100\n#Shift -0:00:01.00\n0:00:02.00 0:00:04.00 D0 Shifted line\n"; + let doc = parse(jss).expect("parse"); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].start, ms_to_tick(1000)); + assert_eq!(doc.cues[0].end, ms_to_tick(3000)); + } + + #[test] + fn rejects_non_jacosub() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nHello\n").is_err()); + } +} diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index 0ba9f2ba5..2d0cf90c1 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -4,7 +4,7 @@ //! - **Files:** [SubRip](srt) (`.srt`), [WebVTT](vtt) (`.vtt`), [Scenarist SCC](scc) (`.scc`, //! CEA-608 pop-on, roll-up and paint-on on read; pop-on on write), [MacCaption MCC](mcc) //! (`.mcc`, SMPTE ST 334-2 packets with CEA-608 and CEA-708), [EBU STL](stl) (`.stl`, EBU -//! Tech 3264) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a +//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a //! [`Document`] of [`Cue`]s and write back. Readers are forgiving (BOM, UTF-16, Windows-1252 //! fallback, CRLF/CR, missing SRT indexes, `,` or `.` milliseconds, missing hours, no blank //! line between cues); writers are strict. WebVTT cue identifiers, cue settings, `` @@ -32,8 +32,14 @@ #[doc = include_str!("../README.md")] struct ReadmeExamples; +pub mod ass; pub mod cea608; +pub mod jacosub; pub mod mcc; +#[cfg(feature = "mov-text")] +pub mod mov_text; +pub mod pjs; +pub mod realtext; pub mod scc; pub mod srt; pub mod stl; @@ -69,10 +75,30 @@ pub enum Format { Ttml, /// DFXP (TTML1). Dfxp, + /// Advanced SubStation Alpha (also reads SubStation Alpha). + Ass, + /// Phoenix Japanimation Society (PJS) subtitles. + Pjs, + /// RealText streaming timed text markup. + RealText, + /// JACOsub scriptable subtitles. + JacoSub, } impl Format { - pub const ALL: [Format; 7] = [Format::Srt, Format::WebVtt, Format::Scc, Format::Mcc, Format::Stl, Format::Ttml, Format::Dfxp]; + pub const ALL: [Format; 11] = [ + Format::Srt, + Format::WebVtt, + Format::Scc, + Format::Mcc, + Format::Stl, + Format::Ttml, + Format::Dfxp, + Format::Ass, + Format::Pjs, + Format::RealText, + Format::JacoSub, + ]; pub fn name(self) -> &'static str { match self { Format::Srt => "SubRip (SRT)", @@ -82,6 +108,10 @@ impl Format { Format::Stl => "EBU STL", Format::Ttml => "TTML (IMSC1)", Format::Dfxp => "DFXP (TTML1)", + Format::Ass => "Advanced SubStation Alpha (ASS)", + Format::Pjs => "PJS", + Format::RealText => "RealText", + Format::JacoSub => "JACOsub", } } pub fn extension(self) -> &'static str { @@ -93,6 +123,10 @@ impl Format { Format::Stl => "stl", Format::Ttml => "ttml", Format::Dfxp => "dfxp", + Format::Ass => "ass", + Format::Pjs => "pjs", + Format::RealText => "rt", + Format::JacoSub => "jss", } } pub fn from_name(s: &str) -> Option { @@ -104,6 +138,10 @@ impl Format { "stl" | "ebu-stl" | "ebustl" | "ebu" => Some(Format::Stl), "ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml), "dfxp" => Some(Format::Dfxp), + "ass" | "ssa" => Some(Format::Ass), + "pjs" => Some(Format::Pjs), + "rt" | "realtext" => Some(Format::RealText), + "jss" | "js" | "jacosub" => Some(Format::JacoSub), _ => None, } } @@ -251,6 +289,19 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if head.starts_with("File Format=MacCaption_MCC") { return Some(Format::Mcc); } + if head.starts_with("[Script Info]") { + return Some(Format::Ass); + } + if realtext::is_realtext(head) { + return Some(Format::RealText); + } + let first_lines: Vec<&str> = head.lines().map(str::trim).filter(|l| !l.is_empty()).take(3).collect(); + if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) { + return Some(Format::Pjs); + } + if first_lines.iter().any(|l| jacosub::is_timed_line(l)) || (head.starts_with('#') && (head.contains("TimeRes") || head.contains("#T"))) { + return Some(Format::JacoSub); + } let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase()); if (head.starts_with('<') && (head.contains("") || head.contains(":tt "))) && (head.contains("ns/ttml") || head.contains("ttaf1")) @@ -262,7 +313,7 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { match ext.as_deref() { Some("srt") if has_arrow_timing || head.is_empty() => Some(Format::Srt), Some("vtt") if has_arrow_timing => Some(Format::WebVtt), - Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml") => None, + Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "pjs" | "rt" | "jss" | "js") => None, _ if has_arrow_timing => Some(Format::Srt), _ => None, } @@ -296,6 +347,10 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result { Format::Scc => scc::parse(&text), Format::Mcc => mcc::parse(&text), Format::Ttml | Format::Dfxp => ttml::parse(&text), + Format::Ass => ass::parse(&text), + Format::Pjs => pjs::parse(&text), + Format::RealText => realtext::parse(&text), + Format::JacoSub => jacosub::parse(&text), Format::Stl => stl::parse(bytes), } } @@ -333,6 +388,10 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec { Format::Stl => stl::write(doc, opts.rate, opts.program), Format::Ttml => ttml::write(doc, ttml::Flavor::Imsc1, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), Format::Dfxp => ttml::write(doc, ttml::Flavor::Dfxp, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), + Format::Ass => ass::write(doc).into_bytes(), + Format::Pjs => pjs::write(doc).into_bytes(), + Format::RealText => realtext::write(doc).into_bytes(), + Format::JacoSub => jacosub::write(doc).into_bytes(), } } diff --git a/crates/captions/src/mov_text.rs b/crates/captions/src/mov_text.rs new file mode 100644 index 000000000..d1a3ce2a9 --- /dev/null +++ b/crates/captions/src/mov_text.rs @@ -0,0 +1,871 @@ +//! MP4 Timed Text (`mov_text` / `tx3g`, 3GPP TS 26.245). +//! +//! A clean-room reader and writer for 3GPP Timed Text subtitle samples and sample entry +//! configurations (`tx3g`), as carried in ISO BMFF (`.mp4`) and QuickTime (`.mov`) files. +//! +//! ## Sample Structure +//! +//! A timed text sample consists of: +//! - A 16-bit big-endian text length. +//! - The text string bytes (UTF-8, or UTF-16 with BOM). +//! - Zero or more modifier boxes: +//! - `styl`: Character style runs (bold, italic, underline, font ID, font size, text color). +//! - `hlit`: Highlighted character range. +//! - `hclr`: Highlight color (RGBA). +//! - `krok`: Karaoke highlight timing and character spans. +//! - `dlay`: Scroll delay in track-timescale ticks. +//! - `href`: Hypertext link URL and alt text. +//! - `tbox`: Text box override coordinates (`top, left, bottom, right`). +//! - `blnk`: Blinking text character range. +//! - `twrp`: Text wrap flag (0 = no wrap, 1 = automatic soft wrap). +//! +//! ## Style Flags +//! +//! Style flags in `styl` records: +//! - `0x01`: Bold (`...`) +//! - `0x02`: Italic (`...`) +//! - `0x04`: Underline (`...`) + +use crate::time::Tick; +use crate::{Cue, Document, TICKS_PER_SECOND}; + +/// What went wrong reading or writing timed text. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The input slice is shorter than the declared field or box size. + #[error("truncated timed text data")] + Truncated, + /// The text payload is not valid UTF-8 and contains no valid UTF-16 BOM. + #[error("invalid text encoding in timed text sample")] + InvalidText, + /// The text exceeds the 16-bit length prefix (65,535 bytes). + #[error("timed text string exceeds 65535 bytes: {0}")] + TextTooLong(usize), + /// A modifier box header has an invalid size (< 8). + #[error("invalid modifier box size: {0}")] + InvalidBox(&'static str), +} + +/// `Result` alias for timed text operations. +pub type Result = std::result::Result; + +/// Face style flag: Bold (`0x01`). +pub const STYLE_FLAG_BOLD: u8 = 0x01; +/// Face style flag: Italic (`0x02`). +pub const STYLE_FLAG_ITALIC: u8 = 0x02; +/// Face style flag: Underline (`0x04`). +pub const STYLE_FLAG_UNDERLINE: u8 = 0x04; + +/// A character styling record within a `styl` box. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StyleRecord { + /// 0-indexed start character index (inclusive, measured in Unicode scalar values). + pub start_char: u16, + /// 0-indexed end character index (exclusive, measured in Unicode scalar values). + pub end_char: u16, + /// 16-bit font ID matching an entry in the sample description font table (`ftab`). + pub font_id: u16, + /// Face style flags: bit 0 = bold, bit 1 = italic, bit 2 = underline. + pub face_style_flags: u8, + /// Font size in points. + pub font_size: u8, + /// Text RGBA color (`[r, g, b, a]`). + pub text_color_rgba: [u8; 4], +} + +impl Default for StyleRecord { + fn default() -> Self { + Self { start_char: 0, end_char: 0, font_id: 1, face_style_flags: 0, font_size: 16, text_color_rgba: [255, 255, 255, 255] } + } +} + +impl StyleRecord { + /// Returns `true` if bold is set. + pub fn is_bold(&self) -> bool { + self.face_style_flags & STYLE_FLAG_BOLD != 0 + } + + /// Returns `true` if italic is set. + pub fn is_italic(&self) -> bool { + self.face_style_flags & STYLE_FLAG_ITALIC != 0 + } + + /// Returns `true` if underline is set. + pub fn is_underline(&self) -> bool { + self.face_style_flags & STYLE_FLAG_UNDERLINE != 0 + } +} + +/// Coordinates of a text display box (`tbox`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TextBox { + pub top: i16, + pub left: i16, + pub bottom: i16, + pub right: i16, +} + +/// An entry in a karaoke box (`krok`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct KaraokeEntry { + /// Highlight end time in timescale ticks. + pub highlight_end_time: u32, + /// Start character index (inclusive). + pub start_char: u16, + /// End character index (exclusive). + pub end_char: u16, +} + +/// A hypertext link entry (`href`). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HyperText { + /// Start character index (inclusive). + pub start_char: u16, + /// End character index (exclusive). + pub end_char: u16, + /// Destination URL. + pub url: String, + /// Accessible alt text string. + pub alt_string: String, +} + +/// An unpacked 3GPP Timed Text (`tx3g` / `mov_text`) sample. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TextSample { + /// Decoded UTF-8 text content. + pub text: String, + /// Character styling records from the `styl` box. + pub styles: Vec, + /// Highlighted character range `(start_char, end_char)` from `hlit`. + pub highlight: Option<(u16, u16)>, + /// Highlight color `[r, g, b, a]` from `hclr`. + pub highlight_color: Option<[u8; 4]>, + /// Karaoke timing and spans `(highlight_start_time, entries)` from `krok`. + pub karaoke: Option<(u32, Vec)>, + /// Scroll delay in milliseconds from `dlay`. + pub scroll_delay: Option, + /// Hypertext links from `href` boxes. + pub hypertext: Vec, + /// Text box override from `tbox`. + pub text_box: Option, + /// Blinking character ranges `(start_char, end_char)` from `blnk` boxes. + pub blinking: Vec<(u16, u16)>, + /// Wrap flag from `wrap` box: `0` = automatic wrap, `1` = no wrap. + pub wrap_flag: Option, +} + +/// Sample description table configuration for a `tx3g` track. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Tx3gConfig { + /// 32-bit display flags (e.g. scroll in, scroll out, continuous scroll). + pub display_flags: u32, + /// Horizontal justification: 0 = left, 1 = center, -1 = right. + pub horizontal_justification: i8, + /// Vertical justification: 0 = top, 1 = center, -1 = bottom. + pub vertical_justification: i8, + /// Background RGBA color. + pub background_color: [u8; 4], + /// Default text box coordinates. + pub default_text_box: TextBox, + /// Default style record. + pub default_style: StyleRecord, + /// Font table entries `(font_id, font_name)`. + pub fonts: Vec<(u16, String)>, +} + +impl Default for Tx3gConfig { + fn default() -> Self { + Self { + display_flags: 0, + horizontal_justification: 1, // center + vertical_justification: -1, // bottom + background_color: [0, 0, 0, 255], + default_text_box: TextBox::default(), + default_style: StyleRecord::default(), + fonts: vec![(1, "Arial".to_string())], + } + } +} + +impl Tx3gConfig { + /// Parse a `tx3g` sample entry payload (after the standard 8-byte sample entry header). + pub fn parse(payload: &[u8]) -> Result { + if payload.len() < 30 { + return Err(Error::Truncated); + } + let display_flags = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]); + let horizontal_justification = payload[4] as i8; + let vertical_justification = payload[5] as i8; + let background_color = [payload[6], payload[7], payload[8], payload[9]]; + + let default_text_box = TextBox { + top: i16::from_be_bytes([payload[10], payload[11]]), + left: i16::from_be_bytes([payload[12], payload[13]]), + bottom: i16::from_be_bytes([payload[14], payload[15]]), + right: i16::from_be_bytes([payload[16], payload[17]]), + }; + + let default_style = StyleRecord { + start_char: u16::from_be_bytes([payload[18], payload[19]]), + end_char: u16::from_be_bytes([payload[20], payload[21]]), + font_id: u16::from_be_bytes([payload[22], payload[23]]), + face_style_flags: payload[24], + font_size: payload[25], + text_color_rgba: [payload[26], payload[27], payload[28], payload[29]], + }; + + let mut fonts = Vec::new(); + let mut pos = 30; + while pos + 8 <= payload.len() { + let box_size = u32::from_be_bytes([payload[pos], payload[pos + 1], payload[pos + 2], payload[pos + 3]]) as usize; + if box_size < 8 || pos.checked_add(box_size).is_none_or(|end| end > payload.len()) { + break; + } + let box_type = &payload[pos + 4..pos + 8]; + if box_type == b"ftab" && box_size >= 10 { + let count = u16::from_be_bytes([payload[pos + 8], payload[pos + 9]]) as usize; + let mut fpos = pos + 10; + for _ in 0..count { + if fpos + 3 > pos + box_size { + break; + } + let font_id = u16::from_be_bytes([payload[fpos], payload[fpos + 1]]); + let name_len = payload[fpos + 2] as usize; + fpos += 3; + if fpos + name_len > pos + box_size { + break; + } + if let Ok(name) = std::str::from_utf8(&payload[fpos..fpos + name_len]) { + fonts.push((font_id, name.to_string())); + } + fpos += name_len; + } + } + pos += box_size; + } + + Ok(Self { display_flags, horizontal_justification, vertical_justification, background_color, default_text_box, default_style, fonts }) + } + + /// Write the `tx3g` sample entry payload (after the 8-byte sample entry header). + pub fn write(&self) -> Vec { + let mut out = Vec::with_capacity(30 + 32); + out.extend_from_slice(&self.display_flags.to_be_bytes()); + out.push(self.horizontal_justification as u8); + out.push(self.vertical_justification as u8); + out.extend_from_slice(&self.background_color); + + out.extend_from_slice(&self.default_text_box.top.to_be_bytes()); + out.extend_from_slice(&self.default_text_box.left.to_be_bytes()); + out.extend_from_slice(&self.default_text_box.bottom.to_be_bytes()); + out.extend_from_slice(&self.default_text_box.right.to_be_bytes()); + + out.extend_from_slice(&self.default_style.start_char.to_be_bytes()); + out.extend_from_slice(&self.default_style.end_char.to_be_bytes()); + out.extend_from_slice(&self.default_style.font_id.to_be_bytes()); + out.push(self.default_style.face_style_flags); + out.push(self.default_style.font_size); + out.extend_from_slice(&self.default_style.text_color_rgba); + + // ftab box + let mut ftab_payload = Vec::new(); + let fonts = &self.fonts[..self.fonts.len().min(u16::MAX as usize)]; + ftab_payload.extend_from_slice(&(fonts.len() as u16).to_be_bytes()); + for (id, name) in fonts { + ftab_payload.extend_from_slice(&id.to_be_bytes()); + let name_bytes = name.as_bytes(); + let limit = name.floor_char_boundary(name_bytes.len().min(255)); + ftab_payload.push(limit as u8); + ftab_payload.extend_from_slice(&name_bytes[..limit]); + } + let ftab_size = 8u32.saturating_add(ftab_payload.len() as u32); + out.extend_from_slice(&ftab_size.to_be_bytes()); + out.extend_from_slice(b"ftab"); + out.extend_from_slice(&ftab_payload); + + out + } +} + +/// Read and decode a single 3GPP Timed Text sample (`tx3g` / `mov_text`). +pub fn read_sample(data: &[u8]) -> Result { + if data.len() < 2 { + return Err(Error::Truncated); + } + + let text_len = u16::from_be_bytes([data[0], data[1]]) as usize; + if data.len() < 2 + text_len { + return Err(Error::Truncated); + } + + let text_bytes = &data[2..2 + text_len]; + let text = decode_text(text_bytes)?; + + let mut sample = TextSample { text, ..Default::default() }; + + let mut pos = 2 + text_len; + while pos + 8 <= data.len() { + let size = u32::from_be_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; + if size < 8 { + return Err(Error::InvalidBox("size smaller than 8")); + } + let box_end = pos.checked_add(size).ok_or(Error::Truncated)?; + if box_end > data.len() { + return Err(Error::Truncated); + } + + let box_type = &data[pos + 4..pos + 8]; + let payload = &data[pos + 8..box_end]; + + match box_type { + b"styl" => { + if payload.len() < 2 { + return Err(Error::Truncated); + } + let count = u16::from_be_bytes([payload[0], payload[1]]) as usize; + let mut spos = 2; + for _ in 0..count { + if spos + 12 > payload.len() { + return Err(Error::Truncated); + } + sample.styles.push(StyleRecord { + start_char: u16::from_be_bytes([payload[spos], payload[spos + 1]]), + end_char: u16::from_be_bytes([payload[spos + 2], payload[spos + 3]]), + font_id: u16::from_be_bytes([payload[spos + 4], payload[spos + 5]]), + face_style_flags: payload[spos + 6], + font_size: payload[spos + 7], + text_color_rgba: [payload[spos + 8], payload[spos + 9], payload[spos + 10], payload[spos + 11]], + }); + spos += 12; + } + } + b"hlit" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + let start = u16::from_be_bytes([payload[0], payload[1]]); + let end = u16::from_be_bytes([payload[2], payload[3]]); + sample.highlight = Some((start, end)); + } + b"hclr" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + sample.highlight_color = Some([payload[0], payload[1], payload[2], payload[3]]); + } + b"krok" => { + if payload.len() < 6 { + return Err(Error::Truncated); + } + let start_time = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]); + let count = u16::from_be_bytes([payload[4], payload[5]]) as usize; + let mut entries = Vec::new(); + let mut kpos = 6; + for _ in 0..count { + if kpos + 8 > payload.len() { + return Err(Error::Truncated); + } + entries.push(KaraokeEntry { + highlight_end_time: u32::from_be_bytes([payload[kpos], payload[kpos + 1], payload[kpos + 2], payload[kpos + 3]]), + start_char: u16::from_be_bytes([payload[kpos + 4], payload[kpos + 5]]), + end_char: u16::from_be_bytes([payload[kpos + 6], payload[kpos + 7]]), + }); + kpos += 8; + } + sample.karaoke = Some((start_time, entries)); + } + b"dlay" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + sample.scroll_delay = Some(u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]])); + } + b"href" => { + if payload.len() < 6 { + return Err(Error::Truncated); + } + let start = u16::from_be_bytes([payload[0], payload[1]]); + let end = u16::from_be_bytes([payload[2], payload[3]]); + let url_len = payload[4] as usize; + if 5 + url_len > payload.len() { + return Err(Error::Truncated); + } + let url = std::str::from_utf8(&payload[5..5 + url_len]).map_err(|_| Error::InvalidText)?.to_string(); + let alt_pos = 5 + url_len; + let alt_len = payload.get(alt_pos).copied().unwrap_or(0) as usize; + let alt_string = if alt_len > 0 && alt_pos + 1 + alt_len <= payload.len() { + std::str::from_utf8(&payload[alt_pos + 1..alt_pos + 1 + alt_len]).map_err(|_| Error::InvalidText)?.to_string() + } else { + String::new() + }; + sample.hypertext.push(HyperText { start_char: start, end_char: end, url, alt_string }); + } + b"tbox" => { + if payload.len() < 8 { + return Err(Error::Truncated); + } + sample.text_box = Some(TextBox { + top: i16::from_be_bytes([payload[0], payload[1]]), + left: i16::from_be_bytes([payload[2], payload[3]]), + bottom: i16::from_be_bytes([payload[4], payload[5]]), + right: i16::from_be_bytes([payload[6], payload[7]]), + }); + } + b"blnk" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + let start = u16::from_be_bytes([payload[0], payload[1]]); + let end = u16::from_be_bytes([payload[2], payload[3]]); + sample.blinking.push((start, end)); + } + b"twrp" | b"wrap" => { + if payload.is_empty() { + return Err(Error::Truncated); + } + sample.wrap_flag = Some(payload[0]); + } + _ => { + // Unknown modifier box: safely ignored. + } + } + + pos = box_end; + } + + Ok(sample) +} + +/// Helper to decode UTF-8 or UTF-16 with BOM. +fn decode_text(bytes: &[u8]) -> Result { + if bytes.len() >= 2 { + if bytes[0] == 0xFE && bytes[1] == 0xFF { + // UTF-16 BE + let u16s: Vec = bytes[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); + return String::from_utf16(&u16s).map_err(|_| Error::InvalidText); + } else if bytes[0] == 0xFF && bytes[1] == 0xFE { + // UTF-16 LE + let u16s: Vec = bytes[2..].as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + return String::from_utf16(&u16s).map_err(|_| Error::InvalidText); + } + } + std::str::from_utf8(bytes).map(ToString::to_string).map_err(|_| Error::InvalidText) +} + +/// Pack and encode a timed text sample into bytes. +pub fn write_sample(sample: &TextSample) -> Result> { + let text_bytes = sample.text.as_bytes(); + if text_bytes.len() > u16::MAX as usize { + return Err(Error::TextTooLong(text_bytes.len())); + } + + let mut out = Vec::with_capacity(2 + text_bytes.len() + 64); + out.extend_from_slice(&(text_bytes.len() as u16).to_be_bytes()); + out.extend_from_slice(text_bytes); + + // 1. styl box + if !sample.styles.is_empty() { + if sample.styles.len() > u16::MAX as usize { + return Err(Error::InvalidBox("too many styles in sample")); + } + let size = 8u32.checked_add(2).and_then(|s| s.checked_add(sample.styles.len() as u32 * 12)).ok_or(Error::InvalidBox("styl size overflow"))?; + out.extend_from_slice(&size.to_be_bytes()); + out.extend_from_slice(b"styl"); + out.extend_from_slice(&(sample.styles.len() as u16).to_be_bytes()); + for st in &sample.styles { + out.extend_from_slice(&st.start_char.to_be_bytes()); + out.extend_from_slice(&st.end_char.to_be_bytes()); + out.extend_from_slice(&st.font_id.to_be_bytes()); + out.push(st.face_style_flags); + out.push(st.font_size); + out.extend_from_slice(&st.text_color_rgba); + } + } + + // 2. hlit box + if let Some((start, end)) = sample.highlight { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"hlit"); + out.extend_from_slice(&start.to_be_bytes()); + out.extend_from_slice(&end.to_be_bytes()); + } + + // 3. hclr box + if let Some(color) = sample.highlight_color { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"hclr"); + out.extend_from_slice(&color); + } + + // 4. krok box + if let Some((start_time, ref entries)) = sample.karaoke { + if entries.len() > u16::MAX as usize { + return Err(Error::InvalidBox("too many karaoke entries")); + } + let size = 8u32.checked_add(6).and_then(|s| s.checked_add(entries.len() as u32 * 8)).ok_or(Error::InvalidBox("krok size overflow"))?; + out.extend_from_slice(&size.to_be_bytes()); + out.extend_from_slice(b"krok"); + out.extend_from_slice(&start_time.to_be_bytes()); + out.extend_from_slice(&(entries.len() as u16).to_be_bytes()); + for e in entries { + out.extend_from_slice(&e.highlight_end_time.to_be_bytes()); + out.extend_from_slice(&e.start_char.to_be_bytes()); + out.extend_from_slice(&e.end_char.to_be_bytes()); + } + } + + // 5. dlay box + if let Some(delay) = sample.scroll_delay { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"dlay"); + out.extend_from_slice(&delay.to_be_bytes()); + } + + // 6. href boxes + for link in &sample.hypertext { + let url_bytes = link.url.as_bytes(); + let alt_bytes = link.alt_string.as_bytes(); + let ulen = url_bytes.len().min(255) as u8; + let alen = alt_bytes.len().min(255) as u8; + let size = 8u32 + 4 + 1 + ulen as u32 + 1 + alen as u32; + out.extend_from_slice(&size.to_be_bytes()); + out.extend_from_slice(b"href"); + out.extend_from_slice(&link.start_char.to_be_bytes()); + out.extend_from_slice(&link.end_char.to_be_bytes()); + out.push(ulen); + out.extend_from_slice(&url_bytes[..ulen as usize]); + out.push(alen); + out.extend_from_slice(&alt_bytes[..alen as usize]); + } + + // 7. tbox box + if let Some(tb) = sample.text_box { + out.extend_from_slice(&16u32.to_be_bytes()); + out.extend_from_slice(b"tbox"); + out.extend_from_slice(&tb.top.to_be_bytes()); + out.extend_from_slice(&tb.left.to_be_bytes()); + out.extend_from_slice(&tb.bottom.to_be_bytes()); + out.extend_from_slice(&tb.right.to_be_bytes()); + } + + // 8. blnk boxes + for &(start, end) in &sample.blinking { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"blnk"); + out.extend_from_slice(&start.to_be_bytes()); + out.extend_from_slice(&end.to_be_bytes()); + } + + // 9. twrp box + if let Some(flag) = sample.wrap_flag { + out.extend_from_slice(&9u32.to_be_bytes()); + out.extend_from_slice(b"twrp"); + out.push(flag); + } + + Ok(out) +} + +fn push_escaped_char(out: &mut String, ch: char) { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + _ => out.push(ch), + } +} + +/// Convert a [`TextSample`] into HTML-style formatted markup (``, ``, ``, ``). +pub fn sample_to_markup(sample: &TextSample) -> String { + if sample.styles.is_empty() { + let mut out = String::with_capacity(sample.text.len()); + for ch in sample.text.chars() { + push_escaped_char(&mut out, ch); + } + return out; + } + + let chars: Vec = sample.text.chars().collect(); + let n = chars.len(); + if n == 0 { + return String::new(); + } + + let mut starts: std::collections::HashMap> = std::collections::HashMap::new(); + let mut ends: std::collections::HashMap> = std::collections::HashMap::new(); + for st in &sample.styles { + if st.end_char > st.start_char { + starts.entry(st.start_char).or_default().push(st); + ends.entry(st.end_char).or_default().push(st); + } + } + + let mut out = String::with_capacity(sample.text.len() + sample.styles.len() * 16); + + for (i, &ch) in chars.iter().enumerate() { + let char_idx = i as u16; + + // Open tags for any style starting at char_idx + if let Some(list) = starts.get(&char_idx) { + for st in list { + let has_color = st.text_color_rgba != [255, 255, 255, 255]; + if has_color { + out.push_str(&format!( + "", + st.text_color_rgba[0], st.text_color_rgba[1], st.text_color_rgba[2] + )); + } + if st.is_bold() { + out.push_str(""); + } + if st.is_italic() { + out.push_str(""); + } + if st.is_underline() { + out.push_str(""); + } + } + } + + push_escaped_char(&mut out, ch); + + // Close tags for any style ending at char_idx + 1 + if let Some(list) = ends.get(&(char_idx + 1)) { + for st in list.iter().rev() { + if st.is_underline() { + out.push_str(""); + } + if st.is_italic() { + out.push_str(""); + } + if st.is_bold() { + out.push_str(""); + } + let has_color = st.text_color_rgba != [255, 255, 255, 255]; + if has_color { + out.push_str(""); + } + } + } + } + + out +} + +#[derive(Clone, Copy, PartialEq, Eq)] +struct CharFormatting { + flags: u8, + color: [u8; 4], +} + +impl Default for CharFormatting { + fn default() -> Self { + Self { flags: 0, color: [255, 255, 255, 255] } + } +} + +/// Parse HTML-style formatted markup (``, ``, ``, ``) into a [`TextSample`]. +pub fn markup_to_sample(markup: &str) -> TextSample { + let mut bold_depth = 0usize; + let mut italic_depth = 0usize; + let mut underline_depth = 0usize; + let mut color_stack: Vec<[u8; 4]> = Vec::new(); + + let mut decoded_chars: Vec = Vec::with_capacity(markup.len()); + let mut char_styles: Vec = Vec::with_capacity(markup.len()); + + let mut chars = markup.chars().peekable(); + + while let Some(ch) = chars.next() { + if ch == '<' { + let mut tag = String::new(); + for next in chars.by_ref() { + if next == '>' { + break; + } + tag.push(next); + } + let trimmed = tag.trim().to_ascii_lowercase(); + if trimmed == "b" { + bold_depth += 1; + } else if trimmed == "/b" { + bold_depth = bold_depth.saturating_sub(1); + } else if trimmed == "i" { + italic_depth += 1; + } else if trimmed == "/i" { + italic_depth = italic_depth.saturating_sub(1); + } else if trimmed == "u" { + underline_depth += 1; + } else if trimmed == "/u" { + underline_depth = underline_depth.saturating_sub(1); + } else if trimmed.starts_with("font") { + if let Some(color) = parse_font_color(&tag) { + color_stack.push(color); + } + } else if trimmed == "/font" { + color_stack.pop(); + } + } else { + let mut text_chunk = String::new(); + text_chunk.push(ch); + while let Some(&next) = chars.peek() { + if next == '<' { + break; + } + text_chunk.push(next); + chars.next(); + } + + let decoded = crate::decode_entities(&text_chunk); + let mut flags = 0u8; + if bold_depth > 0 { + flags |= STYLE_FLAG_BOLD; + } + if italic_depth > 0 { + flags |= STYLE_FLAG_ITALIC; + } + if underline_depth > 0 { + flags |= STYLE_FLAG_UNDERLINE; + } + let color = color_stack.last().copied().unwrap_or([255, 255, 255, 255]); + let fmt = CharFormatting { flags, color }; + + for c in decoded.chars() { + decoded_chars.push(c); + char_styles.push(fmt); + } + } + } + + let text: String = decoded_chars.iter().collect(); + + // Group adjacent characters with identical non-default formatting into sorted, non-overlapping style runs. + let mut styles = Vec::new(); + let mut run_start: Option<(usize, CharFormatting)> = None; + + for (idx, &fmt) in char_styles.iter().enumerate() { + let is_styled = fmt.flags != 0 || fmt.color != [255, 255, 255, 255]; + match run_start { + Some((start, current_fmt)) => { + if fmt != current_fmt { + if current_fmt.flags != 0 || current_fmt.color != [255, 255, 255, 255] { + styles.push(StyleRecord { + start_char: start as u16, + end_char: idx as u16, + font_id: 1, + face_style_flags: current_fmt.flags, + font_size: 16, + text_color_rgba: current_fmt.color, + }); + } + run_start = if is_styled { Some((idx, fmt)) } else { None }; + } + } + None => { + if is_styled { + run_start = Some((idx, fmt)); + } + } + } + } + + if let Some((start, fmt)) = run_start { + styles.push(StyleRecord { + start_char: start as u16, + end_char: char_styles.len() as u16, + font_id: 1, + face_style_flags: fmt.flags, + font_size: 16, + text_color_rgba: fmt.color, + }); + } + + TextSample { text, styles, ..Default::default() } +} + +/// Helper to parse color attribute from `` tag. +fn parse_font_color(tag: &str) -> Option<[u8; 4]> { + let lower = tag.to_ascii_lowercase(); + let col_idx = lower.find("color=")?; + let rest = tag[col_idx + 6..].trim_start(); + let val = if let Some(stripped) = rest.strip_prefix('"') { + let end = stripped.find('"')?; + &stripped[..end] + } else if let Some(stripped) = rest.strip_prefix('\'') { + let end = stripped.find('\'')?; + &stripped[..end] + } else { + let end = rest.find(char::is_whitespace).unwrap_or(rest.len()); + &rest[..end] + }; + + let hex = val.strip_prefix('#').unwrap_or(val); + if hex.len() == 6 { + let r = u8::from_str_radix(hex.get(0..2)?, 16).ok()?; + let g = u8::from_str_radix(hex.get(2..4)?, 16).ok()?; + let b = u8::from_str_radix(hex.get(4..6)?, 16).ok()?; + Some([r, g, b, 255]) + } else if hex.len() == 8 { + let r = u8::from_str_radix(hex.get(0..2)?, 16).ok()?; + let g = u8::from_str_radix(hex.get(2..4)?, 16).ok()?; + let b = u8::from_str_radix(hex.get(4..6)?, 16).ok()?; + let a = u8::from_str_radix(hex.get(6..8)?, 16).ok()?; + Some([r, g, b, a]) + } else { + None + } +} + +/// Convert a caption [`Cue`] into a [`TextSample`]. +pub fn cue_to_sample(cue: &Cue) -> TextSample { + markup_to_sample(&cue.text) +} + +/// Convert a [`TextSample`] into a caption [`Cue`] spanning `start` to `end`. +pub fn sample_to_cue(sample: &TextSample, start: Tick, end: Tick) -> Cue { + Cue { start, end, text: sample_to_markup(sample), speaker: None, id: None, settings: String::new() } +} + +/// Decode a stream of timed text samples into a [`Document`]. +pub fn decode_timed_samples<'a, I>(doc: &mut Document, samples: I, timescale: u32) -> Result<()> +where + I: IntoIterator, +{ + decode_timed_samples_with_config(doc, samples, timescale, None) +} + +/// Decode a stream of timed text samples into a [`Document`], applying an optional sample description configuration. +pub fn decode_timed_samples_with_config<'a, I>(doc: &mut Document, samples: I, timescale: u32, config: Option<&Tx3gConfig>) -> Result<()> +where + I: IntoIterator, +{ + if timescale == 0 { + return Ok(()); + } + let ts = timescale as i128; + for (pts, duration, data) in samples { + let mut sample = read_sample(data)?; + if sample.text.trim().is_empty() { + continue; + } + if sample.styles.is_empty() + && let Some(cfg) = config + && (cfg.default_style.face_style_flags != 0 || cfg.default_style.text_color_rgba != [255, 255, 255, 255]) + { + sample.styles.push(StyleRecord { + start_char: 0, + end_char: sample.text.chars().count() as u16, + font_id: cfg.default_style.font_id, + face_style_flags: cfg.default_style.face_style_flags, + font_size: cfg.default_style.font_size, + text_color_rgba: cfg.default_style.text_color_rgba, + }); + } + let end_pts = pts.checked_add(duration as u64).ok_or(Error::InvalidBox("timestamp interval overflow"))?; + let start_ticks = (pts as i128 * TICKS_PER_SECOND as i128 / ts) as i64; + let end_ticks = (end_pts as i128 * TICKS_PER_SECOND as i128 / ts) as i64; + doc.cues.push(sample_to_cue(&sample, Tick(start_ticks), Tick(end_ticks))); + } + Ok(()) +} diff --git a/crates/captions/src/pjs.rs b/crates/captions/src/pjs.rs new file mode 100644 index 000000000..91874941b --- /dev/null +++ b/crates/captions/src/pjs.rs @@ -0,0 +1,102 @@ +//! Phoenix Japanimation Society (PJS) subtitles (`.pjs`): times in tenths of a second. +//! +//! ```text +//! 10,50,"First line" +//! 60,120,"Second line|with break" +//! ``` +//! +//! Lines are comma-separated `start,end,"text"` with times in deciseconds (tenths of a second). +//! Inside the quotes, `|` breaks a line. + +use crate::text::{escape_markup, ms_to_tick, number, plain_lines, tick_to_ms}; +use crate::{Cue, Document, Error, Result}; + +/// `start,end,"text"` as its parts. +pub(crate) fn split_cue(line: &str) -> Option<(i64, i64, &str)> { + let (start_str, rest) = line.split_once(',')?; + let (end_str, text_str) = rest.split_once(',')?; + let start = number(start_str.trim())?; + let end = number(end_str.trim())?; + let text = text_str.trim(); + let text = if let Some(stripped) = text.strip_prefix('"').and_then(|t| t.strip_suffix('"')) { stripped } else { text }; + Some((start, end, text)) +} + +/// Parse a PJS subtitle document. +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut found = false; + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let Some((start_ds, end_ds, raw)) = split_cue(line) else { + doc.warnings.push(format!("line {}: not a PJS cue, skipped", n + 1)); + continue; + }; + found = true; + let mut lines = Vec::new(); + for l in raw.split('|') { + let trimmed = l.trim(); + if !trimmed.is_empty() { + let unquoted = trimmed.replace("\"\"", "\""); + lines.push(escape_markup(&unquoted)); + } + } + let start = ms_to_tick(start_ds.saturating_mul(100)); + let end = ms_to_tick(end_ds.saturating_mul(100)); + if end <= start || lines.is_empty() { + doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1)); + continue; + } + doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() }); + } + if !found && !text.trim().is_empty() { + return Err(Error::NotFormat("PJS")); + } + Ok(doc) +} + +/// Serialize a document into PJS format. +pub fn write(doc: &Document) -> String { + let mut out = String::new(); + let ds = |t| (tick_to_ms(t) + 50) / 100; + for c in &doc.cues { + let start = ds(c.start); + let end = ds(c.end).max(start + 1); + let lines: Vec = + plain_lines(&c.text).into_iter().map(|l| l.replace('"', "\"\"").replace('|', "|")).filter(|l| !l.is_empty()).collect(); + if !lines.is_empty() { + out.push_str(&format!("{start},{end},\"{}\"\n", lines.join("|"))); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_write_roundtrip() { + let pjs = "10,50,\"First line\"\n60,120,\"Second line|with break\"\n130,150,\"Say \"\"Hi\"\"\"\n"; + let doc = parse(pjs).expect("parse"); + assert_eq!(doc.cues.len(), 3); + assert_eq!(doc.cues[0].start, ms_to_tick(1000)); + assert_eq!(doc.cues[0].end, ms_to_tick(5000)); + assert_eq!(doc.cues[0].text, "First line"); + assert_eq!(doc.cues[1].start, ms_to_tick(6000)); + assert_eq!(doc.cues[1].end, ms_to_tick(12000)); + assert_eq!(doc.cues[1].text, "Second line\nwith break"); + assert_eq!(doc.cues[2].text, "Say \"Hi\""); + + let written = write(&doc); + assert_eq!(written, pjs); + } + + #[test] + fn rejects_non_pjs() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nHello\n").is_err()); + } +} diff --git a/crates/captions/src/realtext.rs b/crates/captions/src/realtext.rs new file mode 100644 index 000000000..1c4328a3b --- /dev/null +++ b/crates/captions/src/realtext.rs @@ -0,0 +1,247 @@ +//! RealText (`.rt`): streaming HTML-like timed text markup. +//! +//! ```text +//! +//! +//! ``` +//! +//! RealText documents encapsulate timed text inside a `` container with `