mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-23 02:51:42 +01:00
Merge storytold/craft-libs main into math-ports
This commit is contained in:
1630 files changed
+271120
-12987
No files matched your search
@@ -1,2 +0,0 @@
|
||||
[lints]
|
||||
cargo.unused_workspace_dependencies = "allow"
|
||||
@@ -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'
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
+22
-50
@@ -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).
|
||||
|
||||
@@ -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
|
||||
+12
-48
@@ -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') }}
|
||||
|
||||
@@ -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
|
||||
+10
-19
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 }}
|
||||
@@ -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
|
||||
@@ -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
|
||||
+11
-18
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
+18
-25
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
+26
-68
@@ -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
|
||||
@@ -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' }}
|
||||
+13
-21
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
+18
-24
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
+169
-30
@@ -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 (<os>)` leg beside each `gate (<os>)` 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
|
||||
# `<version>-rust-<profile>-<job>-crates-<os>-<arch>-<run>-<attempt>-...`, 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: ""
|
||||
|
||||
+83
-1
@@ -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.
|
||||
Generated
+1981
-39
File diff suppressed because it is too large.
Load diff
+68
-3
@@ -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-<name> = { path = "crates/<name>" }`
|
||||
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"
|
||||
|
||||
@@ -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 <volkerstroebel@mysurdity.de>
|
||||
|
||||
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 <ossman@cendio.se> 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.
|
||||
*/
|
||||
@@ -2,6 +2,7 @@ Craft App Libraries
|
||||
===================
|
||||
|
||||
<a href="https://sonarcloud.io/project/overview?id=storytold_craft-libs"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
|
||||
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/craft-libs?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
|
||||
|
||||
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
|
||||
|
||||
+45
-2
@@ -57,13 +57,56 @@ pub struct WriteOptions<'a> {
|
||||
/// reported.
|
||||
pub fn write(doc: &Document, opts: &WriteOptions<'_>, report: &mut Report) -> Result<Vec<u8>> {
|
||||
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<Document> {
|
||||
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<Vec<u8>> {
|
||||
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<Document> {
|
||||
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
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -67,6 +67,7 @@ fn indirect_f64(d: &[u8]) -> Option<f64> {
|
||||
|
||||
struct R<'a> {
|
||||
report: &'a mut Report,
|
||||
options: super::ReadOptions,
|
||||
mobs: HashMap<MobId, &'a Obj>,
|
||||
essence: HashMap<MobId, &'a [u8]>,
|
||||
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<Document> {
|
||||
pub(crate) fn read(bytes: &[u8], options: &super::ReadOptions, report: &mut Report) -> Result<Document> {
|
||||
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<Document> {
|
||||
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 };
|
||||
|
||||
@@ -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"))?;
|
||||
|
||||
@@ -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<i64> = 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));
|
||||
}
|
||||
@@ -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<Vec<u8>> {
|
||||
pub(crate) fn write(
|
||||
doc: &Document,
|
||||
version: craft_cfb::Version,
|
||||
identity: &Identity<'_>,
|
||||
references: &super::ReferenceOptions,
|
||||
report: &mut Report,
|
||||
) -> Result<Vec<u8>> {
|
||||
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<Auid> = 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))]));
|
||||
}
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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<u8>,
|
||||
names: HashMap<(u32, String), u32>,
|
||||
next: u32,
|
||||
@@ -90,6 +90,12 @@ pub(crate) struct Writer {
|
||||
entries: Vec<(u32, u32, u32, Vec<Seg>)>,
|
||||
}
|
||||
|
||||
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<u32, Vec<Prop>>,
|
||||
pub(crate) objects: BTreeMap<u32, Vec<Prop>>,
|
||||
names: HashMap<u32, String>,
|
||||
by_name: HashMap<String, u32>,
|
||||
}
|
||||
@@ -229,11 +235,16 @@ fn be32(b: &[u8], at: usize) -> Option<u32> {
|
||||
}
|
||||
|
||||
/// 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<Item = u32> + '_ {
|
||||
self.objects.keys().copied()
|
||||
}
|
||||
|
||||
pub fn open(data: &'a [u8]) -> Result<Container<'a>, 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<Vec<u8>, String> {
|
||||
pub(crate) fn value(&self, p: &Prop) -> Result<Vec<u8>, String> {
|
||||
let total = p.segs.iter().try_fold(0usize, |total, s| {
|
||||
let len = match s {
|
||||
Seg::Imm(b) => b.len(),
|
||||
|
||||
+340
-10
@@ -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<Uid, Vec<u8>>,
|
||||
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<u32, std::result::Result<Option<u32>, 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<Document> {
|
||||
read_with_budget(bytes, report, MAX_COMPONENT_VISITS)
|
||||
}
|
||||
|
||||
fn read_with_budget(bytes: &[u8], report: &mut Report, budget: usize) -> Result<Document> {
|
||||
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<Document> {
|
||||
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<CItem> {
|
||||
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<u32> {
|
||||
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<Option<u32>, 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<Option<u32>, 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<u32>,
|
||||
todo: &mut Vec<u32>,
|
||||
queued: &mut usize,
|
||||
max_visits: usize,
|
||||
max_pending: usize,
|
||||
) -> std::result::Result<Option<u32>, 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<String>, 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<Option<u32>, 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::<Vec<_>>());
|
||||
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<u32> = (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<T>(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<u32> = (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<u32> = (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<u32> = (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::<Vec<_>>());
|
||||
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::<Vec<_>>());
|
||||
assert!(results.iter().all(|r| matches!(r, Ok(None))));
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,3 @@
|
||||
pub(crate) fn parse_wav(b: &[u8]) -> Option<(Vec<u8>, 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<u8>, u16, u32, u16)> {
|
||||
craft_audio::aiff_pcm(b).map(|p| (p.data, p.channels, p.sample_rate, p.bits))
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
+17
-10
@@ -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`):
|
||||
|
||||
|
||||
@@ -22,8 +22,55 @@ fn files(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
}
|
||||
|
||||
fn samples() -> Option<PathBuf> {
|
||||
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<std::ffi::OsString>, pinned: impl FnOnce() -> Option<PathBuf>) -> Option<PathBuf> {
|
||||
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]
|
||||
|
||||
@@ -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)"]
|
||||
@@ -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<Vec<Row<'_>>, 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<Row<'static>> {
|
||||
rows(MANIFEST).unwrap_or_else(|e| panic!("malformed corpus.tsv: {e}"))
|
||||
}
|
||||
|
||||
/// The names of the pinned files.
|
||||
pub fn names() -> impl Iterator<Item = &'static str> {
|
||||
MANIFEST.lines().filter_map(|l| l.split('\t').nth(1))
|
||||
manifest().into_iter().map(|row| row.name)
|
||||
}
|
||||
|
||||
pub fn pinned() -> Option<PathBuf> {
|
||||
@@ -21,10 +68,7 @@ pub fn pinned() -> Option<PathBuf> {
|
||||
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");
|
||||
|
||||
@@ -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
|
||||
|
@@ -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"
|
||||
@@ -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<String, AiError>;
|
||||
fn test(&self) -> Result<ProviderInfo, AiError>;
|
||||
}
|
||||
```
|
||||
|
||||
- `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<term,
|
||||
translation>`) 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 |
|
||||
@@ -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<std::io::Error> for AiError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
Self::Io(e)
|
||||
}
|
||||
}
|
||||
@@ -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<File, AiError> {
|
||||
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<Cancel<'_>>) -> Result<PathBuf, AiError> {
|
||||
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<Option<String>, 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<ureq::Body>) -> Option<String> {
|
||||
// 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<ureq::Body>) -> Option<u64> {
|
||||
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<String, AiError> {
|
||||
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: `<file>.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<PathBuf, AiError> {
|
||||
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(_))));
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
@@ -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<Tensor, candle_core::Error> {
|
||||
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<Self, AiError> {
|
||||
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<Weights, AiError> {
|
||||
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<String, AiError> {
|
||||
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<u32> = 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<u32> = 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<String, AiError> {
|
||||
self.generate(prompt, opts).map(|s| s.trim().to_string())
|
||||
}
|
||||
|
||||
fn test(&mut self) -> Result<ProviderInfo, AiError> {
|
||||
Ok(ProviderInfo { label: format!("loaded: {}", self.entry.name), models: vec![self.entry.id.to_string()] })
|
||||
}
|
||||
|
||||
fn is_local(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -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<f32>,
|
||||
}
|
||||
|
||||
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<std::path::PathBuf> {
|
||||
dirs::cache_dir().map(|d| d.join("artcraft").join("models"))
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Inference backends behind one trait. Apps hold a `Box<dyn Provider>`
|
||||
//! 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<String>,
|
||||
}
|
||||
|
||||
/// 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<String, AiError>;
|
||||
/// Can we reach it? Never sends document text — just a handshake.
|
||||
fn test(&mut self) -> Result<ProviderInfo, AiError>;
|
||||
/// 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<String>,
|
||||
/// Model id sent in every request.
|
||||
pub model: String,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl OpenAiCompat {
|
||||
pub fn new(endpoint: impl Into<String>, token: Option<String>, model: impl Into<String>) -> 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::typestate::WithBody>) -> ureq::RequestBuilder<ureq::typestate::WithBody> {
|
||||
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<String, AiError> {
|
||||
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<ProviderInfo, AiError> {
|
||||
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::<std::net::IpAddr>().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"));
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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}`, `<markup>`, 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. `<markup>` spans are
|
||||
/// carved out first — a tag with attributes contains whitespace, and a
|
||||
/// whole `<em>Hello</em>` run must keep "Hello" translatable while the
|
||||
/// tags themselves stay byte-identical.
|
||||
pub fn segment(text: &str, grammar: &dyn TranslateGrammar) -> Vec<Segment> {
|
||||
fn flush(out: &mut Vec<Segment>, 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<Segment> = 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 `</`, `<?`, `<!`
|
||||
/// or `<`+letter and close at the first `>` before any `<` or newline;
|
||||
/// the scan is capped so pathological input can't stall it.
|
||||
fn tag_len(s: &str) -> Option<usize> {
|
||||
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<bool> = 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<Vec<String>, 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<Run<'_>> = 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<usize> = runs.iter().map(|r| r.seg).collect();
|
||||
|
||||
let mut out: Vec<String> = 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<Vec<String>, 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::<Vec<_>>(), 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<String, AiError> {
|
||||
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<Vec<String>> {
|
||||
let mut out = vec![String::new(); want];
|
||||
let mut seen = vec![false; want];
|
||||
let mut current: Option<usize> = 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<usize> {
|
||||
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("<em>Hello</em> world", &PdfGrammar);
|
||||
assert!(segs.iter().any(|s| matches!(s, Segment::Protected(p) if p == "<em>")));
|
||||
assert!(segs.iter().any(|s| matches!(s, Segment::Protected(p) if p.trim() == "</em>")));
|
||||
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("<a href=\"x\">link</a>", &PdfGrammar);
|
||||
assert!(segs.iter().any(|s| matches!(s, Segment::Protected(p) if p == "<a href=\"x\">")));
|
||||
// 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<String, AiError> {
|
||||
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<crate::provider::ProviderInfo, AiError> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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<P: Serialize, T: Serialize>(generator: &str, paths: &[P], document: &T) -> Result<String, serde_json::Error> {
|
||||
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<P: Serialize, T: Serialize>(version: u32, generator: &str, paths: &[P], document: &T) -> Result<String, serde_json::Error> {
|
||||
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) }
|
||||
}
|
||||
|
||||
@@ -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<std::fs::Permissions> {
|
||||
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<u32>,
|
||||
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<u32>,
|
||||
/// 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]);
|
||||
}
|
||||
|
||||
+97
-3
@@ -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"]
|
||||
+42
-3
@@ -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<u8> = 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.
|
||||
@@ -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<Self, AdtsConfigError> {
|
||||
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)] {
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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<usize> {
|
||||
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<i16>) -> 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<Vec<i16>> {
|
||||
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<Vec<u8>> {
|
||||
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<i16> = 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<Vec<u8>> {
|
||||
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<i16> = 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));
|
||||
}
|
||||
}
|
||||
@@ -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<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// 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)
|
||||
}
|
||||
@@ -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<usize> {
|
||||
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<i16>) -> 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<Vec<i16>> {
|
||||
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<Vec<u8>> {
|
||||
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<i16> = 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<u8>, 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<Vec<u8>> {
|
||||
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<i16> = 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());
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<i16>> {
|
||||
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<Vec<u8>> {
|
||||
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<i16> = 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());
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<i16>> {
|
||||
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<Vec<u8>> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<String> {
|
||||
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<RawAudio, Error> {
|
||||
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<u8>> = 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<Vec<u8>, 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)
|
||||
}
|
||||
@@ -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<String> {
|
||||
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<String>, Option<String>) {
|
||||
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<String> {
|
||||
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::<String>(),
|
||||
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<u16> = 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<RawAudio, Error> {
|
||||
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<u8>> = 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<u32, Error> {
|
||||
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<Vec<u8>, 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)
|
||||
}
|
||||
@@ -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::<f32>()).ok_or(Error::MemoryLimitExceeded)?;
|
||||
let output = (len / (factor / 8) as usize).checked_mul(std::mem::size_of::<f32>()).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<f32> {
|
||||
let n = 24 * ratio + 1;
|
||||
let mid = (n / 2) as f64;
|
||||
let fc = 0.45 / ratio as f64;
|
||||
let mut taps: Vec<f64> = (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<Vec<f32>, 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}");
|
||||
}
|
||||
}
|
||||
@@ -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<usize, Error> {
|
||||
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<Item = usize>, 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<String>,
|
||||
/// Optional track title if present in container metadata.
|
||||
pub title: Option<String>,
|
||||
/// Optional artist name if present in container metadata.
|
||||
pub artist: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<Vec<u8>>,
|
||||
}
|
||||
|
||||
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<DecodedAudio, Error> {
|
||||
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<DecodedAudio, Error> {
|
||||
// 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<f32>` per channel.
|
||||
pub channels: Vec<Vec<f32>>,
|
||||
}
|
||||
|
||||
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<Format, Error> {
|
||||
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<Metadata, Error> {
|
||||
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<RawAudio, Error> {
|
||||
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<DecodedAudio, Error> {
|
||||
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<DecodedAudio, Error> {
|
||||
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<Vec<u8>, 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<Vec<u8>, 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));
|
||||
}
|
||||
}
|
||||
@@ -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<u8>, 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<u8> {
|
||||
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<u8>, 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<u8> = (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<u8> = (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]));
|
||||
}
|
||||
}
|
||||
@@ -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<T> = std::result::Result<T, DecodeError>;
|
||||
|
||||
/// 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<StreamInfo> {
|
||||
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<Vec<i32>>,
|
||||
/// 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<u32> {
|
||||
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<u64> {
|
||||
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<i64> {
|
||||
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<u64> {
|
||||
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<StreamInfo>,
|
||||
}
|
||||
|
||||
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<Frame> {
|
||||
// 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<i64>> = 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<Vec<i32>> = 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<u64> {
|
||||
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<Vec<i64>> {
|
||||
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<Vec<i32>>,
|
||||
}
|
||||
|
||||
/// 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<Decoded> {
|
||||
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<Decoded> {
|
||||
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<StreamInfo> = 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<i32>> = 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<i32> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<i16>) -> 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<u8>) -> 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<Vec<i16>, 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<Vec<u8>, 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<Vec<i16>, 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<Decoder> = 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<Vec<u8>, 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<Encoder> = 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);
|
||||
}
|
||||
}
|
||||
@@ -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<i16>) -> 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<u8>) -> 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<u8>) -> 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<Vec<i16>, 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<Vec<u8>, 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<Vec<i16>, 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<Decoder> = 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<i16>> = 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<Vec<u8>, 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<Encoder> = 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<i16>> = 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<u8>> = 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);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+106
-17
@@ -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<alac::Error> for AudioError {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "vmd-decode")]
|
||||
impl From<vmd::Error> 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<opus::encoder::Error> 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;
|
||||
@@ -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<BlurayLpcm> {
|
||||
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<Vec<Vec<f32>>> {
|
||||
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<Vec<f32>> {
|
||||
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::<f32>::new()]);
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
|
||||
@@ -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<T> = std::result::Result<T, EncodeError>;
|
||||
|
||||
/// 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<bool> {
|
||||
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<u32> {
|
||||
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<f32> = (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<Polyphase>,
|
||||
/// Buffered input per channel, and how much of it is consumed.
|
||||
input: Vec<Vec<f32>>,
|
||||
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<Encoder> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8>) {
|
||||
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::<f32>() / 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::<f32>() / 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<u8>) {
|
||||
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<ChannelPlan> = 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<usize>,
|
||||
twiddle: Vec<Cpx>,
|
||||
}
|
||||
|
||||
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<Cpx>) {
|
||||
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).
|
||||
|
||||
@@ -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<i16>,
|
||||
/// `cache[0]` = max pseudo-pulses; `cache[k]` = bits(k) - 1 in 1/8 bits.
|
||||
pub cache_bits: Vec<u8>,
|
||||
/// Per-band maximum allocation: `[(2*LM + C-1)*NB_EBANDS + band]`.
|
||||
pub caps: Vec<u8>,
|
||||
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<i16>, Vec<u8>) {
|
||||
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<i32> {
|
||||
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<u8> {
|
||||
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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<f32> = 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::<u32>() == 1 {
|
||||
best = index.iter().sum::<u32>() 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<u64>) {
|
||||
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<u32> {
|
||||
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<Vec<u32>> = 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<u6
|
||||
}
|
||||
let rem = n - j;
|
||||
let t = y[j].unsigned_abs() as usize;
|
||||
let below = row(rem - 1);
|
||||
// Codewords with |y_j| = t start at sum_{m < kk - t} V(rem-1, m) within their sign half.
|
||||
let mut base: u64 = (0..kk - t).map(|m| vv(rem - 1, m)).sum();
|
||||
let mut base: u64 = below[..kk - t].iter().map(|&x| x as u64).sum();
|
||||
if y[j] < 0 {
|
||||
base += (vv(rem - 1, kk) + vv(rem, kk)) / 2;
|
||||
base += (below[kk] as u64 + row(rem)[kk] as u64) / 2;
|
||||
}
|
||||
index += base;
|
||||
kk -= t;
|
||||
@@ -193,7 +266,6 @@ pub struct BandEnc<'m, 'e> {
|
||||
pub i: usize,
|
||||
pub spread: usize,
|
||||
pub remaining_bits: i32,
|
||||
pvq_v: Vec<u64>,
|
||||
iy: Vec<i32>,
|
||||
tmp: Vec<f32>,
|
||||
}
|
||||
@@ -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<f32> = 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<f32> = (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<f32> = (0..32).map(|i| ((i as f32) * 0.7).sin()).collect();
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Loaded 100 of 1630 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user